如何通过过滤器来实现没有登录则无法访问

首先在web.xml文件中加入

<!-- 过滤器 -->
  <filter>
    <filter-name>loginfilter</filter-name>
    <filter-class>com.organicsalt.filter.LoginFilter</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>loginfilter</filter-name>
    <url-pattern>*.do</url-pattern>
  </filter-mapping>

然后再创建一个filter文件夹,并在里面创建LoginFilter类继承Filter接口
LoginFilter.java

package com.organicsalt.filter;

import com.organicsalt.bean.User;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.logging.LogRecord;

public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException{
        System.out.println("过滤器初始化");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("过滤器执行");

        //1.得到HttpServletRequest
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //2.得到session
        HttpSession session = request.getSession();
        //3.得到User对象
        User user = (User)session.getAttribute("user");
        //4.得到请求路径
        String url = request.getRequestURI();
        //5.判断session是否存在user对象
        if(user == null && url.indexOf("login.do") == -1){
            System.out.println("登录信息不存在");
            response.sendRedirect(request.getContextPath() + "/pages/login.jsp");
        }
        else {
            System.out.println("登录信息已存在");
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {
        System.out.println("过滤器销毁");
    }

}

最后将所有的页面后面加上.do就可以实现过滤器的功能了!

你可能感兴趣的:(暑期实习)