当前位置:网站首页>Filter & (login interception)

Filter & (login interception)

2022-07-01 14:57:00 lwj_ 07

Filter: Simply put, it is to set up an interception checkpoint between the client and the server , When it is found that the resources requested by the client or the resources responded by the server to the client are not standardized ( such as : Sensitive characters, etc ) The resource will be blocked

Another function is : You can store some permissions in the interception level  

  One 、Fiter Quick start

Be careful 1: That's the way it works Filter yes javax.servlet Under bag Filter

Be careful 2: as long as Filter The interception path of is /* Then the path resources accessed by the client or the resources responded by the server Will be intercepted first , Then let it go and see the code

  Code demonstration :

 eg: When we don't have Filter When intercepting, we turn on the server access hello.jsp The resource results are as follows :( Access this resource normally )

 eg: When we turn on Filter When the interception does not pass, we open the server access hello.jsp The resource results are as follows :( Suppose we don't release Then it is equivalent to client access hello.jsp Our request was It's intercepted and we won't let it go In other words, we can't get resources )

Be careful : If you don't release it, you don't need to write code   Release requires calling the release method

  Enable server client access hello.jsp resources :

You will find that you can't get the resource data , Because the client's request was intercepted

 eg: When we turn on Filter Intercept At the time of release ( That is to say, the request of the client was intercepted, but we let it go ) The client can get the resources under the corresponding path :

  Enable server client access hello.jsp resources :

Two 、Filter Execute the process

Demonstrate the execution process of the above figure with code :

hello.jsp:

 

  visit hello.jsp Result : If the output 1  2  3 It means that the square will return to Filter Execute the code logic after release in

3、 ... and 、Filter Use details   ( Intercept path configuration & Filter chain )

3.1、 Configuration of interception path

 3.2、 Filter chain

 Filter The priority of the :

 

  Code demonstration filter chain ( See if you follow the first step above . The second step ..... Code execution ):

FilterDemo (Filter1):

 FilterDemo2 (Fiter2):

hello.jsp:

  Turn on server access hello.jsp Looking at the execution results shows that the verification of the above figure is successful :

  Four 、 validate logon

  We have written the login interface :LoginServlet

package com.itheima.web;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // 1、 Receive client user name and password 
            String username =request.getParameter("username");
            String password =request.getParameter("password");

            //  Get checkbox data 
            String remember =request.getParameter("remember");

            // 2、 call service Layer to query 
            UserService userService =new UserService();
            User user =userService.login(username,password);

            // 3、 Determine whether the query has a result 
            if (user != null){
                //  Judge user Not for null It means the login is successful 

                //  Judge whether the user has checked remember me  remember
                //  Here we use :"1".equals(remember)  without remember.equals("1")
                //  To prevent null pointer exceptions   because remember It is possible that the user did not check   by null  Then the comparison will result in a null pointer 
                if ("1".equals(remember)){
                    //  Checked , send out Cookie

                    // 1  establish Cookie object 
                    Cookie c_username =new Cookie("username",username);
                    Cookie c_password =new Cookie("password",password);
                    //  Set up Cookie How long does the data live on the client 
                    c_username.setMaxAge(60*60*24*60);
                    c_password.setMaxAge(60*60*24*60);
                    // 2  send out Cookie
                    response.addCookie(c_username);
                    response.addCookie(c_password);

                }

                // 2.  hold user The queried data is first encapsulated in Session In the domain  ( Data is saved and shared between servers )
                HttpSession httpSession =request.getSession();
                //  Store in Session domain 
                httpSession.setAttribute("user",user);

                // 1. Login successful  ( requirement : Dynamically redirect to MVC Adding, deleting, modifying and querying commodities based on the three-tier structure :SelectAllServlet Query all resources )
                String path =request.getContextPath();
                response.sendRedirect(path+"/selectAllServlet");

            } else {
                //  Login failed 
                //  Save the error message to request In the domain   Forward to login.jsp
                request.setAttribute("login_msg"," Wrong user name or password ");
                //  Jump to the logged in login.jsp page 
                request.getRequestDispatcher("/login.jsp").forward(request,response);
            }

        }
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doGet(request, response);
        }
    }

We can see from the code that we are judging user Not for null The account and password entered by the user are correct , Login successfully , Then at this time, we put the information entered by the user user It's stored in Session domain

So our interceptors only need to get Session In domain user Data to determine user Whether the data is null 、 Not for null It indicates that the login information of the user is correct Then we will release Let users access the resources after login , If null It means that the account and password entered by the user are incorrect Then we will forward to the login page ( Be careful : The first time I got it from the interceptor user The object must be null, Because when the client accesses the path, it will first enter the interceptor path , At this time user The object has not been encapsulated into Session In the domain   

  Interceptor :

When the client accesses the desired resource path The interceptor path is /* So I will enter the interceptor first So this explains the scarlet letter problem above

package com.itheima.web.filter;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 *   Login verification filter 
 */

