Spring MVC参数接收 总结
1. 简介
Spring MVC可以简化从前端接收参数的步骤。
2. Param传参
通过设定函数入参和添加标记来简化接受:
//参数接收
@RequestMapping("product")
@ResponseBody
//接受/product?product=goods&id=123
//1.名称必须相同,2.不传值不会不报错
public String product(String product, int id){
System.out.println("product = " + product+ ", id = " + id);
return "product = " + product+ ", id = " + id;
}
//注解指定
//pdt必须传递并转化成product,不传就报400异常
//id可以不传递,不传默认值就是1
@RequestMapping("product1")
@ResponseBody
public String product1(@RequestParam(value = "pdt") String product, @RequestParam(required = false,defaultValue = "1") int id){
System.out.println("product = " + product+ ", id = " + id);
return "product = " + product+ ", id = " + id;
}
//特殊值 ids=1&ids=2&ids=3
@GetMapping("product2")
@ResponseBody
public String product2(@RequestParam List<String> ids){//@RequestParam必须加
System.out.println("hbs = " + ids);
return "ok";
}
//数据直接放到数据类里,要求名字必须相同
//如果没传就用默认值,都不会报错
@RequestMapping("product3")
@ResponseBody
public String product3(Product product){
System.out.println("product" + product);
return product.toString();
}
3. 动态路径传参
也可以直接从动态路径接受参数:
//动态路径用{}括起来
//接收路径参数用PathVariable标记
@RequestMapping("{pdt}/{id}")
public String login(@PathVariable("pdt") String product, @PathVariable String id){
System.out.println("product = " + product + ", id = " + id);
return "product = " + product + ", id = " + id;
}
4. JSON传参
从前端传来的JSON解析接收方法如下:
pom.xml中导入json依赖:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.15.0</version>
</dependency>
配置类中加入@EnableWebMvc注解:
...
@EnableWebMvc
public class MVCConfig {
...
}
业务逻辑实现:
@RequestMapping("/")
@Controller
@ResponseBody
public class JsonController {
@RequestMapping(value = "product",method = RequestMethod.POST)
public String data(@RequestBody Product product){//@RequestBody表示接受json数据
System.out.println("product = " + product);
return product.toString();
}
}
5.接收Cookie
通过@CookieValue标注接受Cookie
@RequestMapping
public String data(@CookieValue(value = "cookieName") String cookie){
System.out.println("cookie = " + cookie);
return "ok";
}
6.接收Header
通过@RequestHeader标注接受Header:
@RequestMapping
public String data(@RequestHeader("Connection") String conn){//接收header的Connection字段
System.out.println("conn = " + conn);
return "conn = " + conn;
}
7.获取原生对象
原生对象可以直接在函数入参获取:
@Controller
public class dataController {
@Autowired
private ServletContext servletContext;//通过IOC自动获取ServletContext对象
public void api(HttpServletResponse response, HttpServletRequest request, HttpSession session) {//获取HttpServletResponse,HttpServletRequest,HttpSession对象
//获取ServletContext对象
ServletContext servletContext1 = request.getServletContext();
ServletContext servletContext2 = session.getServletContext();
}
}
原文地址:https://blog.csdn.net/a827143452/article/details/142458657
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!