1. 简介
Spring MVC可以简化从前端接收参数的步骤。
2. Param传参
通过设定函数入参和添加标记来简化接受:
java">//参数接收
@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. 动态路径传参
也可以直接从动态路径接受参数:
java">//动态路径用{}括起来
//接收路径参数用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注解:
java">...
@EnableWebMvc
public class MVCConfig {
...
}
业务逻辑实现:
java">@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
java">@RequestMapping
public String data(@CookieValue(value = "cookieName") String cookie){System.out.println("cookie = " + cookie);return "ok";
}
6.接收Header
通过@RequestHeader标注接受Header:
java">@RequestMapping
public String data(@RequestHeader("Connection") String conn){//接收header的Connection字段System.out.println("conn = " + conn);return "conn = " + conn;
}
7.获取原生对象
原生对象可以直接在函数入参获取:
java">@Controller
public class dataController {@Autowiredprivate 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();}
}