java Servlet annotation implementation filter

java Servlet annotation implementation filter

What I wrote earlier: This article is related to Token verification. Visitors can go and have a look at my article Implementation of Token of Servlet

How to implement Servlet filter:

1. Configure in xml file
2. Add comments in the file header

First, we should know what a filter is:

java filter: as the name suggests, it is a method that plays the role of filtering in java.
Before a request reaches the servlet, it can be intercepted for logical judgment, and then decide whether to release it to the requested servlet.
You can also intercept the result for logical judgment before a response arrives at the client, and then decide whether to allow it to be returned to the client.

In the implementation of Token in the previous article, we can know that the user does not have a Token for the first login and needs to verify the generation. At the same time, the front end needs to bring the latest Token back to the back end every business request. Next, we use a filter to filter tokens.

1. First, create a new java file, inherit the Filter, and add the @ WebFilter annotation on the file header. The Url here is the request address of the business page, / * can match multiple requests and process them

@WebFilter(urlPatterns = "/recharge/*")
public class Myfilter implements Filter {

If you inherit the Filter interface, you need to implement three methods:

According to the meaning of the word, the doFilter method should be the method for processing filtering

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

    }

    @Override
    public void destroy() {

    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

One thing to note here is: you should understand that this is a business request from the front end, and you need a filter to verify the Token
Simply write a front-end business dopost request:

package com.example.demo.newyears.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:Yun
 * @Date:2022/01/10/10:34
 * @Description:
 **/

@WebServlet(name = "recharge", urlPatterns = "/recharge")
public class Recharge extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (resp.getHeader("Token") != null) {
            resp.getWriter().println(req.getAttribute("id"));
        }
    }
}

Work of the filter: the work of the filter is to get the Token in the request header of the front end and process the Token. Then, it should be noted that there are exceptions to be handled at the back end, because after the filter is processed, the Token obtained at the back end may have been filtered back to the front end by the filter, so the back end needs to handle the exceptions.

The filter code is as follows:

package com.example.demo.newyears.servlet;

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

/**
 * @Author:Yun
 * @Date:2022/01/10/8:52
 * @Description:
 **/
//Block all specified URLs
@WebFilter(urlPatterns = "/recharge/*")
public class Myfilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //If the code format of the return body is set in the filter, there is no need to set it on the business page
        ((HttpServletResponse) servletResponse).setHeader("Content-Type", "application/json;charset=UTF-8");
//        String token = "";
//        if (servletRequest instanceof HttpServletRequest) {
**//Note here, doFilter In method servletRequest,servletResponse and HttpServletRequest Is corresponding to a request**
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        try {
        //This method is shown in the following code snippet
            Token.timethan(req, resp);
        } catch (NullPointerException | ParseException e){
            e.printStackTrace();
        }
        //Verify Token
//        ((HttpServletResponse) servletResponse).setHeader("Token", "xxxxxxxxxxx");
        //Before todo servlet execution
        //Go on, responsibility chain, this sentence is very important
        filterChain.doFilter(servletRequest, servletResponse);
        //Contents of todo servlet
    }
}

Note that servletRequest, servletResponse and HttpServletRequest in the doFilter method correspond to one request, so here you can obtain the parameters in the request and set the parameters you want to pass

Complete source code:

Myfilter.java

package com.example.demo.newyears.servlet;

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

/**
 * @Author:Yun
 * @Date:2022/01/10/8:52
 * @Description:
 **/
//Block all specified URLs
@WebFilter(urlPatterns = "/recharge/*")
public class Myfilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        ((HttpServletResponse) servletResponse).setHeader("Content-Type", "application/json;charset=UTF-8");
//        String token = "";
//        if (servletRequest instanceof HttpServletRequest) {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
//            token = req.getHeader("Token");
//            req.setAttribute("id", 24);
        //setArribute The content of the settings can be obtained in the servlet doget
//        }
        try {
            Token.timethan(req, resp);
        } catch (NullPointerException | ParseException e){
            e.printStackTrace();
        }
        //Verify Token
