如何获取上下文参数《context-param》


在web.xml中有这样的上下文参数

如何获取上下文参数《context-param》_第1张图片


在servlet中获取

方式一:

@WebServlet("/exer2")
public class Exer2 extends HttpServlet {


protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


//直接使用封装好的方法获取
String sex = getServletContext().getInitParameter("sex");
System.out.println(sex);

}


}

方式二

@WebServlet("/exer2")
public class Exer2 extends HttpServlet {


ServletConfig config;

public void init(ServletConfig config) throws ServletException {
this.config = config; //获取servletConfig对象
super.init(config);
}



protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
获取上下文参数值
String sex = config.getServletContext().getInitParameter("sex");
System.out.println(sex);



}

你可能感兴趣的:(JavaWeb)