day07-SpringBoot接收参数相关注解

SpringBoot接收参数相关注解

1.基本介绍

  1. SpringBoot接收客户端提交数据/参数会使用到相关注解
  2. 详解@PathVariable、@RequestHeader、@ModelAttribute、@RequestParam、@CookieValue、@RequestBody

2.接参数相关注解应用实例

演示各种方式提交数据/参数给服务器,服务器如何使用注解接收

2.1@PathVariable

通过@RequestMapping和@PathVariable,获取映射路径的占位符匹配的参数,并赋给方法形参。

index.html

<a href="/monster/100/king">@PathVariable-路径变量 monster/100/king</a>

ParameterController.java

...
@RestController
public class ParameterController {
 @GetMapping("/monster/{id}/{name}")
 public String pathVariable(@PathVariable("id") Integer id,//单个接收
 @PathVariable("name") String name,
 //使用map可以一次接收多个路径占位符
 @PathVariable Map<String, String> map) {
 System.out.println("id=" + id);
 System.out.println("name=" + name);
 System.out.println("map=" + map);
 return "success";
 }
}

访问超链接,结果后台输出:

id=100
name=king
map={id=100, name=king}

2.2@RequestHeader

@RequestHeader用于将请求的头信息区数据映射到功能处理方法的参数上,@RequestHeader("xxx") 代表获取请求头的xxx属性,xxx不区分大小写。

index.html

<a href="/requestHeader">@RequestHeader-获取HTTP请求头</a>

ParameterController.java

//@RequestHeader("xxx") 代表获取请求头的xxx属性,xxx不区分大小写
//@RequestHeader Map<String,String> header 表示将获取请求头的所有属性,并放入map中
@GetMapping("/requestHeader")
public String requestHeader(@RequestHeader("Host") String host,
 @RequestHeader Map<String, String> header) {
 System.out.println("host=" + host);
 System.out.println("header=" + header);
 return "success";
}

访问超链接,后台输出:

