SpringMVC interceptor and use of JSR303

Table of contents

1. JSR303

2. Interceptor


1. JSR303

1.1.What is JSR303

   JSR 303, which is part of the Java EE (now called Jakarta EE) specification. JSR 303 defines a standard specification for validating Java objects , also known as Bean validation.

        Bean validation is a framework for validating object properties to ensure that the object complies with specific rules and constraints. These rules can include field non-emptiness, length restrictions, format validation, etc. By using Bean Validation, developers can easily define and apply validation rules in their applications to ensure data integrity and consistency.

1.2 Why use JSR-303
        When we develop applications, we often need to verify the data entered by the user to ensure the validity and consistency of the data. For example, we may need to verify that the username in the user registration form meets the requirements, that the password is strong enough, that the email address is valid, etc.

        Before learning this, we all verified through the front-end. If the front-end code verification is not written well or for people who know a little programming, you can directly bypass the front-end and send requests (through testing tools like Postman). Data request), it is unsafe to pass some wrong parameters.

Therefore, we usually do a set of verifications on the front end and another set of verifications on the back end, so that security can be greatly improved.
 

1.3. Commonly used annotations
Annotation Description
@Null is used to verify that the object is null
@NotNull is used when the object cannot be null and cannot check a string with a length of 0
@NotBlank is only used for the String type and cannot be null and the size after trim() >0
@NotEmpty is used for collection classes, String classes cannot be null, and size>0. But strings with spaces cannot be verified.
@Size is used to check whether the length of the object (Array, Collection, Map, String) is within the given range.
@Length is used for the size of the String object must be within the specified range.
@Pattern Used for whether the String object conforms to the rules of the regular expression
@Email Used for whether the String object conforms to the email format
@Min Used for whether the Number and String objects are greater than or equal to the specified value
@Max Used for whether the Number and String objects are less than or equal to the specified value
@ AssertTrue is used to determine whether a Boolean object is true.
@AssertFalse is used to determine whether a Boolean object is false.

1.4 Usage examples 

1Import JSR303 dependencies

<!-- JSR303 -->
<hibernate.validator.version>6.0.7.Final</hibernate.validator.version>
 
<!-- JSR303 -->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>${hibernate.validator.version}</version>
</dependency>

package com.lya.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.validator.constraints.NotBlank;

@Data//相当于set get toString方法
@AllArgsConstructor //有参构造器
@NoArgsConstructor //无参构造器

public class book {

    @NotBlank(message = "书籍编号不能为空")
    private Integer bid;
    @NotBlank(message = "书籍名称不能为空")
    private String bname;
    @NotBlank(message = "书籍价格不能为空")
    private Float price;

    private String pic = "暂未上传图片";


    public Integer getBid() {
        return bid;
    }

    public void setBid(Integer bid) {
        this.bid = bid;
    }

    public String getBname() {
        return bname;
    }

    public void setBname(String bname) {
        this.bname = bname;
    }

    public Float getPrice() {
        return price;
    }

    public void setPrice(Float price) {
        this.price = price;
    }

    public String getPic() {
        return pic;
    }

    public void setPic(String pic) {
        this.pic = pic;
    }

Front-end code:

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>书籍的编辑界面</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/clz/${empty bs ? 'add' : 'edit'}" method="post">
    id:<input type="text" name="bid" value="${bs.bid }"><span style="color: red">${Map.bid}</span><br>
    bname:<input type="text" name="bname" value="${bs.bname }"><span style="color: red">${Map.bid}</span><br>
    price:<input type="text" name="price" value="${bs.price }"><span style="color: red">${Map.bid}</span><br>
    <input type="submit">
</form>
</body>
</html>

1.5 The difference between @Validated and @Valid

@Validated:

Provided by Spring

Support group verification

Can be used on types, methods and method parameters. But it cannot be used on member attributes (fields)

Since it cannot be added to member attributes (fields), cascade verification cannot be completed alone and needs to be coordinated with @Valid

@Valid:

Provided by JDK (standard JSR-303 specification)

Group verification is not supported

Can be used on methods, constructors, method parameters and member properties (fields)

Can be added to member attributes (fields) to complete cascade verification independently

2. Interceptor


