1.方式一:获取地址栏参数
形式一:@PathVariable
// http://127.0.0.1:8080/user/123/roles/222
@RequestMapping(value = "/user/{userId}/roles/{roleId}", method = RequestMethod.GET)
@ResponseBody
public String hello(@PathVariable("userId") String userId, @PathVariable("roleId") String roleId) {
return "User Id : " + userId + " Role Id : " + roleId;
}
形式二:@RequestParam
// http://127.0.0.1:8080/hello?uname=lisi
@RequestMapping("/hello")
@ResponseBody
//将接收前端uname的值给name
public String hello(@RequestParam("uname") String name) {
return "Hello " + name;
}
形式三:HttpServletRequest
// http://127.0.0.1:8080/hello?name=lisi
@RequestMapping("/hello")
@ResponseBody
public void hello(HttpServletRequest request, HttpServletResponse response) {
String uname = request.getParameter("name");
System.out.println("hello " + uname);
}
2.方式二:获取请求体参数
形式一:使用@RequestBody将 JSON 字符串转为一个对象
@RequestMapping("/hello")
@ResponseBody
public void hello(@RequestBody User user) {
System.out.println("user: " + user.getName() + ", age: " + user.getAge());
}
形式二:key/value
@RequestMapping("/hello")
@ResponseBody
public void hello(HttpServletRequest request, HttpServletResponse response) {
String uname = request.getParameter("name");
System.out.println("hello " + uname);
}
形式三:json
@RequestMapping("/hello")
@ResponseBody
public void hello(HttpServletRequest req) {
try {
ObjectMapper om = new ObjectMapper();
User user = om.readValue(req.getInputStream(), User.class);
System.out.println(user.getName());
System.out.println(user.getAge());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@RequestMapping("/hello")
@ResponseBody
public void hello(HttpServletRequest req) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream()));
String json = reader.readLine();
reader.close();
User user = new ObjectMapper().readValue(json, User.class);
System.out.println("hello " + user.getName() + ", you are " + user.getAge() + " years old.");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
注意这里BufferedReader
的readLine()
方法来读取请求体。这可能会导致问题,因为readLine()
方法会读取一行文本,而不是整个JSON对象。
而不能使用
解决方法是使用StringBuilder
@RequestMapping("/hello")
@ResponseBody
public void hello(HttpServletRequest req) {
try {
StringBuilder sb = new StringBuilder();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream()));
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
String json = sb.toString();
User user = new ObjectMapper().readValue(json, User.class);
System.out.println("hello " + user.getName() + ", you are " + user.getAge() + " years old.");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
3.方式三:获取请求头参数
@RequestMapping("/hello")
@ResponseBody
public void hello(HttpServletRequest req) {
String uname = req.getHeader("name");
System.out.println("hello " + uname);
}
标签:String,SpringMVC,public,几种,uname,user,new,接收,hello
From: https://blog.csdn.net/weixin_52153645/article/details/139809407