Springboot-普通参数与基本注解
实例(boot-05-web-1)
1、普通参数与基本注解
1.1、注解:
@PathVariable、@RequestHeader、@ModelAttribute、@RequestParam、@MatrixVariable、@CookieValue、@RequestBody
实例:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello</title>
<link rel="shortcut icon" href="/favicon.ico"/>
<link rel="bookmark" href="/favicon.ico"/>
</head>
<body>
<h3>测试基本注解</h3>
<ul>
<a href="car/1/owner/libai?age=18&inters=basketball&inters=game">car/{id}/owner/{username}</a>
<li>@PathVariable(路径变量)</li>
<li>@RequestHeader(获取请求头)</li>
<li>@RequestParam(获取请求参数)</li>
<li>@CookieValue(获取cookie值)</li>
<li>@RequestAttribute(获取request域属性)</li>
<li>@RequestBody(获取请求体)</li>
<li>@MatrixVariable(矩阵变量)</li>
</ul>
<br>
<hr>
通过请求参数的方式:/cars/{path}?xxx=xxx&aaa=ccc queryString 查询字符串 @RequestParam: <br>
通过矩阵变量的方式:/cars/sell;low=34;brand=byd,audi,yd ;表示矩阵变量
页面开发,如果cookie禁用了,session里面的内容怎么使用:
session.set(a,b)--->jsessionid--->cookie--->每次发请求携带
url重写:/abc;jsessionid=xxxx 把cookie的值使用矩阵变量的方式进行传递
<a href="/cars/sell;low=34;brand=byd,audi,yd">@MatrixVariable(矩阵变量)</a>
<a href="/cars/sell;low=34;brand=byd;brand=audi;brand=yd">@MatrixVariable(矩阵变量)</a>
<a href="boss/1;age=20/2;age=10">@MatrixVariable(矩阵变量)/boss/{bossId}/{empId}</a>
<br>
<hr/>
<form action="/save" method="post">
测试@RequestBody获取数据<br>
用户名:<input name="userName"/><br>
邮箱:<input name="email"><br>
<input type="submit" value="提交">
</form>
<hr/>
<br/>
<ol>
<li>矩阵变量需要在Springboot中手动开启</li>
<li>根据RFC3989的规范,矩阵变量应当绑定在路径变量中!</li>
<li>若是有多个矩阵变量,应当使用英文符号;进行分隔</li>
<li>若是一个矩阵变量有多个值,应当使用英文符号,进行分隔,或之命名多个重复的key即可。</li>
<li>如:/car/sell;low=34;brand=byd,audi,yd</li>
<li>如:/car/sell;low=34;brand=byd;brand=audi;brand=ya</li>
</ol>
</body>
</html>
//@RequestAttribute注解
package com.zm.boot.controller;
import com.sun.xml.internal.ws.api.ha.StickyFeature;
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;
import java.util.HashMap;
import java.util.Map;
@Controller
public class RequestController {
@GetMapping("/goto")
public String goToPage(HttpServletRequest request){
request.setAttribute("msg","成功");
request.setAttribute("code",200);
return "forward:/success"; //转发到 /success请求
}
@ResponseBody
@GetMapping("/success")
public Map success(@RequestAttribute("msg") String msg,
@RequestAttribute("code") Integer code,
HttpServletRequest request){
Object msg1=request.getAttribute("msg");
Map<String,Object>map=new HashMap<>();
map.put("reqMethod_msg",msg1);
map.put("annotation_msg",msg);
map.put("annotation_code",code);
return map;
}
}
package com.zm.boot.controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.Cookie;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
public class ParameterTestController {
//@PathVariable,@RequestHeader,@RequestParam,@CookieValue 注解
// car/{id}/owner/{username}如:car/2/owner/libai 代表获取2号汽车 car/1代表获取1号汽车
@GetMapping("/car/{id}/owner/{username}")
public Map<String,Object> getCar(@PathVariable("id") Integer id,
@PathVariable("username") String name,
@PathVariable Map<String,String> pv,
@RequestHeader("User-Agent") String userAgent,
@RequestHeader Map<String,Object> header,
@RequestParam("age") Integer age,
@RequestParam("inters") List<String> inters,
@RequestParam Map<String,String>params,
@CookieValue("Idea-4c23c799") String Idea_4c23c799,
@CookieValue("Idea-4c23c799") Cookie cookie){
Map<String,Object> map=new HashMap<>();
// map.put("id",id);
// map.put("name",name);
// map.put("pv",pv);
// map.put("userAgent",userAgent);
// map.put("headers",header);
map.put("age",age);
map.put("inters",inters);
map.put("params",params);
map.put("Idea-4c23c799",Idea_4c23c799);
System.out.println(cookie.getName()+"=====>"+cookie.getValue());
return map;
}
//@RequestBody 注解
@PostMapping("save")
public Map postMethod(@RequestBody String content){ //post表单提交
Map<String,Object> map=new HashMap<>();
map.put("content",content);
return map;
}
//@MatrixVariable 注解
//1、语法: 请求路径:/cars/sell;low=34;brand=byd,audi,yd
//2、SpringBoot默认是禁用了矩阵变量的功能
// 手动开启:原理。对于路径的处理。UrlPathHelper进行解析。
// removeSemicolonContent(移除分号内容)支持矩阵变量的
//3、矩阵变量必须有url路径变量才能被解析
@GetMapping("/cars/{path}")
public Map carsSell(@MatrixVariable("low") Integer low,
@MatrixVariable("brand") List<String> brand,
@PathVariable("path") String path){
Map<String,Object> map= new HashMap<>();
map.put("low",low);
map.put("brand",brand);
map.put("path",path);
return map;
}
// /boss/1;age=20/2;age=10
@GetMapping("/boss/{bossId}/{empId}")
public Map boss(@MatrixVariable(value = "age",pathVar = "bossId") Integer bossAge,
@MatrixVariable(value = "age",pathVar = "empId") Integer empAge){
Map<String,Object> map=new HashMap<>();
map.put("bossAge",bossAge);
map.put("empAge",empAge);
return map;
}
}
@MatrixVariable注解需要手动开启,在config文件中,如:
package com.zm.boot.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.util.UrlPathHelper;
@Configuration(proxyBeanMethods = false)
public class WebConfig {
@Bean
public WebMvcConfigurer webMvcConfigurer(){
return new WebMvcConfigurer() {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper urlPathHelper=new UrlPathHelper();
urlPathHelper.setRemoveSemicolonContent(false); //不移除;后的内容,矩阵变量功能就可以生效
configurer.setUrlPathHelper(urlPathHelper);
}
};
}
}
2、Servlet API:
WebRequest、ServletRequest、MultipartRequest、 HttpSession、javax.servlet.http.PushBuilder、Principal、InputStream、Reader、HttpMethod、Locale、TimeZone、ZoneId
ServletRequestMethodArgumentResolver 以上的部分参数
3、复杂参数:
Map、Model(map、model里面的数据会被放在request的请求域,相当于调用了request.setAttribute方法)、Errors/BindingResult、RedirectAttributes(重定向携带数据)、ServletResponse(response)、SessionStatus、UriComponentsBuilder、ServletUriComponentsBuilder
Map<String,Object> map, Model model, HttpServletRequest request 都是可以给request域中放数据;通过request.getAttribute()来获取相关的数据
Map、Model类型的参数,会返回 mavContainer.getModel();—> BindingAwareModelMap 是Model 也是Map
mavContainer.getModel(); 获取到值的
4、自定义对象参数 封装POJO
可以自动类型转换与格式化,可以级联封装
ServletModelAttributeMethodProcessor
这个参数处理器支持是否为简单类型。
WebDataBinder为web数据绑定器
WebDataBinder binder = binderFactory.createBinder(webRequest, attribute, name);
WebDataBinder :web数据绑定器,将请求参数的值绑定到指定的JavaBean里面
WebDataBinder 利用它里面的 Converters 将请求数据转成指定的数据类型。再次封装到JavaBean中
GenericConversionService:在设置每一个值的时候,找它里面的所有converter那个可以将这个数据类型(request带来参数的字符串)转换到指定的类型(JavaBean – Integer)
byte – > file
@FunctionalInterfacepublic interface Converter<S, T>
未来我们可以给WebDataBinder里面放自己的Converter;
private static final class StringToNumber implements Converter<String, T>
例,在index.html里写
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello</title>
<link rel="shortcut icon" href="/favicon.ico"/>
<link rel="bookmark" href="/favicon.ico"/>
</head>
<body>
<form action="/saveuser" method="post">
姓名:<input name="userName" value="libai"/><br>
年龄:<input name="age" value="18"/><br>
生日:<input name="birth" value="2021/3/30"/><br>
宠物姓名:<input name="pet.name" value="猫猫"/><br>
宠物年龄:<input name="pet.age" value="5"/><br>
<input type="submit" value="保存">
</form>
</body>
</html>
创建person.java以及pet.java文件
package com.zm.boot.bean;
import lombok.Data;
import java.util.Date;
@Data
public class Person {
private String userName;
private Integer age;
private Date birth;
private Pet pet;
}
package com.zm.boot.bean;
import lombok.Data;
@Data
public class Pet {
private String name;
private Integer age;
}
在controller文件中写:
package com.zm.boot.controller;
import com.zm.boot.bean.Person;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.Cookie;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
public class ParameterTestController {
//数据绑定:页面提交的请求数据(GET,POST)都可以和对象属性进行绑定
@PostMapping("/saveuser")
public Person saveuser(Person person){
return person;
}
}
自定义Converter,Pet.java与Person.java文件同上
更改从页面获取的值的样式,如:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello</title>
<link rel="shortcut icon" href="/favicon.ico"/>
<link rel="bookmark" href="/favicon.ico"/>
</head>
<body>
<form action="/saveuser" method="post">
姓名:<input name="userName" value="libai"/><br>
年龄:<input name="age" value="18"/><br>
生日:<input name="birth" value="2021/3/30"/><br>
<!-- 宠物姓名:<input name="pet.name" value="猫猫"/><br>-->
<!-- 宠物年龄:<input name="pet.age" value="5"/><br>-->
宠物:<input name="pet" value="猫猫,3"/>
<input type="submit" value="保存">
</form>
</body>
</html>
在config文件中:如
package com.zm.boot.config;
import com.zm.boot.bean.Pet;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.util.UrlPathHelper;
@Configuration(proxyBeanMethods = false)
public class WebConfig {
@Bean
public WebMvcConfigurer webMvcConfigurer(){
return new WebMvcConfigurer() {
@Override
public void addFormatters(FormatterRegistry registry){
registry.addConverter(new Converter<String, Pet>() {
@Override
public Pet convert(String source){
if(!StringUtils.isEmpty(source)){
Pet pet=new Pet();
String[] split=source.split(",");
pet.setName(split[0]);
pet.setAge(Integer.parseInt(split[1]));
return pet;
}
return null;
}
});
}
};
}
}