host=localhost:8080
header={host=localhost:8080, user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/110.0, accept=text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8, accept-language=zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2, accept-encoding=gzip, deflate, br, connection=keep-alive, referer=http://localhost:8080/index.html, cookie=Idea-f24e85b1=ae595c67-c988-4ef0-856d-44549b2b2eb7, upgrade-insecure-requests=1, sec-fetch-dest=document, sec-fetch-mode=navigate, sec-fetch-site=same-origin, sec-fetch-user=?1}

2.3@RequestParam

该注解的作用是:把请求中的指定名称的参数传递给控制器中的形参赋值

  1. value / name:请求参数中的名称 (必写参数)
  2. required:请求参数中是否必须提供此参数,默认值是true,true为必须提供
  3. defaultValue:默认值

index.html

<a href="/hi?name=杰克&hobby=羽毛球&hobby=篮球">@RequestParam-获取请求参数</a>

ParameterController.java

也可以使用map接收所有参数值,但是如果有多个相同名称的参数值,只能接收第一个,因为map的key冲突了

@GetMapping("/hi")
public String hi(@RequestParam("name") String username,
 @RequestParam("hobby") List<String> hobbies) {
 System.out.println("username=" + username);
 System.out.println("hobby=" + hobbies);
 return "success";
}

访问超链接,后台输出:

username=杰克
hobby=[羽毛球, 篮球]

2.4@CookieValue

通过@CookieValue注解可以拿到cookie的值,它的属性有:

  1. value:参数名称
  2. required:是否必须
  3. defaultValue:默认值

ParameterController.java

/**
 * 1.value="xxx"表示接收名字为xx的cookie
 * 如果浏览器带有对应的cookie,若后面的参数类型为String,则接收到的是对应的value
 * 若后面的参数类型为Cookie,则接收到的是对应的cookie
 * 2.required = false 表示该值为非必须的,默认是true
 */
@GetMapping("/cookie")
public String cookie(@CookieValue(value = "cookie_key", required = false) String val,
 @CookieValue(value = "username", required = false) Cookie cookie) {
 System.out.println("cookie_value=" + val);
 if (cookie != null) {
 System.out.println("username=" + cookie.getName() + "-" + cookie.getValue());
 }
 return "success";
}

浏览器访问方法路径,如果没有对应的cookie,就会输出null,如果有则输出对应的cookie值:

cookie_value=hello
username=username-king

2.5@RequestBody

@RequestBody接收的参数来自requestBody中,即请求体。一般用于处理非Content-Type: application/x-www-form-urlencoded编码格式的数据,比如:application/jsonapplication/xml等类型的数据。

application/json类型的数据而言,使用注解@RequestBody可以将body里面所有的json数据传到后端,后端再进行解析。

index.html:一般来说,@RequestBody注解一般使用在post请求中,因为前端将json数据放在了请求体中。

<h1>测试@RequestBody获取数据,获取post请求体</h1>
<form action="/save" method="post">
 姓名:<input name="name"/><br/>
 年龄:<input name="age"/><br/>
 <input type="submit" value="提交"/>
</form>

ParameterController.java

@PostMapping("/save")
public String postMethod(@RequestBody String content) {
 System.out.println("content=" + content);
 return "success";
}

浏览器填写表单,提交:

后端输出:content=name=jack&age=25

2.6@RequestAttribute

@RequestAttribute 可以获取request请求域中的数据

index.html

<a href="/login">@RequestAttribute-获取request域属性</a>

RequestController.java

package com.li.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
/**
 * @author 李
 * @version 1.0
 */
@Controller
public class RequestController {
 @GetMapping("/login")
 public String login(HttpServletRequest request) {
 request.setAttribute("user", "Smith");//向request域中添加数据
 return "forward:/ok";//转发到/ok(需要在配置中启用视图解析器)
 }
 @GetMapping("/ok")
 @ResponseBody
 public String ok(@RequestAttribute(value = "user", required = false) String username) {
 //获取到request域中的数据
 System.out.println("username=" + username);
 return "success";
 }
}

浏览器访问超链接 /login,后台输出:

username=Smith

2.7@SessionAttribute

@SessionAttribute用来标注在接口的参数上,参数的值来源于session作用域。

RequestController.java

package com.li.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;
import javax.servlet.http.HttpServletRequest;
/**
 * @author 李
 * @version 1.0
 */
@Controller
public class RequestController {
 @GetMapping("/login")
 public String login(HttpServletRequest request) {
 //向session中添加数据
 request.getSession().setAttribute("website", "https://www.baidu.com");
 return "forward:/ok";//转发到/ok(需要在配置中启用视图解析器)
 }
 @GetMapping("/ok")
 @ResponseBody
 public String ok(@SessionAttribute(value = "website", required = false) String site) {
 //获取session域的数据
 System.out.println("site=" + site);
 return "success";
 }
}

浏览器访问/login,后台输出:

site=https://www.baidu.com

3.复杂参数的使用

3.1基本介绍

  1. 在开发中,SpringBoot在响应客户端请求时也支持复杂参数
  2. Map、Model、Errors/BindingResult、RedirectAttributes、ServletResponse、SessionStatus、UriComponentsBuilder、ServletUriComponentsBuilder、HttpSession
  3. Map、Model数据会被放在request域中
  4. RedirectAttributes重定向携带数据

3.2复杂参数应用实例

说明:演示复杂参数的使用,重点演示Map、Model、ServletResponse

控制器中添加两个方法

//模拟响应一个注册的请求
@GetMapping("/register")
public String register(Map<String, Object> map,
 Model model,
 HttpServletResponse response) {
 //如果有一个注册请求,会将注册数据封装到map或者model中(这里没有写表单,手动添加一下)
 map.put("user", "jack");
 map.put("job", "java后端");
 model.addAttribute("salary", 10000);
 //map和model中的数据会被自动放入到request域中
 
 //演示创建cookie,通过response添加到客户端
 Cookie cookie = new Cookie("email","marry@qq.com");
 response.addCookie(cookie);
 
 return "forward:/registerOk";//请求转发
}
@GetMapping("/registerOk")
@ResponseBody
public String regOk(HttpServletRequest request) {
 System.out.println("user=" + request.getAttribute("user"));
 System.out.println("job=" + request.getAttribute("job"));
 System.out.println("salary=" + request.getAttribute("salary"));
 return "success";
}

浏览器访问register方法,后台输出:

user=jack
job=java后端
salary=10000

为什么map和model中的数据会被自动放入到request域中?

register()方法通过response参数将cookie返回给浏览器:

4.自定义对象参数-自动封装

4.1基本介绍

  1. 在开发中,SpringBoot在响应客户端请求时,也支持自定义对象参数
  2. 完成自动类型转换与格式化
  3. 支持级联封装

4.2应用实例

演示自定义对象参数的使用,完成自动封装,类型转换

save.html

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>save</title>
</head>
<body>
<h1>根据表单数据-自动封装POJO(级联封装)</h1>
<form action="/saveMonster" method="post">
 编号:<input name="id" value=""/><br/>
 姓名:<input name="name" value=""/><br/>
 年龄:<input name="age" value=""/><br/>
 婚否:<input name="isMarried" value=""/><br/>
 生日:<input name="birth" value=""/><br/>
 坐骑名称:<input name="car.name" value=""/><br/>
 坐骑价格:<input name="car.price" value=""/><br/>
 <input type="submit" value="保存"/>
</form>
</body>
</html>

bean/Car.java

package com.li.bean;
import lombok.Data;
/**
 * @author 李
 * @version 1.0
 */
@Data
public class Car {
 private String name;
 private Double price;
}

bean/Monster.java

package com.li.bean;
import lombok.Data;
import java.util.Date;
/**
 * @author 李
 * @version 1.0
 */
@Data
public class Monster {
 private Integer id;
 private String name;
 private Integer age;
 private Boolean isMarried;
 private Date birth;
 private Car car;
}

控制器ParameterController.java添加处理请求

//处理添加Monster的方法
@PostMapping("/saveMonster")
@ResponseBody
public String saveMonster(Monster monster) {
 System.out.println("monster=" + monster);
 return "success";
}

浏览器访问save.html,输入数据点击提交:

后端接收到表单信息,自动封装到对象中(支持级联封装):

monster=Monster(id=10086, name=白骨精, age=567, isMarried=false, birth=Thu Dec 23 00:00:00 CST 1456, car=Car(name=宝马, price=200000.0))
作者:一刀一个小西瓜原文地址:https://www.cnblogs.com/liyuelian/p/17234226.html

%s 个评论

要回复文章请先登录注册