zl程序教程

您现在的位置是:首页 >  其它

当前栏目

@RequestParam和@RequestBody和@PathVariable注解的区别

区别 注解 RequestBody RequestParam
2023-09-14 09:14:08 时间

@RequestParam使用

@RequestParam把请求参数放到了请求头中

@RequestMapping("/list1")
public String test1(int userId) {
  return "list";
}
@RequestMapping("/list2")
public String test2(@RequestParam int userId) {
  return "list";
}

(1)不加@RequestParam前端的参数名需要和后端控制器的变量名保持一致才能生效

(2)不加@RequestParam参数为非必传,加@RequestParam写法参数为必传。但@RequestParam可以通过@RequestParam(required = false)设置为非必传

(3)@RequestParam可以通过@RequestParam(“userId”)或者@RequestParam(value = “userId”)指定传入的参数名。

(4)@RequestParam可以通过@RequestParam(defaultValue = “0”)指定参数默认值

(5)如果接口除了前端调用还有后端RPC调用,则不能省略@RequestParam,否则RPC会找不到参数报错

(6)访问时:

  • 不加@RequestParam注解:url可带参数也可不带参数,输入 localhost:8080/list1 以及 localhost:8080/list1?userId=xxx 方法都能执行
  • 加@RequestParam注解:url必须带有参数。也就是说你直接输入localhost:8080/list2 会报错,不会执行方法。只能输入localhost:8080/list2?userId=xxx才能执行相应的方法

(7)前端页面如下两种写法:在url地址都会显示 localhost:8080/loan/loan?ptype=2 形式

<a th:href="@{loan/loan?ptype=1}">查看更多优选类产品</a>
<a th:href="@{loan/loan(ptype=2)}">查看更多散标类产品</a>

@RequestBody使用 

@RequestBody 注解则是将 HTTP 请求正文插入方法中,使用适合的 HttpMessageConverter 将请求体写入某个对象。

下面这种data方式将参数放在请求体中,后端需要使用@RequestBody + 实体类来接收。

例如:将请求中的 datas 写入 Person 对象中 

@RequestMapping(value = "person/login")
@ResponseBody
public Person login(@RequestBody Person person) {  // 将请求中的 datas 写入 Person 对象中
  return person;  // 不会被解析为跳转路径,而是直接写入 HTTP 响应正文中
}
function login() {
  var datas = '{"name":"' + $('#name').val() + '","id":"' + $('#id').val() + '","status":"' + $('#status').val() + '"}';
  $.ajax({
    type : 'POST',
    contentType : 'application/json',
    url : "${pageContext.request.contextPath}/person/login",
    processData : false,
    dataType : 'json',
    data : datas,
    success : function(data) {
      alert("id: " + data.id + "name: " + data.name + "status: "+ data.status);
    },
    error : function() {
      alert('Sorry, it is wrong!');
    }
  });
};

@PathVariable使用 

参数获取从请求头中获取,也就是路径中获取

使用 @PathVariable ,将花括号 { } 中的占位符,映射到 fruitId 中。

@Controller
public class Hello05Controller {
    //http://localhost/fruit/20
    @RequestMapping("/fruit/{fruitId}")
    public String edit(@PathVariable("fruitId") Integer fid){
        System.out.println("fid = " + fid);
        return "succ";
    }
}