What are the annotations used by SpringBoot to receive parameters?
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
Create src\main\resources\ static\index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> <h2 id="hello-nbsp-llp">hello, llp</h2> 基本注解: <hr/> <a href="/monster/200/jack" rel="external nofollow" >@PathVariable-路径变量 monster/200/jack</a><br/><br/> </body> </html>
@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"; } }
@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/>
√ 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"; }
@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/>
√ 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"; }
@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/>
√ 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"; }
@RequestBody Use
Demo Use @RequestBody, modify ParameterController.java, complete the test
√ Modify index.html
<hr/> <h2 id="测试-RequestBody获取数据-nbsp-获取POST请求体">测试@RequestBody获取数据: 获取POST请求体</h2> <form action="/save" method="post"> 姓名: <input name="name"/> <br> 年龄: <input name="age"/> <br/> <input type="submit" value="提交"/> </form>
√ Modify ParameterController.java
/** * @RequestBody 是整体取出Post请求内容 */ @PostMapping("/save") public String postMethod(@RequestBody String content) { System.out.println("content-" + content); return "success"; }
@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>
√ 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"; } }
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, ServletResponse2. 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"; }

- During development, SpringBoot responds to client requests , also supports custom object parameters
- Complete automatic type conversion and formatting
- Supports cascade encapsulation
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>添加妖怪</title></head> <body><h2 id="添加妖怪-坐骑-测试封装-nbsp-POJO">添加妖怪-坐骑[测试封装 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>
@PostMapping("/savemonster") public String saveMonster(Monster monster) { System.out.println("monster= " + monster); return "success"; }

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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Introduction to Jasypt Jasypt is a java library that allows a developer to add basic encryption functionality to his/her project with minimal effort and does not require a deep understanding of how encryption works. High security for one-way and two-way encryption. , standards-based encryption technology. Encrypt passwords, text, numbers, binaries... Suitable for integration into Spring-based applications, open API, for use with any JCE provider... Add the following dependency: com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt benefits protect our system security. Even if the code is leaked, the data source can be guaranteed.

Usage scenario 1. The order was placed successfully but the payment was not made within 30 minutes. The payment timed out and the order was automatically canceled. 2. The order was signed and no evaluation was conducted for 7 days after signing. If the order times out and is not evaluated, the system defaults to a positive rating. 3. The order is placed successfully. If the merchant does not receive the order for 5 minutes, the order is cancelled. 4. The delivery times out, and push SMS reminder... For scenarios with long delays and low real-time performance, we can Use task scheduling to perform regular polling processing. For example: xxl-job Today we will pick

1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

When Springboot+Mybatis-plus does not use SQL statements to perform multi-table adding operations, the problems I encountered are decomposed by simulating thinking in the test environment: Create a BrandDTO object with parameters to simulate passing parameters to the background. We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use tools such as Mybatis-plus-join, you can only configure the corresponding Mapper.xml file and configure The smelly and long ResultMap, and then write the corresponding sql statement. Although this method seems cumbersome, it is highly flexible and allows us to

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

In projects, some configuration information is often needed. This information may have different configurations in the test environment and the production environment, and may need to be modified later based on actual business conditions. We cannot hard-code these configurations in the code. It is best to write them in the configuration file. For example, you can write this information in the application.yml file. So, how to get or use this address in the code? There are 2 methods. Method 1: We can get the value corresponding to the key in the configuration file (application.yml) through the ${key} annotated with @Value. This method is suitable for situations where there are relatively few microservices. Method 2: In actual projects, When business is complicated, logic
