首页 > 文章列表 > SpringBoot接收参数使用的注解是什么

SpringBoot接收参数使用的注解是什么

springboot
149 2023-05-20

SpringBoot接收参数使用的注解是什么

1.基本介绍

SpringBoot 接收客户端提交数据/参数会使用到相关注解

详 解 @PathVariable 、 @RequestHeader 、 @ModelAttribute 、 @RequestParam 、 @MatrixVariable、@CookieValue、@RequestBody

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

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

2.应用实例演示

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

创建src\main\resources\static\index.html

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>index</title>

</head>

<body>

<h2>hello, llp</h2>

基本注解:

<hr/>

<a href="/monster/200/jack" rel="external nofollow" >@PathVariable-路径变量 monster/200/jack</a><br/><br/>

</body>

</html>

@PathVariable 使用

演示@PathVariable 使用,创建src\main\java\com\llp\springboot\controller\ParameterController.java, 完成测试

@RestController

public class ParameterController {

    /**

     * /monster/{id}/{name} 解读

     * 1. /monster/{id}/{name} 构成完整请求路径

     * 2. {id} {name} 就是占位变量

     * 3. @PathVariable("name"): 这里name 和{name} 命名保持一致

     * 4. String name_ 这里自定义,和{name}命名无关

     * 5. @PathVariable Map<String, String> map 把所有传递的值传入map

     * 6. 可以看下@PathVariable源码

     */

    @GetMapping("/monster/{id}/{name}")

    public String pathVariable(@PathVariable("id") Integer id,

                               @PathVariable("name") String name,

                               @PathVariable Map<String, String> map) {

        System.out.println("id-" + id);

        System.out.println("name-" + name);

        System.out.println("map-" + map);

        return "success";

    }

}

@RequestHeader 使用

演示@RequestHeader 使用,修改 ParameterController.java , 完成测试

&radic; 修改 index.html

<a href="/requestHeader" rel="external nofollow" >@RequestHeader-获取Http请求头 </a><br/><br/>

&radic; 修改 ParameterController.java

/**

 * @RequestHeader("Host") 获取http请求头的 host信息

 * @RequestHeader Map<String, String> header: 获取到http请求的所有信息

 */

@GetMapping("/requestHeader")

public String requestHeader(@RequestHeader("host") String host,

                            @RequestHeader Map<String, String> header,

                            @RequestHeader("accept") String accept) {

    System.out.println("host-" + host);

    System.out.println("header-" + header);

    System.out.println("accept-" + accept);

    return "success";

}

@RequestParam 使用

演示@RequestParam 使用,修改 ParameterController.java , 完成测试

&radic; 修改 index.html

<a href="/hi?name=wukong&fruit=apple&fruit=pear&id=300&address=北京" rel="external nofollow" >@RequestParam-获取请求参数</a><br/><br/>

&radic; 修改 ParameterController.java

/**

 * @param username wukong

 * @param fruits  List<String> fruits 接收集合 [apple, pear]

 * @param paras Map<String, String> paras 如果我们希望将所有的请求参数的值都获取到,

 *              可以通过@RequestParam Map<String, String> paras这种方式

 *             一次性的接收所有的请求参数 {name=wukong, fruit=apple, id=300, address=北京}

 *             如果接收的某个参数中有多个之值比如这里fruits是一个集合,从map中只能拿到一个

 *              可以理解map底层会将相同的key的value值进行覆盖

 * @return

 * @RequestParam

 */

@GetMapping("/hi")

public String hi(@RequestParam(value = "name") String username,

                 @RequestParam("fruit") List<String> fruits,

                 @RequestParam Map<String, String> paras) {

    //username-wukong

    System.out.println("username-" + username);

    //fruit-[apple, pear]

    System.out.println("fruit-" + fruits);

    //paras-{name=wukong, fruit=apple, id=300, address=北京}

    System.out.println("paras-" + paras);

    return "success";

}

@CookieValue 使用

演示@CookieValue 使用,修改 ParameterController.java , 完成测试

&radic; 修改 index.html

<a href="/cookie" rel="external nofollow" >@CookieValue-获取cookie值</a><br/><br/>

&radic; 修改 ParameterController.java

/**

 * 因为我的浏览器目前没有cookie,我们可以自己设置cookie[技巧还是非常有用]

 * 如果要测试,可以先写一个方法,在浏览器创建对应的cookie

 * 说明 1. value = "cookie_key" 表示接收名字为 cookie_key的cookie

 * 2. 如果浏览器携带来对应的cookie , 那么 后面的参数是String ,则接收到的是对应对value

 * 3. 后面的参数是Cookie ,则接收到的是封装好的对应的cookie

 */

@GetMapping("/cookie")

public String cookie(@CookieValue(value = "cookie_key", required = false) String cookie_value,

                     HttpServletRequest request,

                     @CookieValue(value = "username", required = false) Cookie cookie) {

    System.out.println("cookie_value-" + cookie_value);

    if (cookie != null) {

        System.out.println("username-" + cookie.getName() + "-" + cookie.getValue());

    }

    System.out.println("-------------------------");

    Cookie[] cookies = request.getCookies();

    for (Cookie cookie1 : cookies) {

        System.out.println(cookie1.getName() + "=>" + cookie1.getValue());

    }

    return "success";

}