@WebFilter("/*")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {

        // 1. Judge Session If there user (LoginServlet Query it in login and store it in Session User information in the domain )

        HttpServletRequest req =(HttpServletRequest) request;
        //  Be careful :Session In the call getSession() Methodical request yes HttpServletRequest Under bag request So we need to 
        // Filter Under bag request convert to HttpServletRequest Under bag request
        HttpSession session =req.getSession();
        Object user =session.getAttribute("user");

        //  Judge user Is it null
        if (user != null){
            //  Not for null, It means that the user has logged in 
            //  release 
            chain.doFilter(request, response);
        }
        else {
            //  by null, Indicates that the user is not logged in  ( Go to the login page )
            request.setAttribute("login_msg"," You haven't logged in yet !");
            request.getRequestDispatcher("/login.jsp").forward(req,response);
        }
    }




    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }
}

When we open the server client to access resources :

  So we need to modify the code , When the client accesses is login ( register ) On the page , Put about login ( register ) Resources in the page (css、html etc. ) Show it to the user and release it without being blocked :

package com.itheima.web.filter;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 *   Login verification filter 
 */

@WebFilter("/*")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req =(HttpServletRequest) request;
        //  Be careful :Session In the call getSession() Methodical request yes HttpServletRequest Under bag request So we need to 
        // Filter Under bag request convert to HttpServletRequest Under bag request

        // ! Determine whether the access resource path is related to login registration 
        String[] urls = {"/login.jsp","/register.jsp","/imgs/","/css/","/loginServlet","/registerServlet","/checkCodeServlet"};
        // !  Get the currently accessed resource path 
        String url =req.getRequestURL().toString(); // http://localhost:8089/brand-demo/register.jsp  type 

        // !  Judge 
        for (String u:urls) {   //  Traverse urls The address in the array 
            if (url.contains(u)){   //  If url Contains the traversal u

                //  Included words   It indicates that the user accesses the resource path related to login or registration 
                //  Just let it go 
                chain.doFilter(request, response);
                return;

            }
        }
        // (5 Just judge one by one   After judging and finding that it is not included, continue to execute the code )


        // 1. Judge Session If there user (LoginServlet Query it in login and store it in Session User information in the domain )

        HttpSession session =req.getSession();
        Object user =session.getAttribute("user");

        //  Judge user Is it null
        if (user != null){
            //  Not for null, It means that the user has logged in 
            //  release 
            chain.doFilter(request, response);
        }
        else {
            //  by null, Indicates that the user is not logged in  ( Go to the login page )
            request.setAttribute("login_msg"," You haven't logged in yet !");
            request.getRequestDispatcher("/login.jsp").forward(req,response);
        }
    }




    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }
}

===================== Detailed logical analysis in code ===================

Pay special attention to small details : forward 、 Redirect etc. , As long as you jump to a new page ,URL The address bar will find changes , Then the interceptor will be regarded as a new access request Then it was intercepted Finally decided to let go

Interceptor code :

package com.itheima.web.filter;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 *   Login verification filter 
 */

@WebFilter("/*")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req =(HttpServletRequest) request;
        //  Be careful :Session In the call getSession() Methodical request yes HttpServletRequest Under bag request So we need to 
        // Filter Under bag request convert to HttpServletRequest Under bag request

        // ! Determine whether the access resource path is related to login registration 
        String[] urls = {"/login.jsp","/register.jsp","/imgs/","/css/","/loginServlet","/registerServlet","/checkCodeServlet"};
        // !  Get the currently accessed resource path 
        String url =req.getRequestURL().toString(); // http://localhost:8089/brand-demo/register.jsp  type 

        // !  Judge 
        for (String u:urls) {   //  Traverse urls The address in the array 
            if (url.contains(u)){   //  If url Contains the traversal u

                //  Included words   It indicates that the user accesses the resource path related to login or registration 
                //  Just let it go 
                chain.doFilter(request, response);
                return;    //  End the code   The following code will not be executed 

            }
        }
        // (5 Just judge one by one   After judging and finding that it is not included, continue to execute the code )


        // 1. Judge Session If there user (LoginServlet Query it in login and store it in Session User information in the domain )

        HttpSession session =req.getSession();
        Object user =session.getAttribute("user");

        //  Judge user Is it null
        if (user != null){
            //  Not for null, It means that the user has logged in 
            //  release 
            chain.doFilter(request, response);
        }
        else {
            //  by null, Indicates that the user is not logged in  ( Go to the login page )
            request.setAttribute("login_msg"," You haven't logged in yet !");
            request.getRequestDispatcher("/login.jsp").forward(req,response);
        }
    }




    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }
}

