Servlet Filter 过滤器

Posted zkzk945

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Servlet Filter 过滤器相关的知识,希望对你有一定的参考价值。

1.编码转换

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // TODO Auto-generated method stub
        // place your code here

        if(!charEncoding.equals(request.getCharacterEncoding()))
        {
            request.setCharacterEncoding(charEncoding);
        }
        
        response.setCharacterEncoding(charEncoding);
        
        // pass the request along the filter chain
        chain.doFilter(request, response);
    }

2.权限校验过滤

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // TODO Auto-generated method stub
        // place your code here

        HttpServletRequest req=(HttpServletRequest)request;
        HttpServletResponse res = (HttpServletResponse)response;
        
        String servletPath = req.getServletPath();
        
        System.out.println("servletPath " + servletPath);
        
        HttpSession session = req.getSession();
        String flag = (String)session.getAttribute("flag");
        
        if(servletPath != null &&
                (servletPath.equals("/21/login.jsp") ||
                        (servletPath.equals("/21/index.jsp")) ||
//                        servletPath.equals("/21/hello.jsp") ||
                        (servletPath.equals("/21/LoginServerlet21"))
                        ))
        {
            chain.doFilter(request, response);
        }else
        {
            if(flag != null && flag.equals("login_success"))
            {
                chain.doFilter(request, response);
            }
            else if(flag != null && flag.equals("login_error"))
            {
                req.setAttribute("msg", "登陆失败,请重新登陆!!!!<br />");
                req.setAttribute("return_uri", servletPath);
                RequestDispatcher rd = req.getRequestDispatcher("/21/login.jsp");
                rd.forward(req, res);
            }
            else
            {
                req.setAttribute("msg", "你尚未登陆");
                req.setAttribute("return_uri", servletPath);
                RequestDispatcher rd = req.getRequestDispatcher("/21/login.jsp");
                rd.forward(req, res);
            }
        }

3.源码

  https://git.oschina.net/zkzk945/JavaEE.git

以上是关于Servlet Filter 过滤器的主要内容,如果未能解决你的问题,请参考以下文章

servlet 过滤器(Filter)

javaweb-Servlet过滤器Filter

Servlet3.0学习总结——使用注解标注过滤器(Filter)

spring使用servlet过滤器filter,进行登录校验

JAVA过滤器的使用(Filter)

05-JavaWeb的三大组件:小程序Servlet+过滤器Filter+监听器Listener