servletContext读取全局参数核心方法
getServletContext().getInitParameter(name);//根据指定的参数名获取参数值
1. 在web.xml中配置全局参数
<?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. 在动态资源servlet里面使用servletcontext读取全局参数代码
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"));
}结果如下:

JSP文件读取web.xml配置参数
<%out.println(request.getServletContext().getAttribute("names"));
out.println(request.getServletContext().getInitParameter("company"));
%>