 2.1 What is an interceptor?
  SpringMVC's processor interceptor is similar to the filter in Servlet development. It is used to pre-process and post-process the processor as well as request interception and filtering. It relies on the web framework and is based on Java's reflection mechanism in implementation, which is an application of aspect-oriented programming (AOP). Since the interceptor is based on the call of the web framework, Spring's dependency injection (DI) can be used to perform some business operations. At the same time, an interceptor instance can be called multiple times within a controller life cycle.

Interceptors are mainly used to implement the following functions:

Preprocessing operations: The interceptor can perform some preprocessing operations before the request is processed, such as parameter verification, permission verification, request logging, etc. This allows for some unified processing of requests before entering the specific request processing logic.
Post-processing operations: The interceptor can perform some post-processing operations after the request processing is completed, such as unified exception handling, result encapsulation, response logging, etc. This allows for some unified processing of the response after the request processing is completed.
Request interception and filtering: The interceptor can intercept and filter requests, and determine whether to allow the request to continue processing based on certain conditions. For example, interception can be performed based on the user's permissions. If the user does not have permission to access a resource, the request can be intercepted directly and the corresponding error message returned.
 

2.2 The difference between interceptors and filters.   
What is a filter:

        Depends on servlet container. Based on function callbacks in implementation, almost all requests can be filtered, but the disadvantage is that a filter instance can only be called once when the container is initialized. The purpose of using filters is to perform some filtering operations , such as: modifying the character encoding in the filter; modifying some parameters of HttpServletRequest in the filter, including: filtering vulgar text, dangerous characters, etc.

filter

1. Filter belongs to Servlet technology and can be used in any web project.

2.filter is mainly due to filtering all requests

3.The execution time of filter is earlier than Interceptor

interceptor

1.interceptor belongs to SpringMVC technology and must have a SpringMVC environment before it can be used.

2.interceptor usually intercepts the processor Controller

3.interceptor can only intercept requests processed by dispatcherServlet

2.3 Application scenarios and functions of interceptors
Permission verification: Interceptors can be used to verify user permissions, such as checking whether the user is logged in, whether he has permission to access a resource, etc. By intercepting requests and performing permission verification, the security of the system and the integrity of the data can be protected.
Logging: Interceptors can be used to record request and response log information, including requested URL, request parameters, processing time, response results, etc. By recording logs, system monitoring, troubleshooting, and performance optimization can be easily performed.
Parameter preprocessing: The interceptor can preprocess request parameters, such as verifying, converting, modifying, etc. parameters. This ensures the validity and consistency of request parameters and reduces the occurrence of errors and exceptions.
Exception handling: Interceptors can be used to uniformly handle exceptions that occur during the request process. By intercepting exceptions and handling them uniformly, you can provide a friendly error prompt page or return specific error information, improving the system's fault tolerance and user experience.
Cache control: Interceptors can be used to control the use of cache, such as determining whether to use cache based on the requested URL, parameters and other conditions, as well as the cache expiration time, etc. By intercepting requests and performing cache control, you can improve system performance and response speed.
Request redirection: The interceptor can redirect the request according to certain conditions and forward the request to other URLs or processors for processing. By intercepting requests and redirecting them, request forwarding, routing and process control can be achieved.
Unified processing: Interceptors can be used to implement some unified processing logic, such as unified encoding conversion, character set settings, response header settings, etc. for requests. By intercepting requests and processing them uniformly, the consistency and maintainability of the system can be improved.
        Interceptors are widely used in web development. They can intercept, process and modify requests, and implement functions such as permission verification, logging, parameter preprocessing, exception handling, cache control, request redirection and unified processing. By using interceptors, the security, stability, performance, and maintainability of the system can be improved.

2.4 Quick Start

2.4.1 Create interceptor

package com.lya.interceptor;
 
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/*
1. 定义拦截器类,实现HandlerInterceptor接口
2. 注意当前类必须受Spring容器控制
 */
public class OneInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("【OneInterceptor】:preHandle...");
 
