1、通过web.xml方式
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <servlet> <servlet-name>Hello07</servlet-name> <servlet-class>com.csdn.servlet.InitParamServlet</servlet-class> <init-param> <param-name>uname</param-name> <param-value>我是服务器</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>Hello07</servlet-name> <url-pattern>/h07</url-pattern> </servlet-mapping> </web-app>
package com.csdn.servlet; import jakarta.servlet.*; import java.io.IOException; public class InitParamServlet extends GenericServlet { private String uname; @Override public void init() throws ServletException { //ServletConfig - 代表当前Servlet的配置信息 ServletConfig config = getServletConfig(); //获取初始化参数 uname = config.getInitParameter("uname"); } @Override public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { System.out.println(uname); } }
2、通过@WebServlet注解方式
package com.csdn.servlet; import jakarta.servlet.*; import jakarta.servlet.annotation.WebInitParam; import jakarta.servlet.annotation.WebServlet; import java.io.IOException; @WebServlet(urlPatterns = "/h07", initParams = { @WebInitParam(name = "uname", value = "我是服务器") }) public class InitParamServlet extends GenericServlet { private String uname; @Override public void init() throws ServletException { //ServletConfig - 代表当前Servlet的配置信息 ServletConfig config = getServletConfig(); //获取初始化参数 uname = config.getInitParameter("uname"); } @Override public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { System.out.println(uname); } }