level 14
代码
package com.app.filter;
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;
//1:需要在相应请求前对于动作进行干涉
//2:需要在相应请求前对于参数进行干涉
public class EncodingFilter implements Filter {
private String Encoding = "UTF-8";
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest res, ServletResponse rep,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) res;
HttpServletResponse response = (HttpServletResponse) rep;
request.setCharacterEncoding(Encoding);
response.setCharacterEncoding(Encoding);
//request.setAttribute("test", "test");
// 可以在过滤器直接跳转页面
// request.getRequestDispatcher("q.jsp").forward(request, response);
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
String Encoding = filterConfig.getInitParameter("Encoding");
if (Encoding != null) {
this.Encoding = Encoding;
}
}
}
web.xml配置
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>com.app.filter.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>*.do</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
2014年05月29日 02点05分
3