servlet过滤器

创建filter过滤器文件,在doFilter方法写入:

package com.aaa.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("*.do")// 拦截需要进行登陆校验的请求    /home  /addCart.do /myCart.do  /login /reg
public class LoginFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        // 判断是否登陆
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        Object user = req.getSession().getAttribute("user");
        if(user == null){
            //session中没有取到用户信息 证明 没有登录 则跳转到登陆界面
            resp.sendRedirect("/shop/views/login.jsp");
        }else{
            //session中获取到了用户信息 证明 已经登陆 则 放行
            filterChain.doFilter(req,resp);
        }
    }

    @Override
    public void destroy() {

    }
}

此servlet用来判断是否为登陆状态,通过使用@WebFilter(*.do)选择器来选中相应后缀名的相应进行筛选,当然,我们需要在jsp页面和servlet页面搞上相应的后缀才可生效。

--------

 

posted @ 2019-06-27 14:25  织式  阅读(99)  评论(0编辑  收藏  举报