[Java]Spring/SpringBoot Controller中接收参数整理

2021-03-31 77点热度 1人点赞 0条评论

本篇整理下Spring、SpringBoot的Controller中,获取提交的参数的方式

普通接收get或post的参数(Url Parameter)

如http://www.example.com/test?id=1&cat=xxx

@RequestMapping(value = "/test", method = RequestMethod.GET)
public @ResponseBody String test(@RequestParam(value = "id", required = true) long id,
@RequestParam(value = "cat", defaultValue = "") String cat) {
    return "id="+id+",cat="+cat;
}

使用原生的Servlet对象

Spring的Controller中还可以直接使用HttpServeltRequest, HttpServletResponse, HttpSession对象,也可以使用这些对象, 直接获取原生Servlet的方法来获取参数,或者获取header:

@RequestMapping(value = "/test", method = RequestMethod.GET)
//如果你需要HttpServletRequest就把HttpServletRequest request写上,不需要可以不写,后面还可以继续跟RequestParam参数
public @ResponseBody String test(HttpServletRequest request, HttpServletResponse response, HttpSession session, @RequestParam(value = "id", required = true) long id) {
    // request.getHeader("User-Agent");
    String cat = request.getParameter("cat");
    return "id="+id+",cat="+cat;
}

接收get的路径中的uri

如 http://www.example.com/10001.jpg, 10001是某个用户的ID,Spring需要动态接收用户ID,来产生用户头像图片。可以使用@PathVariable

@RequestMapping(value = "/{id}.jpg", method = RequestMethod.GET, headers = "Accept=image/*", produces = "image/jpg")
public @ResponseBody BufferedImage userImage(@PathVariable("id") String id) {
    //TODO 得到id参数,返回用户头像数据
}

接收前端的提交的Body,使用@RequestBody

@RequestMapping(value = "/test")
public
@ResponseBody
String test(@RequestBody String string) {
    System.out.println(string);
}

接收一个前端JsonObject,收到后转换成Java的Object

Spring自动把前端发送过来的JSON转换成后端定义好的Object

如定义一个User

public class User implements Serializable {
    private Long id;
    @NotBlank(message = "姓名不能为空")
    @Length(max = 100, message = "姓名不能超过100个字")
    private String name;
    @Range(min = 1, max = 200, message = "请填写正确年龄")
    private Integer age;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

前端假设用axios提交,示例:

var user = {id: 1, name: '张三',age: 21}
axios.post('test', Qs.stringify(user))
    .then(function (response) {
        // console.log(response.data)
       
    })
    .catch(function (error) {
       
    });

Controller中接收User:

@RequestMapping(value = "/test")
public
@ResponseBody
String saveUser(@Valid @ModelAttribute("user") User user, BindingResult result) {
    if (result.hasErrors()) {
        // 如果前端提交的User有问题,比如姓名为空(这部分,请看User.java里限制的定义),返回错误给前端
    }
    //TODO 保存User
}

接收整个JSON,直接转成自由的Java(Jackson)

如果使用的是Spring,非SpringBoot,需要在pom.xml中加入jaskson支持:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.12.1</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.12.1</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-joda</artifactId>
    <version>2.12.1</version>
</dependency>

前端提交示例:

var user = {id: 1, name: '张三',age: 21}
axios.post('test', user, {
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(function (response) {
        // console.log(response.data)
       
    })
    .catch(function (error) {
       
    });

后端接收的示例:

@RequestMapping("/test")
publicb @ResponseBody
String saveRegister(@RequestBody JsonNode jsonObject) {
    return "OK";
}

接收前端上传的文件

使用 @RequestParam(value = "file") MultipartFile file

@RequestMapping("/upload")
public
@ResponseBody
String upload(@RequestParam(value = "id", required = true) int id,
                      @RequestParam(value = "file") MultipartFile file) {
    // 可以使用的file的一些方法示例:
    file.getOriginalFilename();//得到文件名
    file.getBytes();//得到文件的bytes
    file.getInputStream();//得到InputStream
    
}

 

admin

这个人很懒,什么都没留下

文章评论

*

code