1、配置参数读取的意义:
把参数提取到配置的信息中这样就大大的增加了整个代码的使用性方面后期的代码维护
需要知道, 在这里的参数读取仅仅是读到程序里面。
2、实现代码
package com.bjsxt.servlet;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;public class ParamServlet extends HttpServlet {String enc;String enc2;@Overridepublic void init() throws ServletException {//读取属性文件//读取初始化参数[A]enc= this.getInitParameter("abc");//读取初始化参数[B]enc= this.getServletConfig().getInitParameter("abc");//读取全局参数enc2= this.getServletContext().getInitParameter("enc");System.out.println("初始化参数:"+enc);System.out.println("全局参数:"+enc2);}@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.setContentType("text/html;charset="+enc);}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>-<web-app version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee">-<servlet><servlet-name>a123</servlet-name><servlet-class>com.bjsxt.servlet.MyServlet</servlet-class></servlet>-<servlet-mapping><servlet-name>a123</servlet-name><!--注意:路径之前必须增加 [/]--><url-pattern>/abc</url-pattern></servlet-mapping>-<servlet><servlet-name>doLogin</servlet-name><servlet-class>com.bjsxt.servlet.DoLogin</servlet-class></servlet>-<servlet-mapping><servlet-name>doLogin</servlet-name><url-pattern>/DoLogin</url-pattern></servlet-mapping>-<servlet><servlet-name>lifeServlet</servlet-name><servlet-class>com.bjsxt.servlet.LifeServlet</servlet-class><load-on-startup>0</load-on-startup></servlet>-<servlet-mapping><servlet-name>lifeServlet</servlet-name><url-pattern>/LifeServlet</url-pattern></servlet-mapping>-<servlet><servlet-name>myServlet2</servlet-name><servlet-class>com.bjsxt.servlet.MyServlet2</servlet-class></servlet>-<servlet-mapping><servlet-name>myServlet2</servlet-name><url-pattern>/MyServlet2</url-pattern></servlet-mapping><!--全局参数 可以多个servlet读取-->-<context-param><param-name>enc</param-name><param-value>GBK</param-value></context-param>-<servlet><servlet-name>paramServlet</servlet-name><servlet-class>com.bjsxt.servlet.ParamServlet</servlet-class><!--初始化参数 只在当前的servlet中可以获得读取的-->-<init-param><param-name>abc</param-name><param-value>UTF-8</param-value></init-param></servlet>-<servlet-mapping><servlet-name>paramServlet</servlet-name><url-pattern>/ParamServlet</url-pattern></servlet-mapping></web-app>