SpringMVC request and response

request and response

request mapping path

The request mapping path is through the annotation: @RequestMapping

Type: method annotation, class annotation

Location: Above the SpringMVC controller method definition

Function: Set the current controller method request access path, if set on the class, set the current controller method request access path prefix uniformly

Attribute: value (default), request access path, or access path prefix

// 当前控制器添加@ResponseBody注解
@ResponseBody
@RequestMapping("/save")
public String save(){
    
    
  	System.out.println("user save ...");
  	return "{'info':'springmvc'}";
}
// 当前类添加注解, 设置请求访问路径

@Controller
@RequestMapping("/book")
public class BookController {
    
    
    @RequestMapping("/save")
    @ResponseBody
    public String save() {
    
    
        System.out.println("book save...");
        return "{'module': 'book save'}";
    }
}

request parameter

pass common parameters

GET request to pass ordinary parameters: url address to pass parameters, the name of the address parameter is the same as the variable name of the formal parameter, and the parameter can be received by defining the formal parameter

The address parameter name is the same as the formal parameter variable name:

Example request: http://localhost:8080/commonParam?name=chenyq&age=18

@Controller
public class UserController {
    
    
    @RequestMapping("/commonParam")
    @ResponseBody
    public String commonParam(String name, int age) {
    
    
        System.out.println("普通参数传递 name ===> " + name);
        System.out.println("普通参数传递 age ===> " + age);
        return "{'module': 'common param'}";
    }
}

The post request passes ordinary parameters: the form form post requests to pass parameters, the form parameter name is the same as the formal parameter variable name, and the parameter can be received by defining the formal parameter

@Controller
public class UserController {
    
    
    @RequestMapping("/commonParam")
    @ResponseBody
    public String commonParam(String name, int age) {
    
    
        System.out.println("普通参数传递 name ===> " + name);
        System.out.println("普通参数传递 age ===> " + age);
        return "{'module': 'common param'}";
    }
}

When the parameter name passed by the request is inconsistent with the formal parameter variable name, we can also use the @RequestParam annotation to bind the relationship between the request parameter and the formal parameter of the processor method

For example, the parameter name passed by the url address is name, and the formal parameter variable name uses username. We can use annotations to bind name and username

@RequestParam annotation parameters

  • required: whether it is a required parameter
  • defaultValue: parameter default value

Example request: http://localhost:8080/commonParam?name=chenyq&age=18

@Controller
public class UserController {
    
    
    @RequestMapping("/commonParam")
    @ResponseBody
  	// @RequestParam注解绑定地址参数名
    public String commonParam(@RequestParam("name") String username, int age) {
    
    
        System.out.println("普通参数传递 name ===> " + username);
        System.out.println("普通参数传递 age ===> " + age);
        return "{'module': 'common param'}";
    }
}

Post request Chinese garbled processing

Add a filter to the web container and specify a character set, a dedicated character filter is provided in the Spring-web package

public class ServletContainersInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
    
    
  	// post请求乱码处理
    @Override
    protected Filter[] getServletFilters() {
    
    
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("utf-8");
        return new Filter[]{
    
    filter};
    }
  
    protected Class<?>[] getRootConfigClasses() {
    
    
        return new Class[0];
    }

    protected Class<?>[] getServletConfigClasses() {
    
    
        return new Class[]{
    
    SpringMvcConfig.class};
    }

    protected String[] getServletMappings() {
    
    
        return new String[]{
    
    "/"};
    }
}

Pass entity class parameters

POJO parameter: The requested parameter name is the same as the property name of the formal parameter object, and the parameter can be received by defining a POJO type parameter

User entity class

public class User {
    
    
    private String name;
    private int age;
}

It is necessary to ensure that the variable name of the passed parameter is consistent with the object property name

Example request: http://localhost:8080/pojoParam?name=chenyq&age=19

@Controller
public class UserController {
    
    
    @RequestMapping("/pojoParam")
    @ResponseBody
    public String pojoParam(User user) {
    
    
        System.out.println("pojo参数传递 user ===>" + user);
        return "{'module': 'pojo param'}";
    }
}

Nested POJO parameters: POJO objects contain POJO objects

The Address entity class is nested in the User entity class

public class User {
    
    
    private String name;
    private int age;
    private Address address;
}

Address entity class

public class Address {
    
    
    private String province;
    private String city;
}

Nested POJO parameters: The request parameter name is the same as the formal parameter object attribute name, and nested POJO attribute parameters can be received according to the object hierarchy relationship

There is no change in the method, and the parameters of the entity class can still be received

Example request: http://localhost:8080/pojoParam?name=chenyq&age=19&address.province=chongqing&address.city=chongqing

@Controller
public class UserController {
    
    
    @RequestMapping("/pojoParam")
    @ResponseBody
    public String pojoParam(User user) {
    
    
        System.out.println("pojo嵌套参数传递 user ===>" + user);
        return "{'module': 'pojo param'}";
    }
}

pass array parameter

Array parameter: The request parameter name is the same as the attribute name of the formal parameter object and there are multiple request parameters. Define the array type parameter to receive the parameter

For example, what hobbies does the receiving user have: The variable names of multiple parameters in the request address can be received using the same array name

Example request: http://localhost:8080/springmvc_03_request/arrayParam?likes=game&likes=music

For example, parameter 1likes and parameter 2likes can be accepted if they are consistent with the array name of the formal parameter likes

@Controller
public class UserController {
    
    
    @RequestMapping("/arrayParam")
    @ResponseBody
    public String arrayParam(String[] likes) {
    
    
        System.out.println("数组参数传递 likes ===>" + Arrays.toString(likes));
        return "{'module': 'array param'}";
    }
}

Pass collection parameters

The collection saves ordinary parameters: the request parameter name is the same as the formal parameter collection object name and there are multiple request parameters, @RequestParam binds the parameter relationship

Passing collection parameters requires @RequestParam to annotate the binding relationship

Example request: http://localhost:8080/listParam?likes=aaa&likes=bbb

@Controller
public class UserController {
    
    
    @RequestMapping("/listParam")
    @ResponseBody
    public String listParam(@RequestParam List<String> likes) {
    
    
        System.out.println("集合参数传递 likes ===>" + likes);
        return "{'module': 'list param'}";
    }
}

pass JSON parameter

The steps to receive the JSON data in the request are as follows :

Add json data conversion related coordinates

<dependency>
  	<groupId>com.fasterxml.jackson.core</groupId>
  	<artifactId>jackson-databind</artifactId>
  	<version>2.9.0</version>
</dependency>

Enable support for automatic conversion of json data

  • The @EnableWebMvc annotation is powerful. This annotation integrates multiple functions. Only some of them are used here, that is, json data for automatic type conversion.
@Configuration
@ComponentScan("com.chenyq.controller")
@EnableWebMvc
public class SpringMvcConfig {
    
    
}

Set to receive json data

@RequestBody annotation, pass the data contained in the request body to the formal parameter parameter, this annotation can only be used once in a processor method

@Controller
public class UserController {
    
    
    @RequestMapping("/listJsonParam")
    @ResponseBody
    public String listJsonParam(@RequestBody List<String> likes) {
    
    
        System.out.println("集合参数传递 likes ===>" + likes);
        return "{'module': 'json list param'}";
    }
}

Postman settings to send json data (add json data to the request body)

insert image description here

The difference between @RequestBody and @RequestParam :

difference :

@RequestParam is used to receive url address pass parameters, form pass parameters [application/x-www-form-urlencoded]

@RequestBody is used to receive json data [application/json]

Application :

In the later stage of development, the data in json format is mainly sent, and @RequestBody is widely used

If you send data in non-json format, use @RequestParam to receive request parameters

Pass the date parameter

Date type data is based on different formats of the system and is not the same

2088-08-18

2088/08/18

08/18/2088

When receiving formal parameters, you need to use the @DateTimeFormat annotation to set different receiving methods according to different date formats

@DateTimeFormat is written in front of the formal parameters of the controller method, and 属性patternthe date and time data format is set through the date and time format string

Example request: http://localhost:8080/dateParam?date=21/09/2022 22:30:00

@Controller
public class UserController {
    
    
    @RequestMapping("/dateParam")
    @ResponseBody
    public String dateParam(@DateTimeFormat(pattern = "dd/MM/yyyy HH:mm:ss") Date date) {
    
    
        System.out.println("date参数传递 date ===> " + date);
        return "{'module': 'date param'}";
    }
}

response data

Response Page ( Understanding )

Just need to return the string for the page name

@Controller
public class UserController {
    
    
@RequestMapping("/toJumpPage")
public String toJumpPage() {
    
    
    System.out.println("跳转页面");
    return "index.jsp";
}

Response text data ( understand )

@Controller
public class UserController {
    
    
    @RequestMapping("/toText")
    @ResponseBody
    public String toText() {
    
    
        System.out.println("响应文本数据");
        return "response Text";
    }
}

Response to json data-entity class object to json

The json conversion coordinates we configured will automatically convert pojo objects into json data

@Controller
public class UserController {
    
    
    @RequestMapping("/toJson")
    @ResponseBody
    public User toJsonPojo() {
    
    
        System.out.println("返回JSON对象数据");
        // 创建一个User对象并返回
        User user = new User("chenyq", 18);
        return user;
    }
}

Response to json data-object collection to json array

@Controller
public class UserController {
    
    
    @RequestMapping("/toJsonList")
    @ResponseBody
    public List<User> toJsonList() {
    
    
        System.out.println("返回JSON对象集合数据");
        // 创建list集合, 添加User对象并返回
        List<User> list = new ArrayList<User>();
        User user1 = new User("chenyq", 18);
        User user2 = new User("kaisa", 20);
        list.add(user1);
        list.add(user2);
        return list;
    }
}

@ResponseBody annotation: Set the return value of the current controller as the response body, if the return value is a string, return String, if it is an object, convert it to JSON and use it as the response body

Guess you like

Origin blog.csdn.net/m0_71485750/article/details/128016698