@RequestParam与@PathVariable
作用
他们两个都可以传参
区别
@PathVariable是利用路径传参,这个参数是包含在路径里的例如/car/{id},你可以传/car/1,这个数据大概率是写死的,也就是你事先知道按下这个按钮会关联到哪个id上,提前把他写死。maybe…
@RequestParam是请求传参,最典型的是form表单提交,他解析你表单里的内容,即请求体。但是Controller的路径里是不包含参数的,比如/car,后面的参数是表单或者你自己通过其他方式提交的。
代码演示
@PathVariable
后端代码
@RequestMapping("/car/{id}/{name}")//路径里
public Map getCar(@PathVariable("id") String id,
@PathVariable("name")String name,
@PathVariable Map<String,String> pv){
//pv是把所有参数整理成一个map,必须是<String,String>的形式
HashMap<String,Object> map = new HashMap<>();
map.put("name",name);
map.put("id",id);
map.put("pv",pv);
return map;
}
前台表单
<a href="/car/12/zhangsan">请求一台车</a>
路径里带的参数!
@RequestParam
后端代码
@RequestMapping("/car")
public Map jiaCar(@RequestParam("id")String id,
@RequestParam("ins")List list,
@RequestParam Map map){
HashMap<Object, Object> Map = new HashMap<>();
Map.put("id",id);
Map.put("ins",list);
Map.put("map",map);
return Map;
}
前台表单
<form action="/car/" >
<input name="id" value="12" >
<input name="name" value="zhangsan">
<input type="submit" value="车">
</form>
<a href="/car?id=18&ins=baste&ins=football">驾car就是驾驶car</a>
//你愿意自己写也成
@RequestAttribute
把参数放在请求中,通过请求带给下一个页面或者请求。类似于Session传参。
@Controller
public class RequstController {
@RequestMapping("/requst")
public String setcode(HttpServletRequest req){
req.setAttribute("msg","请求成功!");
return "forward:/success";
}
@ResponseBody
@GetMapping("/success")
public Map sucFunction(@RequestAttribute("msg")String msg,
HttpServletRequest req){
Object msg1 = req.getAttribute("msg");
HashMap<Object, Object> map = new HashMap<>();
map.put("msg1",msg1);
map.put("msg",msg);
return map;
}
}
当发起第一个请求的时候,请求里携带了一个参数到第二个请求。第二个请求可以通过注解或getAttribute方法来获得该参数
@MatrixVariable
矩阵传参的功能默认是关闭的。
@Configuration
//方法一
public class MyBeans implements WebMvcConfigurer{
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper helper = new UrlPathHelper();
helper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(helper);
}
//方法二
//注册自己的web配置开启矩阵传参的功能
// @Bean
// public WebMvcConfigurer webMvcConfigurer(){
// return new WebMvcConfigurer() {
// @Override
// public void configurePathMatch(PathMatchConfigurer configurer) {
// UrlPathHelper helper = new UrlPathHelper();
// helper.setRemoveSemicolonContent(false);//分号是否忽略 true则矩阵传参失效
// configurer.setUrlPathHelper(helper);
//
// }
// };
// }
}
两种方式:
- 自己写一个配置类继承 WebMvcConfigurer重写configurePathMatch方法修改RemoveSemicolonContent的值
- 直接注入自己的组件