配置过滤器- package com.tan.web.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;
- /**
- * 过滤整个应用的编码
- * @author Administrator
- *
- */
- public class CharsetEncodingFilter implements Filter {
- private String encoding="utf-8";
-
- public void init(FilterConfig filterConfig) throws ServletException {
- //读取filter配置参数信息
- String en= filterConfig.getInitParameter("encoding");
- if(en != null && ! "" .equals(en)){
- this.encoding=en;
- }
- }
-
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
- if(request.getCharacterEncoding()==null){
- request.setCharacterEncoding(encoding);
- }
- response.setContentType("text/html;charset="+this.encoding);
- response.setCharacterEncoding(encoding);
- chain.doFilter(request, response);
- }
-
- public void destroy() {
- // TODO Auto-generated method stub
- }
- }
复制代码 在Web.xml文件中配置- <!-- 配置过滤器 -->
-
- <filter>
- <filter-name>CharsetEncodingFilter</filter-name>
- <filter-class>com.tan.filter.CharsetEncodingFilter</filter-class>
- <init-param>
- <param-name>encoding</param-name>
- <param-value>UTF-8</param-value>
- </init-param>
-
- </filter>
复制代码 这样就没有乱码了。代码很简单。 |