@RequestBody 使用

演示@RequestBody 使用,修改 ParameterController.java , 完成测试

&radic; 修改 index.html

<hr/>

<h2>测试@RequestBody获取数据: 获取POST请求体</h2>

<form action="/save" method="post">

    姓名: <input name="name"/> <br>

    年龄: <input name="age"/> <br/>

    <input type="submit" value="提交"/>

</form>

&radic; 修改 ParameterController.java

/**

 * @RequestBody 是整体取出Post请求内容

 */

@PostMapping("/save")

public String postMethod(@RequestBody String content) {

    System.out.println("content-" + content);

    return "success";

}

@RequestAttribute 和 @SessionAttribute使用

演示@RequestAttribute @SessionAttribute使用,创建 com/hspedu/web/controller/RequestController.java , 完成测试

&radic; 修改 index.html

<a href="/login" rel="external nofollow" >@RequestAttribute、@SessionAttribute-获取request域、session属性-</a>

&radic; 创建 RequestController.java

    @GetMapping("/login")

    public String login(HttpServletRequest request) {

        request.setAttribute("user", "llp");

        //向session中添加数据

        request.getSession().setAttribute("website", "http://www.baidu.com");

        //这里需要使用forward关键字,如果不适用则会走视图解析器,这

        //里视图解析器前缀配置的是/  后缀配置的.html  ---> /ok.html

        //而请求转发在服务器端执行,/被解析成 ip:port/工程路径

        //进而最终得到的完整路径是 ip:port/工程路径/ok.html

        //但是我们这里希望访问的是 ip:port/工程路径/ok这个请求路径

        //因此这里手动的设置forward:/ok ,底层会根据我们设置的路径进行请求转发

        return "forward:/ok";

    }

    @GetMapping("ok")

    //返回字符串,不走视图解析器

    @ResponseBody

    public String ok(@RequestAttribute(value = "user", required = false) String username,

                     @SessionAttribute(value = "website",required = false) String website, HttpServletRequest request) {

        System.out.println("username= " + username);

        System.out.println("通过servlet api 获取 username-" +  request.getAttribute("user"));

        System.out.println("website = " + website);

        System.out.println("通过servlet api 获取 website-"+request.getSession().getAttribute("website"));

        return "success";

    }

}

3.复杂参数

1.基本介绍

  • 在开发中,SpringBoot 在响应客户端请求时,也支持复杂参数

  • Map、Model、Errors/BindingResult、RedirectAttributes、ServletResponse、SessionStatus、 UriComponentsBuilder、ServletUriComponentsBuilder、HttpSession

  • Map、Model 数据会被放在 request 域, 底层 request.setAttribute()

  • RedirectAttributes 重定向携带数据

2.复杂参数应用实例

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

2.代码实现

//响应一个注册请求

@GetMapping("/register")

public String register(Map<String,Object> map,

                       Model model,

                       HttpServletResponse response) {

    //如果一个注册请求,会将注册数据封装到map或者model

    //map中的数据和model的数据,会被放入到request域中

    map.put("user","llp");

    map.put("job","码农");

    model.addAttribute("sal", 2500);

    //一会我们再测试response使用

    //我们演示创建cookie,并通过response 添加到浏览器/客户端

    Cookie cookie = new Cookie("email", "123@sohu.com");

    response.addCookie(cookie);

    //请求转发

    return "forward:/registerOk";

}

@ResponseBody

@GetMapping("/registerOk")

public String registerOk(HttpServletRequest request) {

    System.out.println("user-" + request.getAttribute("user"));

    System.out.println("job-" + request.getAttribute("job"));

    System.out.println("sal-" + request.getAttribute("sal"));

    return "success";

}

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

1.基本介绍

  • 在开发中,SpringBoot 在响应客户端请求时,也支持自定义对象参数

  • 完成自动类型转换与格式化

  • 支持级联封装

2.自定义对象参数-应用实例

1.需求说明 : 演示自定义对象参数使用,完成自动封装,类型转换

2.代码实现

1.创建src\main\resources\static\save.html

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>添加妖怪</title></head>

<body><h2>添加妖怪-坐骑[测试封装 POJO;]</h2>

<form action="/savemonster" method="post">

    编号: <input name="id" value="100"><br/>

    姓名: <input name="name" value="牛魔王"/><br/>

    年龄: <input name="age" value="120"/> <br/>

    婚否: <input name="isMarried" value="true"/> <br/>

    生日: <input name="birth" value="2000/11/11"/> <br/>

    <!--注意这里car对象是monster的属性,给对象属性赋值时需要以对象名.字段名的方式-->

    坐骑:<input name="car.name" value="法拉利"/><br/>

    价格:<input name="car.price" value="99999.9"/>

    <input type="submit" value="保存"/>

</form>

</body>

</html>

2.修改src\main\java\com\llp\springboot\controller\ParameterController.java

@PostMapping("/savemonster")

public String saveMonster(Monster monster) {

    System.out.println("monster= " + monster);

    return "success";

}