您的位置:首页 > 其它

web.xml配置详解系列一

2014-04-16 12:10 239 查看
http://blog.csdn.net/liaoxiaohua1981/article/details/6771043

格式定义:

[html]
view plaincopy

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>contextConfigLocationValue></param-value>
</context-param>

作用:该元素用来声明应用范围(整个WEB项目)内的上下文初始化参数。

param-name 设定上下文的参数名称。必须是唯一名称

param-value 设定的参数名称的值

初始化过程:

在启动Web项目时,容器(比如Tomcat)会读web.xml配置文件中的两个节点<listener>和<contex-param>。
接着容器会创建一个ServletContext(上下文),应用范围内即整个WEB项目都能使用这个上下文。
接着容器会将读取到<context-param>转化为键值对,并交给ServletContext。
容器创建<listener></listener>中的类实例,即创建监听(备注:listener定义的类可以是自定义的类但必须需要继承ServletContextListener)。
在监听的类中会有一个contextInitialized(ServletContextEvent event)初始化方法,在这个方法中可以通过event.getServletContext().getInitParameter("contextConfigLocation") 来得到context-param 设定的值。在这个类中还必须有一个contextDestroyed(ServletContextEvent event) 销毁方法.用于关闭应用前释放资源,比如说数据库连接的关闭。

得到这个context-param的值之后,你就可以做一些操作了.注意,这个时候你的WEB项目还没有完全启动完成.这个动作会比所有的Servlet都要早。

由上面的初始化过程可知容器对于web.xml的加载过程是context-param >> listener >> fileter >> servlet

如何使用

页面中

${initParam.contextConfigLocation}

Servlet中

String paramValue=getServletContext().getInitParameter("contextConfigLocation")

声明:此内容为整理所得

定义

[html]
view plaincopy

<listener>
<listen-class>com.myapp.MyListener</listen-class>
</listener>

作用

该元素用来注册一个监听器类。可以收到事件什么时候发生以及用什么作为响应的通知。事件监听程序在建立、修改和删除会话或servlet环境时得到通知。常与context-param联合使用。
listen-class 指定监听类,该类继承ServletContextListener 包含初始化方法contextInitialized(ServletContextEvent event) 和 销毁方法contextDestoryed(ServletContextEvent event)
示例:初始化日志配置文件

[html]
view plaincopy

<!--初始化日志配置文件 -->
<listener>
<listener-class>
com.myapp.LogbackConfigListener
</listener-class>
</listener>
<context-param>
<param-name>logbackConfigLocation</param-name>
<param-value>WEB-INF/logback.xml</param-value>
</context-param>

[java]
view plaincopy

/**
*
*/
package com.myapp;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
/**
* @author louisliao
*
*/
public class LogbackConfigListener implements ServletContextListener {

private static final Logger logger = LoggerFactory.getLogger(LogbackConfigListener.class);
private static final String CONFIG_LOCATION = "logbackConfigLocation";
/* (non-Javadoc)
* @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
*/
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub

}

/* (non-Javadoc)
* @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
*/
public void contextInitialized(ServletContextEvent event) {
// TODO Auto-generated method stub
String logbackConfigLocation = event.getServletContext().getInitParameter(CONFIG_LOCATION);
String fn = event.getServletContext().getRealPath(logbackConfigLocation);
try {
LoggerContext loggerContext = (LoggerContext)LoggerFactory.getILoggerFactory();
loggerContext.reset();
JoranConfigurator joranConfigurator = new JoranConfigurator();
joranConfigurator.setContext(loggerContext);
joranConfigurator.doConfigure(fn);
logger.debug("loaded slf4j configure file from {}", fn);
}
catch (JoranException e) {
logger.error("can loading slf4j configure file from " + fn, e);
}

}

}

定义

[html]
view plaincopy

<pre class="html" name="code"><filter>
<filter-name>encodingfilter</filter-name>
<filter-class>com.my.app.EncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingfilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping></pre><br>
<pre></pre>
<pre></pre>

作用

用于指定WEB容器的过滤器,在请求和响应对象在Servlet处理之前和之后,可以通过此过滤器对这两个对象进行处理。

备注

filter-class 中指定的过滤器类须继承 javax.servlet.Filter 具有须有以下三种方法

init(FilterConfig filterConfig):初始化;一般情况下时读取配置文件中的init-param参数值 如 filterConfig.getInitParameter("encoding")

doFilter(...):用于对request,response进行处理,并能过chain.doFilter(...) 交过下一个控制器

destroy():资源销毁

示例:如编码过滤器

web.xml配置

[html]
view plaincopy

<filter>
<filter-name>encodingfilter</filter-name>
<filter-class>com.my.app.EncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingfilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

Java 代码

[java]
view plaincopy

/**
*
*/
package com.myapp;

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;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @author louisliao
*
*/
public class EncodingFilter implements Filter {

/**
* 配置中默认的字符编码
*/
protected String encoding = null;
protected FilterConfig filterConfig;
/**
* 当没有指定默认编码时是否允许跳过过滤
*/
protected boolean ignore = true;
/**
*
*/
public EncodingFilter() {
// TODO Auto-generated constructor stub
}

/* (non-Javadoc)
* @see javax.servlet.Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
this.encoding=null;
this.filterConfig=null;
}

/* (non-Javadoc)
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest hRequest=(HttpServletRequest)request;
HttpServletResponse hResponse=(HttpServletResponse)response;
//Conditionally select and set the character encoding to be used
if(ignore || hRequest.getCharacterEncoding()==null){
String coding=selectEncoding(hRequest);
if(coding!=null){
hRequest.setCharacterEncoding(coding);
hResponse.setCharacterEncoding(coding);
}
}
//将控制器传向下一个filter
chain.doFilter(hRequest, hResponse);

}

/* (non-Javadoc)
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
this.filterConfig=filterConfig;
this.encoding=filterConfig.getInitParameter("encoding");
System.out.println(this.encoding);
String value = filterConfig.getInitParameter("ignore");
if (value == null) {
this.ignore = true;
} else if (value.equalsIgnoreCase("true")) {
this.ignore = true;
} else if (value.equalsIgnoreCase("yes")) {
this.ignore = true;
} else {
this.ignore = false;
}
}
protected String selectEncoding(ServletRequest request) {
return (this.encoding);
}

}
init方法是在WEB应用启动就会调用,doFilter则是在访问filter-mapping映射到的url时会调用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: