Application of Spring MVC-related annotations—— Part 1

Table of contents

一、@Controller、@RequestMapping

1.1 Sample program

1.2 Test results

2. @RequestParam

2.1 Sample program

2.2 Test results

三、@RequestHeader、@CookieValue

3.1 Sample program

3.2 Test results

四、@SessionAttributes

4.1 Sample program

4.2 Test results

5. @ModelAttribute

5.1 Sample program

5.2 Test results

Related readings of previous columns & articles 

1. Maven series of columns

2. Mybatis series of columns

3. Spring series of columns

4. Spring MVC series of columns 


一、@Controller、@RequestMapping

@Controller: Function: mark the controller and hand over the controller to the Spring container for management.

                        Location: Above Class

@RequestMapping: Function: Set the request path for the controller method
Location: Above the method or class. Used on a class, it means that all controller methods in the class use this address as the parent path.
Attributes:

  1. value/path: request path
  2. method: Specify the request method
  3. params: specifies the request parameters that must be sent
  4. headers: specifies the request headers that the request must contain

1.1 Sample program

package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/c3")
public class MyController3 {
    /**
     * 访问路径为 /c3/annotation1
     * 支持post和get请求
     * 请求时必须带有age参数
     * 请求时必须带有User-agent请求头
     * @param username
     * @return
     */
    @RequestMapping(path = "/annotation1",method = {RequestMethod.GET,RequestMethod.POST},params = {"age"},headers = {"User-agent"})
    public String annotation1(String username){
        System.out.println("annotation1\t"+username);
        return "lyl-HQX";
    }
}

Here it is stipulated that the request parameter must have age, but the method parameter list below does not have age, so let's test whether it has age or no age.

1.2 Test results

If the request path is: http://localhost:8080/c3/annotation1?age=10

The test results are:

But if the request path is:  http://localhost:8080/c3/annotation1?username=10

 You can report an error when you see it, so you really need to take the age parameter

So the request path should be written like this: http://localhost:8080/c3/annotation1?username=10&age=10

You can see that the username 10 is indeed printed. 

2. @RequestParam

Function: Obtain request parameters in the controller method
Position: Before the method parameters
Attributes:

  1. name: Specify the name of the request parameter
  2. defaultValue: set the default value for the parameter
  3. required: Whether the setting is a parameter that must be passed in

2.1 Sample program

// 在控制器方法中获取请求参数
    @RequestMapping("/annotation2")
    public String annotation2(@RequestParam(name = "name",defaultValue = "HQX",required = false) String name){
        System.out.println("annotation2\t"+name);
        return "lyl-HQX";
    }

This annotation is a related attribute for modifying request parameters, so we should be able to have this name attribute or not.

2.2 Test results

When the request path is: http://localhost:8080/c3/annotation2

 The request path does not have this parameter, and the default value of this parameter is HQX, which is output normally

When the request path is: http://localhost:8080/c3/annotation2?name=LYL

 OK, when the request path has this parameter, it will be output according to the parameter value of the request path, and it can be seen that the test is indeed successful. 

三、@RequestHeader、@CookieValue

@RequestHeader

  • Role: Get the request header data in the controller method
  • Position: Before the method parameter

@CookieValue

  • Role: Get Cookie data in the controller method
  • Position: Before the method parameter

3.1 Sample program

/**
     * @RequestHeader
     * 作用:在控制器方法中获取请求头数据
     * 位置:方法参数前
     * @CookieValue
     * 作用:在控制器方法中获取Cookie数据
     * 位置:方法参数前
     */
    // 获取User-Agent请求头和JSESSIONID的Cookie值
    @RequestMapping("/annotation3")
    public String annotation3(@RequestHeader("User-Agent")String userAgent, @CookieValue("JSESSIONID") String jSessionId){
        System.out.print("annotation3\t");
        System.out.println("userAgent: "+userAgent);
        System.out.print("jSessionId: " + jSessionId);
        return "lyl-HQX";
    }

3.2 Test results

Request path: http://localhost:8080/c3/annotation3

 It can be seen that the relevant data of the request header is indeed printed: for example, the windows system, how many bits, the version of the browser, etc. The sessionID is also obtained.

四、@SessionAttributes

Function: store the data in the Model model in the session domain
Location: above the class

4.1 Sample program

package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/c4")
// 将Model模型中name的数据存到session域中
@SessionAttributes("name")
public class MyController4 {
    @RequestMapping("/t1")
    public String t1(Model model){
        // model1中保存name数据
        model.addAttribute("name","LYL");
        return "lyl-HQX";
    }
    @RequestMapping("/t2")
    public String t2(HttpSession session){
        // 从session中获取name数据
        System.out.println(session.getAttribute("name"));
        return "lyl-HQX";
    }
}

