用过滤器就可以实现,现在web.xml文件中配置好过滤器,自定义个一个过滤器,实现Filter接口,在doFilter中实现自己的过滤逻辑,我这里有个设置所有请求中的字符编码,你可以参考一下:
Java code
web.xml配置如下:
com.wgh.common.SetCharacterEncodingFilter
SetCharacterEncodingFilter过滤器类:
package com.wgh.common;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
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;
public class SetCharacterEncodingFilter implements Filter {
private static String log = "ksURL_log";
private static String web_xml_url;
protected static String defaultEncoding = null;
protected FilterConfig filterConfig = null;
protected boolean ignore = true;
public void destroy() {
this.defaultEncoding = null;
this.filterConfig = null;
this.web_xml_url = null;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (ignore || (request.getCharacterEncoding() == null)) {
String defaultEncoding = selectEncoding(request);
HttpServletRequest req = (HttpServletRequest) request;
if (defaultEncoding != null){
String uri = req.getRequestURI();
String url_suffix = uri.substring(uri.lastIndexOf("/")+1);
request.setCharacterEncoding(defaultEncoding);
}
}
}
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
this.defaultEncoding = filterConfig.getInitParameter("defaultEncoding");
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.defaultEncoding);
}
}
用过滤器就可以实现,现在web.xml文件中配置好过滤器,
自定义个一个过滤器,实现Filter接口,在doFilter中实现自己的过滤逻辑。