过滤器——javaWeb三大组件之一

导读:本篇文章讲解 过滤器——javaWeb三大组件之一,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

在这里插入图片描述

通用过滤器(参考版)

MyFirstFilter.java:

package com.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * @author: hy
 * @create: 2022-08-03 11:36:38
 */
///* :过滤针对服务器的所有请求
//@WebFilter(urlPatterns = "/*")
public class MyFirstFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化过滤器...MyFirstFilter...init");
    }

    /**
     * 请求过滤处理
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("请求进入了过滤器MyFirstFilter......");
        //过滤器设置数据
        //servletRequest.setAttribute("aaa",100);
        //统一设置编码
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setContentType("text/html;charset=utf-8");
        //通过过滤器链对象,将请求继续向后传递
        filterChain.doFilter(servletRequest,servletResponse);
        System.out.println("请求离开了过滤器MyFirstFilter......");

    }

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

MySecondFilter.java:

package com.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * @author: hy
 * @create: 2022-08-03 11:51:22
 */
///TestServlet:之过滤针对TestServlet的请求
//@WebFilter("/TestServlet")
public class MySecondFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("请求到达了MySecondFilter...只拦截针对TestServlet的请求....");
        filterChain.doFilter(servletRequest,servletResponse);
        System.out.println("请求离开了MySecondFilter...");
    }
}

TestServlet.java:

package com.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: hy
 * @create: 2022-08-03 11:27:09
 */
@WebServlet(urlPatterns = "/TestServlet")
public class TestServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("请求到达了TestServlet.......");
        Object obj = req.getAttribute("aaa");
        System.out.println("获取的数据:"+obj);
    }
}

test.jsp:

<%--
  Created by IntelliJ IDEA.
  User: henry
  Date: 2022/8/3
  Time: 11:28
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>test页面</h1>
    <%
        System.out.print("请求到达了test页面....");
    %>
</body>
</html>

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <!--用注解方式配置过滤器-->
<!--    <filter>-->
<!--        <filter-name>LoginFilter</filter-name>-->
<!--        <filter-class>com.filter.LoginFilter</filter-class>-->
<!--        <init-param>-->
<!--            <param-name>whiteNames</param-name>-->
<!--            <param-value>/login.jsp,/login,/,/index.jsp</param-value>-->
<!--        </init-param>-->
<!--    </filter>-->
<!--    <filter-mapping>-->
<!--        <filter-name>LoginFilter</filter-name>-->
<!--        <url-pattern>/*</url-pattern>-->
<!--    </filter-mapping>-->
<!--    <filter>-->
<!--        <filter-name>MyFirstFilter</filter-name>-->
<!--        <filter-class>com.filter.MyFirstFilter</filter-class>-->
<!--    </filter>-->

    <!--配置过滤器过滤的请求地址-->
<!--    <filter-mapping>-->
<!--        <filter-name>MyFirstFilter</filter-name>-->
<!--        <url-pattern>/*</url-pattern>-->
<!--    </filter-mapping>-->

</web-app>

编码过滤器

CharacterEncodingFilter.java:

package com.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * 编码过滤器
 * @author: hy
 * @create: 2022-08-03 11:59:16
 */
@WebFilter("/*")
public class CharacterEncodingFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //设置编码
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setContentType("text/html;charset=utf-8");
        //放行请求
        filterChain.doFilter(servletRequest,servletResponse);
    }
}

登录过滤器(以后直接看完整版!参考版被取消!)

LoginFilter.java:

package com.filter;

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

/**
 * @author: hy
 * @create: 2022-08-04 09:28:43
 */
@WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {

    //白名单
    private String[] whiteNames = {"index.jsp","login.jsp","toLogin","login",""};

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //String params = filterConfig.getInitParameter("whiteNames");
        //whiteNames=params.split(",");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //向下转型
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //获取请求路径
        String uri = req.getRequestURI();
        String process = uri.substring(uri.lastIndexOf("/")+1);

        System.out.println("process:"+process);

        //定义变量,记录当前请求的资源是否属于白名单
        boolean isWhiteName = false;

        //判断请求资源是否在白名单内
        for (String s : whiteNames){
            if(process.equals(s)){
                isWhiteName=true;
                break;
            }
        }

        //是白名单内的请求,就直接放行
        if(isWhiteName) {
            //通过过滤器链条对象,将请求向后传递
            filterChain.doFilter(req,resp);
        }else {
            //不是白名单的请求,要校验
            //如果session没有记录,是非法访问,则跳转到登录
            if(req.getSession().getAttribute("userName")==null){
                req.setAttribute("error","请先登录。。。");
                req.getRequestDispatcher("/login.jsp").forward(req,resp);
            }else{
                //如果session有记录,则放行
                filterChain.doFilter(req,resp);
            }
        }
    }
}

LoginServlet.java:

package com.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: hy
 * @create: 2022-08-04 09:18:20
 */
// /LoginServlet/* :登录要处理两个请求 1.显示登录页面 2.进行登录处理
@WebServlet(urlPatterns = "/LoginServlet/*")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求的地址
        String uri = req.getRequestURI();
        String process = uri.substring(uri.lastIndexOf("/")+1);
        switch (process){
            case "toLogin": //跳转到登录
                this.toLogin(req,resp);
                break;
            case "login": //登录处理
                this.login(req,resp);
                break;
        }
    }

    /**
     * 处理登录
     * @param req
     * @param resp
     */
    private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName = req.getParameter("userName");
        String password = req.getParameter("password");
        //登录成功
        if("admin".equals(userName)&&"123456".equals(password)){
            //记录登录信息
            req.getSession().setAttribute("userName",userName);
            //跳转到后台页面
            req.getRequestDispatcher("/admin.jsp").forward(req,resp);
        }else{
            req.setAttribute("error","用户名或密码错误");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }
    }

    /**
     * 跳转到登录
     * @param req
     * @param resp
     */
    private void toLogin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //转发
        req.getRequestDispatcher("/login.jsp").forward(req,resp);
    }
}

index.jsp:

<%--
  Created by IntelliJ IDEA.
  User: henry
  Date: 2022/8/3
  Time: 11:26
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
    <a href="${pageContext.request.contextPath}/LoginServlet/toLogin">登录</a>
  </body>
</html>

login.jsp:

<%--
  Created by IntelliJ IDEA.
  User: henry
  Date: 2022/8/4
  Time: 9:24
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/LoginServlet/login" method="post">
        用户名:
        <input type="text" name="userName"/>
        密码:
        <input type="password" name="password"/>
        <input type="submit" value="登录"/>
        <div style="color:red">${error}</div>
    </form>
</body>
</html>

admin.jsp:

<%--
  Created by IntelliJ IDEA.
  User: henry
  Date: 2022/8/4
  Time: 9:25
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>这是后台页面,有很多机密数据......</h1>
</body>
</html>

1.通用过滤器(完整版)

页面整体结构:
在这里插入图片描述
TestServlet:

package com.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/TestServlet")
public class TestServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("请求到达了MyFirstFilter");
    }
}

test.jsp:

<%--
  Created by IntelliJ IDEA.
  User: 33154
  Date: 2022/8/5
  Time: 16:51
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>Test页面</h1>
    <%
        System.out.print("请求到达了Test页面");
    %>
</body>
</html>

在这里插入图片描述

MyFirstFilter:

package com.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class MyFirstFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化过滤器MyFirstFilter");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("请求进去了过滤器MyFirstFilter");
        filterChain.doFilter(servletRequest,servletResponse);
        System.out.println("请求离开了过滤器MyFirstFilter");
    }

    @Override
    public void destroy() {
        System.out.println("请求摧毁了过滤器MyFirstFilter");
    }


}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
MyFirstFilter:

package com.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class MyFirstFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化过滤器MyFirstFilter");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("请求进去了过滤器MyFirstFilter");
        servletRequest.setAttribute("aaa",100);
        filterChain.doFilter(servletRequest,servletResponse);
        System.out.println("请求离开了过滤器MyFirstFilter");
    }

    @Override
    public void destroy() {
        System.out.println("请求摧毁了过滤器MyFirstFilter");
    }


}

TestServlet:

package com.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/TestServlet")
public class TestServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("请求到达了MyFirstFilter");
        Object obj=req.getAttribute("aaa");
        System.out.println("获得的数据:"+obj);
    }
}

在这里插入图片描述
MyFirstFilter:

package com.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class MyFirstFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化过滤器MyFirstFilter");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("请求进去了过滤器MyFirstFilter");
        //servletRequest.setAttribute("aaa",100);
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setContentType("text.html;charset=utf-8");
        filterChain.doFilter(servletRequest,servletResponse);
        System.out.println("请求离开了过滤器MyFirstFilter");
    }

    @Override
    public void destroy() {
        System.out.println("请求摧毁了过滤器MyFirstFilter");
    }


}

MySecondFilter :

package com.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@WebFilter(urlPatterns = "/TestServlet")
public class MySecondFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("请求到达了 MySecondFilter...只拦截 MySecondFilter请求");
        filterChain.doFilter(servletRequest,servletResponse);
        System.out.println("请求离开");
    }
}

TestServlet:

package com.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/TestServlet")
public class TestServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("请求到达了MyFirstFilter");
//        Object obj=req.getAttribute("aaa");
//        System.out.println("获得的数据:"+obj);
    }
}

// A code block
var foo = 'bar';

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <filter>
        <filter-name>MyFirstFilter</filter-name>
        <filter-class>com.filter.MyFirstFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>MyFirstFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

MyFirstFilter:

package com.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

//@WebFilter(urlPatterns = "/*")
public class MyFirstFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化过滤器MyFirstFilter");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("请求进去了过滤器MyFirstFilter");
        //servletRequest.setAttribute("aaa",100);
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setContentType("text.html;charset=utf-8");
        filterChain.doFilter(servletRequest,servletResponse);
        System.out.println("请求离开了过滤器MyFirstFilter");
    }

    @Override
    public void destroy() {
        System.out.println("请求摧毁了过滤器MyFirstFilter");
    }


}

MySecondFilter:

package com.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

//@WebFilter(urlPatterns = "/TestServlet")
public class MySecondFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("请求到达了 MySecondFilter...只拦截 MySecondFilter请求");
        filterChain.doFilter(servletRequest,servletResponse);
        System.out.println("请求离开");
    }
}

在这里插入图片描述
在这里插入图片描述

2.编码过滤器

在这里插入图片描述

CharacterEncodingFilter:

package com.filter;

import javax.servlet.*;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class CharacterEncodingFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //设置编码
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setContentType("text/html;charset=utf-8");
        //放行请求
        filterChain.doFilter(servletRequest,servletResponse);
    }
}

3.登录过滤器