4.2 Test results

OK, from the above program we can know that the value of name can only be obtained by visiting /t1 first and then visiting /t2. Direct access to /t2 cannot print out the attribute value of name. Next we test it:

When we first visit /t2:​​​​​​: http://localhost:8080/c4/t2

OK, you can see that it is indeed printing out null,

And the browser has no corresponding value.

Next visit /t1, http://localhost:8080/c4/t1

After adding the value

Visit /t2 again, you can see that the console is indeed printed out. 

 

5. @ModelAttribute

Function 1: Set the specified method to be executed before other methods of the controller
Position: above the method

Function 2: Obtain data from the Model model and assign values ​​to parameters
Position: Before the method parameters

5.1 Sample program

Function 1 sample program:

package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/c5")
public class MyController5 {
    // @ModelAttribute作用1:设置指定方法在控制器其他方法前执行
    @ModelAttribute
    public void before(){
        System.out.println("前置方法");
    }

    @RequestMapping("/t1")
    public String t1(){
        System.out.println("t1");
        return "lyl-HQX";
    }
}

 Function 2 sample program:

package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/c5")
public class MyController5 {
    // @ModelAttribute作用1:设置指定方法在控制器其他方法前执行
    @ModelAttribute
    public void before(Model model){
        System.out.println("前置方法");
        model.addAttribute("name","LYL");
    }

    @RequestMapping("/t1")
    public String t1(@ModelAttribute("name") String name){
        System.out.println(name);
        return "lyl-HQX";
    }
}

5.2 Test results

Function 1 test result: http://localhost:8080/c5/t1

OK, it can be seen that the pre-method has indeed taken effect. 

 Function 2 test results: http://localhost:8080/c5/t1

 OK, you can see that both functions have been successfully executed.

Related readings of previous columns & articles 

     If you don’t know anything about the content of this issue, you can also go to see the content of previous issues. The following is a series of column articles such as Maven and Mybatis carefully crafted by bloggers in the past. Don’t miss it when you pass by! If it is helpful to you, please like it and bookmark it. Among them, some of the Spring columns are being updated, so they cannot be viewed, but they can be viewed after the bloggers have completed all the updates.

1. Maven series of columns

Maven Series Column Maven project development
Maven aggregation development [example detailed explanation --- 5555 words]

2. Mybatis series of columns

Mybatis series column MyBatis entry configuration
Mybatis entry case [super detailed]
MyBatis configuration file - detailed explanation of related tags
Mybatis fuzzy query - three methods of defining parameters and aggregation query, primary key backfill
Mybatis dynamic SQL query -- (attached actual combat case -- 8888 words -- 88 quality points)
Mybatis paging query - four ways to pass parameters
Mybatis first level cache and second level cache (with test method)
Mybatis decomposition query
Mybatis related query [attached actual combat case]
MyBatis annotation development --- realize addition, deletion, modification and dynamic SQL
MyBatis annotation development --- realize custom mapping relationship and associated query

3. Spring series of columns

Spring series column Introduction to getting started with Spring IOC [custom container instance]
IOC uses Spring to implement detailed explanation with examples
The creation method, strategy, destruction timing, life cycle and acquisition method of Spring IOC objects
Introduction to Spring DI and Dependency Injection Method and Dependency Injection Type
Application of Spring IOC-related annotations——Part 1
Application of Spring IOC-related annotations——Part 2
Introduction to Spring AOP and related cases
Annotation, native Spring, and SchemaBased implement AOP in three ways [with detailed case]
Introduction to Spring affairs and related cases
Spring transaction management scheme and transaction manager and transaction control API
Spring transaction related configuration, propagation behavior, isolation level and annotation configuration declarative transaction

4. Spring MVC series of columns 

SpringMVC series column Introduction to Spring MVC with an introductory case
Spring MVC various parameter acquisition and acquisition methods custom type converter and encoding filter
Spring MVC gets parameters and custom parameter type converters and encoding filters
Spring MVC processing response with detailed case explanation
Application of Spring MVC-related annotations—— Part 1

Application of Spring MVC-related annotations - Part 2

Application of Spring MVC-related annotations——Part 2
File upload in multiple situations of Spring MVC
Spring MVC asynchronous upload, cross-server upload and file download
Spring MVC exception handling [single control exception handler, global exception handler, custom exception handler]
Spring MVC interceptors and cross domain requests
SSM integration case [the case of station C explaining the most detailed process]

Guess you like

Origin blog.csdn.net/qq_53317005/article/details/130500872