//        ((HttpServletResponse) servletResponse).setHeader("Token", "xxxxxxxxxxx");

        //todo servlet Before execution
        //Move on, responsibility chain
        filterChain.doFilter(servletRequest, servletResponse);
        //todo servlet Content of
    }
}


Recharge.java

package com.example.demo.newyears.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:Yun
 * @Date:2022/01/10/10:34
 * @Description:
 **/

@WebServlet(name = "recharge", urlPatterns = "/recharge")
public class Recharge extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (resp.getHeader("Token") != null) {
            resp.getWriter().println(req.getAttribute("id"));
        }
    }
}


Token.java

    /**
     * The backend gets the token object of the front-end request header, verifies the identity, and compares the effective time
     *
     * @param req
     * @param resp
     * @return
     * @throws ParseException
     */
    public static void timethan(HttpServletRequest req, HttpServletResponse resp) throws ParseException, IOException {

        //Get the token object
        try {
            String str = Base644.decoding(req.getHeader("Token"));
            //Cut the token into two parts
            //str:"id:1001,status:1,endtime:2022-01-08 19:18:43";fb675266364f697519dac6d1e6ec1da3
            String ahead = str.substring(0, str.indexOf(";"));
            String behind = str.substring(str.indexOf(";") + 1, str.length());

            //Time is truncated from the string
            String ss = ahead.substring(ahead.indexOf("e"), ahead.length());
            String cc = ss.substring(ss.indexOf(":") + 1, ss.length());

            //Convert the time of the string to long data for comparison
            SimpleDateFormat sif = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date data = sif.parse(cc);
            long stime = data.getTime();
            Date date1 = new Date();
            Date dateafter = new Date(date1.getTime());
            long nowtime = dateafter.getTime();
            long differen = stime - nowtime;

            //Resolve the id and status of the current token object
            int id = Integer.parseInt(ahead.substring(ahead.indexOf("i") + 3, ahead.indexOf(",")));
            int status = Integer.parseInt(ahead.substring(ahead.indexOf("s") + 7, ahead.lastIndexOf(",")));

            if (getMd5(ahead).equals(behind)) {
                try {
                    if (differen < 0) {
                        resp.getWriter().println("Please log in again!");
                    } else {
                        resp.getWriter().println("The business processing result requested by the front end has been sent to the back end. Please accept!");
                        //Create a new Token
                        resp.getWriter().println("Token:" + createToken(id, status));
                        resp.setHeader("Token", createToken(id, status));
                        req.setAttribute("id", id);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                resp.getWriter().println("Please log in again!");
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }

    /**
     * Create Token object
     *
     * @param id
     * @param status
     */
    public static String createToken(int id, int status) throws UnsupportedEncodingException {
        SimpleDateFormat sif = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        Date dateafter = new Date(date.getTime() + 300000);
        Object endtime = sif.format(dateafter);
        String json = "id:" + id + ",status:" + status + ",endtime:" + endtime;
        JSONObject jsonObject = new JSONObject();
        String ss = jsonObject.toJSONString(json);
        System.out.println(ss);

        String begin = ss + ";" + getMd5(ss);
        //Call and convert to base64
        return Base644.encoding(begin);
    }

Token.http

GET http://localhost:8080/war/helloworld?name=cc&password=cc123
Accept: application/json;application/json;charset=utf-8

###
POST http://localhost:8080/war/recharge
Content-Type: application/json;charset=utf-8
Token: ImlkOjEwMDEsc3RhdHVzOjEsZW5kdGltZToyMDIyLTAxLTEwIDEyOjAwOjA0IjtkYjE3Y2M4YjJlZWVkZGJjMjhlMDBhMTA0MTdjNTM0OA==

{
  "id": 1001,
  "name": "Mr. Yun",
  "date": [
    {
      "create_time": "2022-01-06"
    }
  ]
}

Finally, please see the renderings:
Login request:

Business request:

That's all for today. If you have any questions, please leave a message or chat with me in private

Keywords: Java Back-end

Added by OopyBoo on Sun, 16 Jan 2022 06:03:18 +0200