在这里插入图片描述
运行结果:
在这里插入图片描述
toLogin.jsp:
在这里插入图片描述
正确输入的情况:
在这里插入图片描述
在这里插入图片描述
login.jsp:
在这里插入图片描述
输入错误的情况下:
在这里插入图片描述
在这里插入图片描述
admin.jsp:(因req.getSession().setAttribute(“userName”,userName)😉
在这里插入图片描述
换新的浏览器后:
在这里插入图片描述

代码整体结构:
在这里插入图片描述

避免干扰,将过MyFirstFilter、MySecondFilter滤器注释起来。
CharacterEncodingFilter:

package com.filter;

import javax.servlet.*;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class CharacterEncodingFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //设置编码
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setContentType("text/html;charset=utf-8");
        //放行请求
        filterChain.doFilter(servletRequest,servletResponse);
    }
}

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
<!--    <filter>-->
<!--        <filter-name>MyFirstFilter</filter-name>-->
<!--        <filter-class>com.filter.MyFirstFilter</filter-class>-->
<!--    </filter>-->
<!--    <filter-mapping>-->
<!--        <filter-name>MyFirstFilter</filter-name>-->
<!--        <url-pattern>/*</url-pattern>-->
<!--    </filter-mapping>-->
</web-app>

代码如下:
LoginServlet:

package com.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

// /LoginServlet/* :登录要处理两个请求 1.显示登录页面 2.进行登录处理
@WebServlet(urlPatterns = "/LoginServlet/*")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求的地址
        String uri=req.getRequestURI();
        String process=uri.substring(uri.lastIndexOf("/")+1);
        switch (process){
            case "toLogin": //跳转到登录
                this.toLogin(req,resp);
                break;
            case "login": //登录处理
                this.login(req,resp);
                break;
        };
    }

    /** 【/**+回车】:生成该种注释
     * 处理登录
     * @param req
     * @param resp
     */
    private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取账号密码
        String userName=req.getParameter("userName");
        String password=req.getParameter("password");
        //登录成功
        if("admin".equals(userName)&&"123456".equals(password)){
            //记录登录信息
            req.getSession().setAttribute("userName",userName);
            //跳转到后台页面
            req.getRequestDispatcher("/admin.jsp").forward(req,resp);
        }else {
            //设置错误信息提示
            req.setAttribute("error","用户名或密码错误!");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }
    }

    /**
     * 跳转到登录
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void toLogin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //转发
        req.getRequestDispatcher("/login.jsp").forward(req,resp);
    }
}

LoginFilter:

package com.filter;

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

@WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {
    //白名单
    private String[] whiteNames={"login.jsp","index.jsp","toLogin","login",""};

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //向下转型
        HttpServletRequest req=(HttpServletRequest)servletRequest;
        HttpServletResponse resp=(HttpServletResponse)servletResponse;
        //获取请求路径
        String uri=req.getRequestURI();
        String process=uri.substring(uri.lastIndexOf("/")+1);

        System.out.println("process:"+process);

        //定义变量,记录当前请求的资源是否属于白名单
        boolean isWhiteName=false;

        //判断请求资源是否在白名单内
        for(String s:whiteNames){
            if(process.equals(s)){
                isWhiteName=true;
                break;
            }
        }

        //是白名单内的请求,就直接放行
        if(isWhiteName){
            //通过过滤器链条对象,将请求向后传递
            filterChain.doFilter(req,resp);
        }else {
            //不是白名单的请求,要校验
            //如果session没有记录,是非法访问,则跳转到登录
            if(req.getSession().getAttribute("userName")==null){
                req.setAttribute("error","请先登录。。。");
                req.getRequestDispatcher("/login.jsp").forward(req,resp);
            }else{
                //如果session有记录,则放行
                filterChain.doFilter(req,resp);
            }
        }
    }
}

login.jsp:

<%--
  Created by IntelliJ IDEA.
  User: 33154
  Date: 2022/8/5
  Time: 20:00
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/LoginServlet/login" method="post">
        用户名:
        <input type="text" name="userName" />
        密码:
        <input type="password" name="password" />
        <input type="submit" value="提交"/>
        <div style="color:red">${error}</div>
    </form>
</body>
</html>

admin.jsp:

<%--
  Created by IntelliJ IDEA.
  User: 33154
  Date: 2022/8/5
  Time: 20:17
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>这是后台页面,有重要数据。。。</h1>
</body>
</html>

index.jsp:

<%--
  Created by IntelliJ IDEA.
  User: 33154
  Date: 2022/8/4
  Time: 9:49
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  $END$
  </body>
</html>

// A code block
var foo = 'bar';
// A code block
var foo = 'bar';
// A code block
var foo = 'bar';

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/118075.html

(0)
seven_的头像seven_bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!