使用<context-param>标签初始化的参数是被应用程序中所有的servlet所共享。但是有时候我们需要为某一个特定的servlet配置参数,这个时候我们就需要使用servlet初始化参数。
1、servlet初始化参数,在web.xml中配置
1.1、配置web.xml文件
<servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>webDemo01.HelloServlet</servlet-class> <init-param> <param-name>data</param-name> <param-value>ServletConfig</param-value> </init-param> <init-param> <param-name>server</param-name> <param-value>1.1.1</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/HelloServlet</url-pattern> </servlet-mapping>
1.2、在指定的servlet中获取参数
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取ServletConfig对象 ServletConfig config = this.getServletConfig(); //根据参数名获取参数值 String initParameter1 = config.getInitParameter("data"); String initParameter2 = config.getInitParameter("server"); PrintWriter writer = response.getWriter(); writer.append(initParameter1).append(initParameter2); }
2、使用注解完成servlet初始化参数。
1 @WebServlet( 2 name="HelloServlet02", 3 urlPatterns={"/HelloServlet02"}, 4 initParams={ 5 @WebInitParam(name="data",value="config"), 6 @WebInitParam(name="server",value="2.2.2") 7 }) 8 public class HelloServlet02 extends HttpServlet { 9 private static final long serialVersionUID = 1L; 10 11 public void doGet(HttpServletRequest request, HttpServletResponse response) 12 throws ServletException, IOException { 13 this.doPost(request, response); 14 } 15 16 public void doPost(HttpServletRequest request, HttpServletResponse response) 17 throws ServletException, IOException { 18 ServletConfig config = this.getServletConfig(); 19 String initParameter = config.getInitParameter("data"); 20 String initParameter2 = config.getInitParameter("server"); 21 response.getWriter().append(initParameter).append(initParameter2); 22 }
区别:
1、使用注解完成servlet初始化参数,如果修改了初始化参数,必须重新编译应用程序才能生效
2、将servlet参数添加到部署描述符,修改xml代码并重启应用程序即可使配置生效