首页新闻找找看学习计划

Servlet3.0 过滤器不起作用?

0
[待解决问题]

不适用web.xml,使用注解,@WebFilter不起作用吗?

都不经过过滤器

 dispatcherTypes都写上了,

package com.navitek.crawler.cloud.filter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

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

/**
 * 
 * crawler_cloud com.navitek.crawler.cloud.filter.WebFilter
 * @Description 异步Servlet有时需要一个拦截器,但必须是异步的Filter,否则将会报错: ... 方法开启异步输出,否则MarkWapperedResponse将不起作用
 * @author shaozt
 * @date 2015年12月7日 下午6:06:57  
 * @version  1.0
 */
@WebFilter(dispatcherTypes = { DispatcherType.ASYNC, DispatcherType.ERROR, DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.REQUEST }, urlPatterns = "/", asyncSupported = true)
public class DoFilter implements Filter {
    private String encode = "UTF-8";// 默认UTF-8编码

    public void init(FilterConfig filterConfig) throws ServletException {
        String encoding = filterConfig.getInitParameter("encode");
        if (encoding != null) {
            encode = encoding;
        }
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        System.out.println("-doFilter.requestURI:" + request.getRequestURI());

        // 设置request编码
        request.setCharacterEncoding(encode);
        // 设置相应信息
        response.setContentType("text/html;charset=" + encode);
        response.setCharacterEncoding(encode);

        chain.doFilter(new CharacterEncodingRequest(request), response);
    }

    public void destroy() {

    }

}

/**
 * 对Get方式传递的请求参数进行编码
 */
class CharacterEncodingRequest extends HttpServletRequestWrapper {
    private HttpServletRequest request = null;

    public CharacterEncodingRequest(HttpServletRequest request) {
        super(request);
        this.request = request;
    }

    /**
     * 对参数重新编码
     */
    @Override
    public String getParameter(String name) {
        String value = super.getParameter(name);
        if (value == null)
            return null;
        String method = request.getMethod();
        if ("get".equalsIgnoreCase(method)) {
            try {
                value = new String(value.getBytes("ISO8859-1"), request.getCharacterEncoding());
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return value;
    }

}

 

Inszt的主页 Inszt | 初学一级 | 园豆:151
提问于:2015-12-07 18:44
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册