Technology Sharing

Web backend development - request response

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Table of contents

Preface

ask

Simple parameters

Original method

Spring way

Post request garbled code processing

Entity parameters

Simple Entity Parameters

Complex Entity Parameters

​Edit

Array collection parameters

Array Parameters

​Edit

Collection Parameters

Date parameters

​Edit

Json parameters

​Edit

Passing json data

json array

json object (POJO)

json collection (POJO)

Notice

Path parameters

Request Mapping Path

@RequestMapping

Request Parameters

response

@ResponseBody

Unified response results


Preface

Request: Get request data

Response: Set the response data

BS architecture Browser/Server, browser/server architecture mode, the client only needs a browser, and the application logic and data are stored on the server (Easy maintenance, average experience

CS architecture Client/Server, client/server architecture mode (Development and maintenance is troublesome, but the experience is good

ask

Simple parameters

Original method

Manually obtain through HttpServletRequest

  1. import jakarta.servlet.http.HttpServletRequest;
  2. import org.springframework.web.bind.annotation.RequestMapping;
  3. import org.springframework.web.bind.annotation.RestController;
  4. @RestController
  5. public class RequestController {
  6. @RequestMapping("/SimpleParam")
  7. public String SimpleParam(HttpServletRequest request){ //返回的字符串类型是String
  8. String name=request.getParameter("name");
  9. String age=request.getParameter("age"); //通过这个方法得到字符串类型的
  10. int age1=Integer.parseInt(age); //将年龄进行类型转换
  11. System.out.println(name+":"+age1); //设置返回格式
  12. return "OK";
  13. }
  14. }

Spring way

Simple parameters:The parameter name is the same as the formal parameter variable name, define the formal parameter, that is, receive the parameter

  1. @RestController
  2. public class RequestController {
  3. @RequestMapping("/SimpleParam")
  4. public String SimpleParam(String name,Integer age){
  5. System.out.println(name+":"+age);
  6. return "OK";
  7. }
  8. }

Note that the postman URLs here arehttp://localhost:8080/SimpleParam?name=tom&age=10

The above two are get requests. When it is a post request, you only need to enter the URL in postman.http://localhost:8080/SimpleParam

Post request garbled code processing

If there are Chinese characters in the post, garbled characters will appear in the background, so set the filter in the configuration

Add filters to the web container and specify character sets. The Spring-web package provides dedicated character filters.

  1. public class ServletContainersInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
  2.    protected Class<?>[] getRootConfigClasses() {
  3.        return new Class[0];
  4.   }
  5.    protected Class<?>[] getServletConfigClasses() {
  6.        return new Class[]{SpringMvcConfig.class};
  7.   }
  8.    protected String[] getServletMappings() {
  9.        return new String[]{"/"};
  10.   }
  11.    //乱码处理
  12.    @Override
  13.    protected Filter[] getServletFilters() {
  14.        CharacterEncodingFilter filter = new CharacterEncodingFilter();
  15.        filter.setEncoding("UTF-8");
  16.        return new Filter[]{filter};//如果有多个过滤器,在这里用,隔开
  17.   }
  18. }

Note that this is for post. If Chinese characters are passed in by get, garbled characters will still appear.

If the method parameter name does not match the request parameter name, you can use @RequestParam to complete the mapping

  1. @RestController
  2. public class RequestController {
  3. @RequestMapping("/SimpleParam")
  4. public String SimpleParam(@RequestParam(name="name") String username, Integer age){ //引号中写的是请求参数名
  5. System.out.println(username+":"+age);
  6. return "OK";
  7. }
  8. }

The required attribute in @RequestParam defaults to true, which means that the request parameter must be passed. If it is not passed, an error will be reported. If the parameter is optional (that is, it can be passed or not), you can set the required attribute to false (so that you will not get an error whether you pass it or not)

Entity parameters

Simple Entity Parameters

The request parameter name is the same as the formal parameter attribute name, just define the Pojo to receive it

  1. @RestController
  2. public class SimplePojo {
  3. @RequestMapping("/SimpleParam1")
  4. public String SimplePojo(user user) {
  5. System.out.println(user);
  6. return "yes";
  7. }
  8. }
  1. public class user {
  2. private String name;
  3. private Integer age;
  4. //加getter和setter方法toString
  5. }

The url here ishttp://localhost:8080/SimpleParam1?name=cat&age=29

Complex Entity Parameters

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

  1. public class user {
  2. private String name;
  3. private Integer age;
  4. private Address address;
  5. //加getter和setter和toString
  6. }
  1. public class Address {
  2. private String province;
  3. private String city;
  4. //加getter和setter还有toString
  5. }
  1. @RestController
  2. public class SimplePojo {
  3. @RequestMapping("/ComplexParam1")
  4. public String ComplexParam(user user) {
  5. System.out.println(user);
  6. return "yes";
  7. }
  8. }

Array collection parameters

Array Parameters

The request parameter name is the same as the parameter group name and the request contains multiple, define array type parameters to receive parameters

  1. @RestController
  2. public class SimplePojo {
  3. @RequestMapping("/arrayParam")
  4. public String ArrayParam(String[] hobby) {//在这里建立一个数组,然后后面的名称和传入参数相同
  5. System.out.println(Arrays.toString(hobby));
  6. return "yes";
  7. }
  8. }

Collection Parameters

The request parameter name is the same as the parameter collection name and there are multiple request parameters@RequestParamBinding parameter relationships

  1. @RestController
  2. public class SimplePojo {
  3. @RequestMapping("/listParam")
  4. public String ArrayParam(@RequestParam List<String> hobby) {
  5. System.out.println(hobby);
  6. return "yes";
  7. }
  8. }

Date parameters

Use @DateTimeFormat annotation to complete date parameter format conversion

  1. @RestController
  2. public class SimplePojo {
  3. @RequestMapping("/dateParam")
  4. public String dateParam(@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")LocalDateTime updateTime) {
  5. System.out.println(updateTime);
  6. return "yes";
  7. }
  8. }

  1. //日期参数    
  2. //使用@DateTimeFormat注解设置日期类型数据格式,默认格式yyyy/MM/dd   @RequestMapping("/dataParam")    
  3. @ResponseBody    
  4. public String dataParam(Date date,@DateTimeFormat(pattern="yyyy-MM-dd") Date date1, @DateTimeFormat(pattern="yyyy/MM/dd HH:mm:ss") Date date2){        
  5. System.out.println("参数传递 date ==> "+date);        
  6. System.out.println("参数传递 date1(yyyy-MM-dd) ==> "+date1);        
  7. System.out.println("参数传递 date2(yyyy/MM/dd HH:mm:ss) ==> "+date2);        
  8. return "{'module':'data param'}";   }
  9. }
  10. //@DateTimeFormat是形参注解,用在SpringMVC控制器方法形参前面,用于设定日期时间型数据格式//属性:pattern:日期时间格式字符串

Get Test:

http://localhost:8080/springmvc_04_request_param/dataParam?date=2088/08/08&date1=2088-08-18&date2=2088/08/28 8:08:08

Json parameters

The json parameter key name is the same as the parameter object attribute name. You can define a Pojo type parameter to receive the parameter. You need to use the @RequestBody identifier.

  1. @RestController
  2. public class SimplePojo {
  3. @RequestMapping("/jsonParam")
  4. public String jsonParam(@RequestBody user user) {
  5. System.out.println(user);
  6. return "yes";
  7. }
  8. }
  9. //user这和前面的复杂实体参数一样

Encapsulate json into the user entity class through @requestbody

Passing json data

Import the coordinates first

  1. <dependency>
  2.  <groupId>com.fasterxml.jackson.core</groupId>
  3.  <artifactId>jackson-databind</artifactId>
  4.  <version>2.9.0</version>
  5. </dependency>

Enable support for automatic conversion of Json data

  1. @Configuration
  2. @ComponentScan("com.itheima.controller")
  3. //开启json数据类型自动转换
  4. @EnableWebMvc
  5. public class SpringMvcConfig {
  6. }
json array
   
  1. //集合参数:json格式
  2.    //1.开启json数据格式的自动转换,在配置类中开启@EnableWebMvc
  3.    //2.使用@RequestBody注解将外部传递的json数组数据映射到形参的集合对象中作为数据
  4. //它用来将请求体所包含的数据传递给请求参数,此注解一个处理器方法只能使用一次
  5.    @RequestMapping("/listParamForJson")
  6.    @ResponseBody
  7.    public String listParamForJson(@RequestBody List<String> likes){
  8.        System.out.println("list common(json)参数传递 list ==> "+likes);
  9.        return "{'module':'list common for json param'}";
  10.   }
json object (POJO)
  1. //POJO参数:json格式
  2. //1.开启json数据格式的自动转换,在配置类中开启@EnableWebMvc
  3. //2.使用@RequestBody注解将外部传递的json数据映射到形参的实体类对象中,要求属性名称一一对应
  4. @RequestMapping("/pojoParamForJson")
  5. @ResponseBody
  6. public String pojoParamForJson(@RequestBody User user){
  7.    System.out.println("pojo(json)参数传递 user ==> "+user);
  8.    return "{'module':'pojo for json param'}";
  9. }

When getting a request:

  1. {
  2.    "name":"xixi",
  3.    "age":21,
  4.    "address":{
  5.        "provice":"taiyuan",
  6.        "city":"taiyuan"
  7.   }
  8. }
json collection (POJO)
  1. //集合参数:json格式
  2. //1.开启json数据格式的自动转换,在配置类中开启@EnableWebMvc
  3. //2.使用@RequestBody注解将外部传递的json数组数据映射到形参的保存实体类对象的集合对象中,要求属性名称一一对应
  4. @RequestMapping("/listPojoParamForJson")
  5. @ResponseBody
  6. public String listPojoParamForJson(@RequestBody List<User> list){
  7.    System.out.println("list pojo(json)参数传递 list ==> "+list);
  8.    return "{'module':'list pojo for json param'}";
  9. }

When getting a request:

  1. [{"name":"xixi","age":12},
  2. {"name":"haha","age":21}
  3. ]
Notice

Path parameters

Pass parameters directly through the request URL, use {...} to identify the path parameter, and use @PathVariable to obtain the path parameter

A path parameter

  1. @RestController
  2. public class SimplePojo {
  3. @RequestMapping("/path/{id}")
  4. public String pathParam(@PathVariable Integer id) {
  5. System.out.println(id);
  6. return "yes";
  7. }
  8. }

The url of the postman test ishttp://localhost:8080/path/1

Multiple path parameters

  1. @RestController
  2. public class SimplePojo {
  3. @RequestMapping("/path/{id}/{name}")
  4. public String pathParam(@PathVariable Integer id ,@PathVariable String name) {
  5. System.out.println(id+":"+name);
  6. return "yes";
  7. }
  8. }

The url of the postman test ishttp://localhost:8080/path/1/cat

Request Mapping Path

Problem: The requested paths should be different during development, but if there are identical paths, an error will be reported. I don't know which one should be called. Usually throughSet the module name as the prefix of the request path

@RequestMapping

It is a method annotation and a class annotation.

Place it above the SpringMVC controller method definition

Used to set the controller method request pathIf the current controller method is set on the class, the request access path prefix

  1. @Controller
  2. //设置模块名作为请求路径的前缀
  3. @RequestMapping("/user")
  4. public class UserController {
  5.    //请求路径映射
  6.    @RequestMapping("/save")
  7.    @ResponseBody
  8.    public String save(){
  9.        System.out.println("user save ...");
  10.        return "{'module':'user save'}";
  11.   }
  12.    //请求路径映射
  13.    @RequestMapping("/delete")
  14.    @ResponseBody
  15.    public String delete(){
  16.        System.out.println("user delete ...");
  17.        return "{'module':'user delete'}";
  18.   }
  19. }

Attribute: value (default): request access path. Or access path prefix

Request Parameters

@RequestParam is a parameter annotation, which is located before the SpringMVC controller method parameter definition and is used to bind the relationship between the request parameters and the processor method parameters.

Parameters: required: whether it is a required parameter DefaultValue: the default value of the parameter

response

@ResponseBody

It is method annotation and class annotation

Located on the controller method/class

The function isDirectly respond to the method return value. If the return value type is an entity object/collection, it will be converted to JSON format response

@RestController=@Controller+@ResponseBody

  1. @RestController
  2. public class ResponseController {
  3. @RequestMapping("/hello")
  4. public String hello(){
  5. System.out.println("hello world");
  6. return "hello world~";
  7. }
  8. @RequestMapping("/getAddr")
  9. public Address getAddr(){
  10. Address addr=new Address();
  11. addr.setProvince("山西");
  12. addr.setCity("太原");
  13. return addr;
  14. }
  15. @RequestMapping("/listAddr")
  16. public List<Address> ListAddr(){
  17. List<Address> list=new ArrayList<>();
  18. Address addr=new Address();
  19. addr.setProvince("山西");
  20. addr.setCity("太原");
  21. Address addr2=new Address();
  22. addr2.setProvince("山");
  23. addr2.setCity("太");
  24. list.add(addr);
  25. list.add(addr2);
  26. return list;
  27. }
  28. }

The test is entered in postmanhttp://localhost:8080/listAddrOther similar

Each method exposed to the outside world is called a functional interface (for example, there are three interfaces above), and the path is their access path.

The problem is that their response results are different, and the final analysis result is more troublesome, so the response results need to be unified

Unified response results

  1. public class Result {
  2. private Integer code;
  3. private String msg;
  4. private Object data;
  5. public Result(){
  6. }
  7. public Result(Integer code,String msg,Object data){
  8. this.code=code;
  9. this.msg=msg;
  10. this.data=data;
  11. }
  12. public Integer getCode() {
  13. return code;
  14. }
  15. public void setCode(Integer code) {
  16. this.code = code;
  17. }
  18. public String getMsg() {
  19. return msg;
  20. }
  21. public void setMsg(String msg) {
  22. this.msg = msg;
  23. }
  24. public Object getData() {
  25. return data;
  26. }
  27. public void setData(Object data) {
  28. this.data = data;
  29. }
  30. public static Result success(Object data){
  31. return new Result(1,"success",data);
  32. }
  33. public static Result success(){
  34. return new Result(1,"success",null);
  35. }
  36. public static Result error(String msg){
  37. return new Result(0,msg,null);
  38. }
  39. @Override
  40. public String toString() {
  41. return "Result{" +
  42. "code=" + code +
  43. ", msg='" + msg + ''' +
  44. ", data=" + data +
  45. '}';
  46. }
  47. }
  1. @RestController
  2. public class ResponseController {
  3. @RequestMapping("/hello")
  4. public Result hello(){
  5. System.out.println("hello world");
  6. //return new Result(1,"success","hello world");
  7. return Result.success("hello world~");//需要给前端传送数据
  8. }
  9. @RequestMapping("/getAddr")
  10. public Result getAddr(){
  11. Address addr=new Address();
  12. addr.setProvince("山西");
  13. addr.setCity("太原");
  14. return Result.success(addr);
  15. }
  16. @RequestMapping("/listAddr")
  17. public Result ListAddr(){
  18. List<Address> list=new ArrayList<>();
  19. Address addr=new Address();
  20. addr.setProvince("山西");
  21. addr.setCity("太原");
  22. Address addr2=new Address();
  23. addr2.setProvince("山");
  24. addr2.setCity("太");
  25. list.add(addr);
  26. list.add(addr2);
  27. return Result.success(list);
  28. }
  29. }