servlet 通过读取web.xml获得全局变量

web.xml中数据库连接配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Servelt_ReadingDBFromWebXml</display-name>
<welcome-file-list>
   <welcome-file>index.html</welcome-file>
</welcome-file-list>

<!-- 通过getServletContext().getInitParameter("XX")读取 -->
<context-param>
   <param-name>encoding</param-name>
   <param-value>UTF-8</param-value>
</context-param>

   <!-- 通过getServletConfig().getInitParameter("XX")读取 -->

   <init-param>
 <param-name>encoding</param-name>
   <param-value>UTF-8</param-value>
   </init-param>

</web-app>

Servlet:

package com.bdqn.util;


import java.io.IOException;


import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;


public class EncodingFilter implements Filter{
private String encoding;
@Override
public void destroy() {
}


@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {

}


@Override
public void init(FilterConfig filterConfig) throws ServletException {


encoding = filterConfig.getServletContext().getInitParameter("encoding"); 

}

}


你可能感兴趣的:(servlet,全局变量)