日期:2014-05-16  浏览次数:20711 次

一个非常优秀的AJAX中文问题解决过滤器

代码如下:

?

public class AjaxEncodeFilter extends HttpServlet implements Filter {

        /**
     * AJAX使用中的字符过滤器,解决中文问题
     */
    private static final long serialVersionUID = 1L;

        public void doFilter(ServletRequest servletRequest,  
                          ServletResponse servletResponse, FilterChain filterChain)  
                          throws IOException, ServletException {  
                    /*  if (logger.isDebugEnabled()) {  
                        logger.debug("doFilter(ServletRequest, ServletResponse, FilterChain) - start"); //$NON-NLS-1$  
                     }  */
              
                     HttpServletRequest request = (HttpServletRequest) servletRequest;  
                     HttpServletResponse response = (HttpServletResponse) servletResponse;  
              
                  String requestedWith = request.getHeader("x-requested-with");  
                    String type = request.getContentType();  
                   if (requestedWith != null && "XMLHttpRequest".equals(requestedWith)  
                           && null != type  
                            && "application/x-www-form-urlencoded".equals(type)) {  
                         // logger.info("This's ajax post.set encode is UTF-8.");  
                        request.setCharacterEncoding("UTF-8");  
                           response.setCharacterEncoding("UTF-8");  
                          request.getParameterMap();  
                     }  
               
                     filterChain.doFilter(request, response);  
              
                 /*  if (logger.isDebugEnabled()) {  
                         logger.debug("doFilter(ServletRequest, ServletResponse, FilterChain) - end"); //$NON-NLS-1$  
                       }  */
                  }

        public void init(FilterConfig arg0) throws ServletException {
            // TODO Auto-generated method stub
            
        }  
}

?