Home > Java > javaTutorial > body text

What are the annotations used by SpringBoot to receive parameters?

WBOY
Release: 2023-05-10 15:49:33
forward
1773 people have browsed it

1. Basic introduction

SpringBoot will use relevant annotations when receiving data/parameters submitted by the client

Detailed explanation of @PathVariable, @RequestHeader, @ModelAttribute, @RequestParam, @MatrixVariable, @CookieValue , @RequestBody

2. Receive parameter-related annotation application examples

1. Requirements: Demonstrate various ways to submit data/parameters to the server, and how the server uses annotations to receive

2 .Application example demonstration

Requirements: Demonstrate various ways to submit data/parameters to the server, and how the server uses annotations to receive

What are the annotations used by SpringBoot to receive parameters?

Create 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>
Copy after login

@PathVariable use

Demonstrate the use of @PathVariable, create src\main\java\com\llp\springboot\controller\ParameterController.java, and complete the test

@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";
    }
}
Copy after login

What are the annotations used by SpringBoot to receive parameters?

@RequestHeader Use

Demonstrate the use of @RequestHeader, modify ParameterController.java, complete the test

√ Modify index.html

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

√ Modify 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";
}
Copy after login

What are the annotations used by SpringBoot to receive parameters?

@RequestParam Use

Demonstrate the use of @RequestParam, modify ParameterController.java, and complete the test

√ Modify index.html

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

√ Modify 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";
}
Copy after login

@CookieValue use

Demonstrate the use of @CookieValue, modify ParameterController.java, and complete the test

√ Modify index.html

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

√ Modify 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";
}
Copy after login

What are the annotations used by SpringBoot to receive parameters?

@RequestBody Use

Demo Use @RequestBody, modify ParameterController.java, complete the test

√ Modify 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>
Copy after login

√ Modify ParameterController.java

/**
 * @RequestBody 是整体取出Post请求内容
 */
@PostMapping("/save")
public String postMethod(@RequestBody String content) {
    System.out.println("content-" + content);
    return "success";
}
Copy after login

@RequestAttribute and @SessionAttribute use

Demonstrate the use of @RequestAttribute @SessionAttribute, create com/hspedu/web/controller/RequestController.java, complete the test

√ Modify index.html

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

√ Create 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";
    }
}
Copy after login

What are the annotations used by SpringBoot to receive parameters?

3. Complex parameters

1. Basic introduction

  • In development, SpringBoot is When responding to client requests, complex parameters

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

  • are also supported.

    Map and Model data will be placed in the request field, and the underlying request.setAttribute()

  • RedirectAttributes redirects carry data

2 .Complex parameter application examples

#1. Description: Demonstrates the use of complex parameters, focusing on: Map, Model, ServletResponse

2. Code implementation

//响应一个注册请求
@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";
}
Copy after login
What are the annotations used by SpringBoot to receive parameters?

4. Custom object parameters - automatic encapsulation

1. Basic introduction
  • During development, SpringBoot responds to client requests , also supports custom object parameters
  • Complete automatic type conversion and formatting
  • Supports cascade encapsulation

2. Custom object parameters - application example

1. Requirement description: Demonstrate the use of custom object parameters, complete automatic encapsulation and type conversion

What are the annotations used by SpringBoot to receive parameters?

2. Code implementation

1. Create 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>
Copy after login

2. Modify src\main\java\com\llp\springboot\controller\ ParameterController.java

@PostMapping("/savemonster")
public String saveMonster(Monster monster) {
    System.out.println("monster= " + monster);
    return "success";
}
Copy after login
What are the annotations used by SpringBoot to receive parameters?###

The above is the detailed content of What are the annotations used by SpringBoot to receive parameters?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!