上下文参数(context-param)
由于init-param是配置在<servlet>标签里的,只能有这个Servlet来读取,因此它不是全局的参数,不能被其他的Servlet读取.
context-param叫做上下文参数,可以被所有的Sevlet读取.上下文标签使用<context-param>配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <context-param>
<param-name>upload folder</param-name>
<param-value>attachment</param-value>
</context-param> <context-param>
<param-name>allowed file type</param-name>
<param-value>.gif, .jpg, .bmp</param-value>
</context-param> <servlet>
<servlet-name>ContextParamServlet</servlet-name>
<servlet-class>com.helloxr.servlet.ContextParamServlet</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>ContextParamServlet</servlet-name>
<url-pattern>/servlet/ContextParamServlet</url-pattern>
</servlet-mapping>
package com.helloxr.servlet; import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class ContextParamServlet extends HttpServlet { private static final long serialVersionUID = 65464645464L; public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setCharacterEncoding("UTF-8");
response.setContentType("text/html"); PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>读取上下文参数</TITLE></HEAD>");
out.println(" <BODY>");
out.println(" <link rel='stylesheet' type='text/css' href='../css/style.css'>");
out.println("<div align=center><br/>");
out.println("<fieldset style='width:90%'><legend>所有的上下文参数</legend><br/>");
ServletContext servletContext = getServletConfig().getServletContext(); String uploadFolder = servletContext.getInitParameter("upload folder");
String allowedFileType = servletContext.getInitParameter("allowed file type"); out.println("<div class='line'>");
out.println(" <div align='left' class='leftDiv'>上传文件夹</div>");
out.println(" <div align='left' class='rightDiv'>" + uploadFolder + "</div>");
out.println("</div>");
out.println("<div class='line'>");
out.println(" <div align='left' class='leftDiv'>实际磁盘路径</div>");
out.println(" <div align='left' class='rightDiv'>" + servletContext.getRealPath(uploadFolder) + "</div>");
out.println("</div>");
out.println("<div class='line'>");
out.println(" <div align='left' class='leftDiv'>允许上传的文件类型</div>");
out.println(" <div align='left' class='rightDiv'>" + allowedFileType + "</div>");
out.println("</div>");
out.println("</fieldset></div>");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
} }
浏览效果: