Spring 请求响应 学习笔记

qaq

极简地记一下

package com.hxy.controller;

import com.hxy.pojo.User;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

@RestController
public class RequestController {

//    @RequestMapping("/hello")
//    public String hello(HttpServletRequest request) {
//        String name = request.getParameter("name");
//        String ageStr = request.getParameter("age");
//
//        int age = Integer.parseInt(ageStr);
//        System.out.println(name + ": " + age);
//
//        return "OK";
//    }

    
    //required指明参数是否必须
    //RequestParam可以将名称手动映射
    @RequestMapping("/hello")
    public String hello(@RequestParam(name = "name", required = false) String username, Integer age) {
        System.out.println(username + ": " + age);
        return "OK";
    }

    //需要和实体对象的属性名一致
    @RequestMapping("/simplePojo")
    public String simplePojo(User user) {
        System.out.println(user);
        return "OK";
    }

    
    //数组参数:需要请求参数名和形参中数组变量名相同
    @RequestMapping("/arrayParam")
    public String arrayParam(String[] hobby) {
        System.out.println(Arrays.toString(hobby));
        return "OK";
    }

    //集合参数:需要请求参数名与形参中集合变量名相同,并且通过@RequestParam绑定参数关系
    @RequestMapping("/listParam")
    public String arrayParam(@RequestParam List<String> hobby) {
        System.out.println(hobby);
        return "OK";
    }

    //日期参数
    @RequestMapping("/dateParam")
    public String dateParam(@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")LocalDateTime updateTime) {
        System.out.println(updateTime);
        return "OK";
    }

    //键名需要和对象中属性值一致
    @RequestMapping("/jsonParam")
    public String jsonParam(@RequestBody User user) {
        System.out.println(user);
        return "OK";
    }


    @RequestMapping("/path/{id}")
    public String pathParam(@PathVariable Integer id) {
        System.out.println(id);
        return "OK";
    }
    
    @RequestMapping("/path/{id}/{name}")
    public String pathParam2(@PathVariable Integer id, @PathVariable String name) {
        System.out.println(id + ": " + name);
        return "OK";
    }
}

ResponseBody

  • 作用在方法上或类上
  • 可以将方法返回值直接响应,如果返回值类型是 实体对象/集合,将会转换为JSON格式响应
  • @RestController = @Controller + @ResponseBody

统一响应格式

  • 将各式各样的返回值统一

    public class Result {
        //响应码,1表示成功,0表示失败
        private Integer code;
        //提示信息
        private String msg;
        //返回的数据
        private Object data;
        //...
    
        //...
        public static Result success(Object data) {
            return new Result(1, "success", data);
        }
        public static Result success() {
            return new Result(1, "success", null);
        }
        public static Result error(String msg) {
            return new Result(0, msg, null);
        }
    }
img_show