如何用过滤器拦截未登录直接访问资源页面

如何用过滤器拦截未登录直接访问资源页面

登录界面 login.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Titletitle>
head>
<body>
    <form action="login" method="post">
        用户名:<input type="text" name="username"><br>
        密码:<input type="password" name="password"><br>
        <input type="submit" value="提交"><br>
    form>
body>
html>

登录成功后页面 index.jsp:

<body>
    欢迎${msg}到来!
body>

登录servlet:

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
     
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     
        //获得用户信息
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //验证用户
        if("yang".equals(username) && "123".equals(password)){
     
            req.getSession().setAttribute("username",username);
            resp.sendRedirect("index.jsp");
            return;
        }
        //登录失败 跳转到登录页面
        resp.sendRedirect("login.jsp");
    }
}

过滤器:

@WebFilter("/*")
public class MyFilter implements Filter {
     
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
     }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
     
        //向下转型
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        //获得请求uri
        String requestURI = request.getRequestURI();
        System.out.println(requestURI);
        //判断请求是否为登录请求  是则放行
        if("/login.jsp".equals(requestURI) || "/login".equals(requestURI)){
     
            System.out.println("ok");
            filterChain.doFilter(request,response);
            return;
        }
        //获得session域中username
        Object username = request.getSession().getAttribute("username");
        //判断是否有用户名 没有就跳回登录页面
        if(username==null){
     
            response.sendRedirect("login.jsp");
            return;
        }
        //放行
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {
     }
}

你可能感兴趣的:(Java基础学习,session,servlet,过滤器)