Suppose we access login.jsp Resources under the path :

  We got from the interceptor urls You can see in the array , We let go login.jsp And click login to enter loginServlet Resources under the path We also released ,

Here's a detail : Is that we let in loginServlet Look at the code after the path resource :

We encapsulate the user login information into user The object is encapsulated in Session In the domain , At this time, if the login is successful, we will redirect to selectAllServlet The next path , Be careful : When redirecting, our URL The address bar will find changes , It is equivalent to revisiting , Then it will again be intercepted by the interceptor as a new client request to intercept the requested data , Then decide whether to let go , We found through circular judgment selectAllServlet Not the objects we include , Then it will enter the following code judgment after the cycle user Is it null, Be careful : It's because we were just logging in loginServlet The path has been user Objects are encapsulated in Session In the domain So at this point user Not for null 了 , Our code is released , So we can view the data of all products , And then selectAllServlet Forward under the path resource 、 Redirection and other new URL The address will also be released , because user There's already data

package com.itheima.web;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // 1、 Receive client user name and password 
            String username =request.getParameter("username");
            String password =request.getParameter("password");

            //  Get checkbox data 
            String remember =request.getParameter("remember");

            // 2、 call service Layer to query 
            UserService userService =new UserService();
            User user =userService.login(username,password);

            // 3、 Determine whether the query has a result 
            if (user != null){
                //  Judge user Not for null It means the login is successful 

                //  Judge whether the user has checked remember me  remember
                //  Here we use :"1".equals(remember)  without remember.equals("1")
                //  To prevent null pointer exceptions   because remember It is possible that the user did not check   by null  Then the comparison will result in a null pointer 
                if ("1".equals(remember)){
                    //  Checked , send out Cookie

                    // 1  establish Cookie object 
                    Cookie c_username =new Cookie("username",username);
                    Cookie c_password =new Cookie("password",password);
                    //  Set up Cookie How long does the data live on the client 
                    c_username.setMaxAge(60*60*24*60);
                    c_password.setMaxAge(60*60*24*60);
                    // 2  send out Cookie
                    response.addCookie(c_username);
                    response.addCookie(c_password);

                }

                // 2.  hold user The queried data is first encapsulated in Session In the domain  ( Data is saved and shared between servers )
                HttpSession httpSession =request.getSession();
                //  Store in Session domain 
                httpSession.setAttribute("user",user);

                // 1. Login successful  ( requirement : Dynamically redirect to MVC Adding, deleting, modifying and querying commodities based on the three-tier structure :SelectAllServlet Query all resources )
                String path =request.getContextPath();
                response.sendRedirect(path+"/selectAllServlet");

            } else {
                //  Login failed 
                //  Save the error message to request In the domain   Forward to login.jsp
                request.setAttribute("login_msg"," Wrong user name or password ");
                //  Jump to the logged in login.jsp page 
                request.getRequestDispatcher("/login.jsp").forward(request,response);
            }

        }
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doGet(request, response);
        }
    }

login.jsp:

<%@ page contentType="text/html;charset=UTF-8" isELIgnored="false" language="java" %>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>login</title>
    <link href="css/login.css" rel="stylesheet">
</head>
<body>
<div id="loginDiv" style="height: 350px">
    <form action="/brand-demo/loginServlet" id="form">
        <h1 id="loginMsg">LOGIN IN</h1>
        <div id="errorMsg">${login_msg} ${register_msg}</div>
        <%--
        ${login_msg}  Is that we are LoginServlet After login failure under resource, forward to login Page handle 
         The login page is displayed to the user , And save the forwarding time to request Data in the domain ( Wrong user name or password ) take 
         To be displayed on the login page   ${login_msg}:EL expression   Take the data stored in the domain 

        ${register_msg}  Get is RegisterServlet Resources are encapsulated in request The data in the domain is forwarded 
        ( Registered successfully , Please log in ) Displayed on the login page 
        --%>


        <p>Username:<input id="username" name="username" value="${cookie.username.value}" type="text"></p>

        <p>Password:<input id="password" name="password" value="${cookie.password.value}" type="password"></p>


        <%-- value  The function of is in the check box , Assuming that the check box is selected, the value of the check box is the value Value 
                 here remember It's a check box   When we check   The default value is “1”
        --%>
        <p>Remember:<input id="remember" name="remember" value="1" type="checkbox"></p>
        <div id="subDiv">
            <input type="submit" class="button" value="login up">
            <input type="reset" class="button" value="reset">&nbsp;&nbsp;&nbsp;
            <a href="register.jsp"> There is no account ?</a>
        </div>
    </form>
</div>


</body>

</html>

 

原网站

版权声明
本文为[lwj_ 07]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/182/202207011449147602.html