        return true;
    }
 
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("【OneInterceptor】:postHandle...");
 
    }
 
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("【OneInterceptor】:afterCompletion...");
    }
}

2.4.2 Configuring interceptors

Configure in spring-mvc.xml:

    <!--配置拦截器-->
    <mvc:interceptors>
        <bean class="com.lya.interceptor.OneInterceptor"></bean>
    </mvc:interceptors>
  • preHandle : used to preprocess intercepted requests. The method receives a return value of Boolean (true, false) type. Returns true: released, false: not released.

    Execution timing: executed before the processor method is executed

    method parameters

    parameter illustrate
    request request object
    response response object
    handler Intercepted method processing

  • postHandle : used to post-process intercepted requests, and can modify model data and views in the method

    Execution timing: after the processor method is executed and before the view is rendered

    method parameters

    parameter illustrate
    request request object
    response response object
    handler Intercepted handler method
    ModelAndView Model and view objects returned by the handler method, the model and view can be modified in the method

  • afterCompletion : used for final processing after the entire process is completed. If there is an exception in the request process, the object can be obtained in the method

    Execution timing: after the view rendering is completed (after the entire process ends)

    method parameters

    parameter illustrate
    request Request parameters
    response response object
    handler Intercepted handler method
    ex exception object

2.5.Interceptor chain

If multiple interceptors can intercept the same request, multiple interceptors will form an interceptor chain. The main purpose is to understand the execution order of each interceptor in the interceptor chain. The execution order of multiple interceptors in the interceptor chain is related to the configuration order of the root interceptor. The one configured first is executed first.

public class TwoInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("【TwoInterceptor】:preHandle...");
​
        return true;
    }
​
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("【TwoInterceptor】:postHandle...");
​
    }
​
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("【TwoInterceptor】:afterCompletion...");
    }
}
    <!-- 多拦截器(拦截器链)-->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="com.lya.interceptor.OneInterceptor"/>
        </mvc:interceptor>
        <mvc:interceptor>
            <mvc:mapping path="/book/**"/>
            <bean class="com.lya.interceptor.TwoInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>

2.6. User login permission case

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("【implements】:preHandle...");
        StringBuffer url = request.getRequestURL();
        if (url.indexOf("/login") > 0 || url.indexOf("/logout") > 0){
            //        如果是 登录、退出 中的一种
            return true;
        }
//            代表不是登录,也不是退出
//            除了登录、退出,其他操作都需要判断是否 session 登录成功过
        String uname = (String) request.getSession().getAttribute("uname");
        if (uname == null || "".equals(uname)){
            response.sendRedirect("/page/login");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

SpringMVC.xml

<mvc:interceptors>
            <bean class="com.lya.interceptor.LoginInterceptor"></bean>
</mvc:interceptors>

LoginController.java

@Controller
public class LoginController {
    @RequestMapping("/login")
    public String login(HttpServletRequest req){
        String uname = req.getParameter("uname");
        HttpSession session = req.getSession();
        if ("zs".equals(uname)){
            session.setAttribute("uname",uname);
        }
        return "redirect:/clz/list";
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest req){
        req.getSession().invalidate();
        return "redirect:/clz/list";
    }
}

Login jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登陆页面</title>
</head>
<body>
<h1>登陆页面</h1>
<form action="/login" method="post">
    用户名:<input name="uname">
    <input type="submit">
</form>
</body>
</html>

Guess you like

Origin blog.csdn.net/m0_73647713/article/details/132840802
Recommended