Source code analysis of the platform for improving students' programming ability overview of source code analysis of the Controller layer and analysis of some annotation mechanisms

Posted by CompuWorld on Fri, 08 Oct 2021 00:47:46 +0200

Project backend structure overview

First, the back-end architecture is based on https://start.spring.io/ Source station IntelliJ IDEA The automatic generation method provided by the plug-in Spring Initializr of the integrated development environment generates the basic structure, and then further module differentiation and detail modification are carried out based on this structure.

Project backend structure generation and analysis

1. Installation   IntelliJ IDEA JAVA integrated development environment, the specific installation process can be referred to IntelliJ IDEA installation steps_ Canghai dawn - CSDN blog_ Idea installation , you can also query by yourself

2. Generate standard Springboot project

Select File - > New - > project in the upper left corner of IDEA

Select Spring Initializr, select the SDK Version (JAVA8 is recommended) and the URL of the initiator service, and then Next

Fill in the basic information of the project and click Next

Select related dependency support. You can select it as needed here. If you don't select it, you can also import MAVEN dependencies later, and then Next

Then wait patiently for project initialization. The interface after initialization is as follows:

The java directory contains all source codes of the project, the resources directory contains static resources, including YML configuration of spring boot project, and the root directory contains pom.xml and other configuration files. The subcontracting structure of the project is as follows:

The project structure is established according to the MVVC mode. In addition to the basic layers such as controller, dao, domain, entity and service, config (configuration class Bean), fliter (filter layer), handler, receiver and util toolkit are added

The above is the main structure of the project back-end, such as layer structure and package structure. Next, this article and subsequent articles will focus on the controller layer and analyze its specific implementation steps and key codes

Project backend Controller layer source code analysis

We take the following part of the code as an example for analysis

@RestController
@RequestMapping("/problemset")
public class ProblemsetController {

    @Autowired
    private ProblemsetService problemsetService;

    @Autowired
    private ProblemService problemService;

    private final Logger log = LoggerFactory.getLogger(ProblemController.class);


    @PostMapping("/getProblemset")
    @PreAuthorize("hasRole('ROLE_COMMON')")
    public ResultEntity getProblemset(@RequestParam("id") int id) {
        try {
            Problemset problemset = problemsetService.getProblemset(id);
            List<Problem> problemList = problemsetService.getProblemList(id);
            problemset.setProblems(problemList);
            return ResultEntity.success("Topic set", problemset);
        } catch (Exception e) {
            log.error("View title set error", e);
            return ResultEntity.error("Error viewing title set, please try again");
        }
    }

}

The controller class is written similar to the general Java class, but it needs spring mvc series @ annotations to implement it

Use the @ RestController annotation above the class declaration

@The RestController annotation is equivalent to the combination of @ Controller + @ResponseBody. The source code is as follows:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
    @AliasFor(
        annotation = Controller.class
    )
 

@The Controller injects the currently decorated class into the SpringBoot IOC container, so that this class is instantiated during the run process of the project where this class is located, and represents that this class is the role of the Controller

@The return value of the ResponseBody representation method is directly written to the Http response body in the specified format, rather than resolved to a jump path. The format conversion is implemented through the method in HttpMessageConverter. Because it is an interface, its implementation class completes the conversion. If the method is required to return json format data rather than jump to the page, you can directly label @ RestController on the class instead of @ ResponseBody in each method

Use the @ RequestMapping("* * *") annotation above the class declaration

@RequestMapping is used to map requests, that is, to specify which URL requests the controller can handle. The source code is as follows:

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping {
    String name() default "";

    @AliasFor("path")
    String[] value() default {};

    @AliasFor("value")
    String[] path() default {};

    RequestMethod[] method() default {};

    String[] params() default {};

    String[] headers() default {};

    String[] consumes() default {};

    String[] produces() default {};
}

There are two properties in @ Target:   ElementType.METHOD   and   ElementType.TYPE  , That is, @ RequestMapping can be used in declarations of methods and classes

You can see that for attributes in the annotation, except the string returned by name(), other methods return arrays, that is, multiple attribute values can be defined. For example, value() and path() can define multiple string values at the same time to receive multiple URL requests

1,  method

method:   Specify the method type of the request, such as GET, POST, PUT, DELETE, etc;

2, consumes,produces

Consumers: specify the submitted content type for processing the request, such as application/json, text/html;

produces:     Specifies the content type to be returned. It is returned only if the (Accept) type in the request header contains the specified type;

3, params,headers

params: Specifies that the request must contain some parameter values of yes before it can be processed by this method.

headers: Specifies that the request must contain some specified header values in order for the method to process the request.

The analysis of other key codes in the controller layer will be updated in succession

Reference articles

[SpringBoot] http @ RestController for requesting comments - short book

@RestController annotation preliminary understanding - qee - blog Park

 @Detailed explanation of requestmapping usage_ Jiangnan rain - CSDN blog_@ requestmapping

@Detailed explanation of RequestMapping_ weixin_30249203 blog - CSDN blog

Topics: Java Spring