Spring Boot请求参数的几种方法,前端后端接口实现方式

一、传参方法

1.直接把请求的参数写在Controller相应的方法的形参中,url中提交的参数需要和Controller方法中的入参名称一致。

@PostMapping(value = "/cron")
public HttpResult<Boolean> verifyCron(String cronExpress) {
    ....
}

若"Content-Type"="application/x-www-form-urlencoded",可用post提交,其他情况不适用post请求。

url请求路径: http://localhost:8090/job/cron?cronExpress=0 0 3 * * ?你好

前端调用方式

request
            .post(`/.../.../cron?cronExpress=${cronExpress}`)
            .set('Content-Type', 'application/x-www-form-urlencoded')

2.通过HttpServletRequest方式,post和get方式都可以。

前端和后端接口参数方式

@PostMapping(value = "/getResult")
    public HttpResult getResult(HttpServletRequest request) {
        Map<String, String[]> paramMap = request.getParameterMap();

前端调用方式

request.post(`/api/service/job/getResult`)
            .set('Content-Type', 'application/x-www-form-urlencoded')
            .send({
                Id : this.state.id,
                status : this.state.chooseState
            })

3.使用bean来处理参数

前端请求方法

//参数
let params = {
            id:values.id,
            branch:values.branch,
            .....
            mailTo: this.state.mailtoSelects.join(",")
}
//请求方式
axios.post(`/service/add`,params).then( res => {
     .......
})

接口

@RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult<Boolean> addJob(@RequestBody SceneJob sceneJob) {

4.通过@PathVariable获取路径中的参数

 @GetMapping(value = "/getAll/{Id}")
    public HttpResult allJob(@PathVariable("Id") long id) {
        .....
    }
request
            .get(`/api/service/job/getAll/${this.state.id}`)

5.通过@RequestParam绑定请求参数到方法入参

当请求参数不存在时会有异常发生,可以通过设置属性required=false解决,@RequestParam(value="username", required=false)

@RequestMapping(value="/add",method=RequestMethod.GET)
    public String add(@RequestParam("name") String name) {
    ...
}

6.用注解 @RequestBody绑定请求参数到方法入参, 用于POST请求

二、@RequestParm和@RequestBody的区别

get请求下,后台接收参数的注解为RequestBody时会报错,在post请求下,后台接收参数的注解为RequestParam时也会报错。

RequestParam注解接收的参数是来自于requestHeader中,即请求头,也就是在url中,RequestBody注解接收的参数则是来自于requestBody中,即请求体中。

如果为get请求时,后台接收参数的注解应该为RequestParam,如果为post请求时,则后台接收参数的注解就是RequestBody。

@RequestParam 获取请求参数的值

@PathVaribale 获取url中的数据

发布了36 篇原创文章 · 获赞 19 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_27182767/article/details/90209943
今日推荐