servletContext讀取全局參數(shù)核心方法
getServletContext().getInitParameter(name);//根據(jù)指定的參數(shù)名獲取參數(shù)值
1. 在web.xml中配置全局參數(shù)
<?xml version="1.0" encoding="UTF-8"?> <web-app version="4.0" 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"> <context-param> <param-name>company</param-name> <param-value>南昌雅騰</param-value> </context-param> </web-app>
2. 在動態(tài)資源servlet里面使用servletcontext讀取全局參數(shù)代碼
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //response.getWriter().append("Served at: ").append(request.getContextPath()); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); ServletContext context = request.getServletContext(); out.println(context.getInitParameter("company")); context.setAttribute("names", "莊子"); //同時可以設置屬性 out.println(context.getAttribute("names")); }
結(jié)果如下:
JSP文件讀取web.xml配置參數(shù)
<%out.println(request.getServletContext().getAttribute("names")); out.println(request.getServletContext().getInitParameter("company")); %>