首页 / 操作系统 / Linux / Spring MVC 前后端传值方式心得笔记
前端传到Controller:方法1通过HttpServletRequest 。写法如下:@Controllerpublic class MyTestController {@RequestMapping("/print")public String PrintInfo(HttpServletRequest request) {System.out.println("name:" +request.getParameter("name"));System.out.println("age:" + request.getParameter("age"));return "testpage";}}HttpServletRequest类是Servlet中的类型,代表了一个Servlet请求。无论Post还是Get请求,都能通过这种方式获取到。比如上面的代码,通过Get方法,如下地址http://127.0.0.1:8080/WebApp/print?name=zhangsan&age=30也可以通过Post方法,使用Postman工具模拟一个post请求,都可以将值传到Controller。这招可以获得Cookie以及Session数据。还可以通过注解@Autowired,将HttpServletRequest 自动的注入进来,不必担心多线程下的并发问题,因为这里HttpServletRequest注入的是一个AOP proxy ,而不是一个普通bean 。每次请求过来,都会检查线程本地属性,来获取真正的Request对象。这些都是Spring自动配置的默认场景。可以参阅https://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-scopes-other-injection但是不推荐使用这个方法,因为这种方法破坏了对一个注入对象的常规理解,造成混乱。代码如下:@Controllerpublic class MyTestController {@Autowiredprivate HttpServletRequest request;@RequestMapping(value="/print")public String PrintInfo() {System.out.println("name:" +request.getParameter("name"));System.out.println("age:" + request.getParameter("age"));return "testpage";}}方法2使用路径变量。写法如下:@Controllerpublic class MyTestController {@RequestMapping("/print/{name}/{age}")public String PrintInfo(@PathVariable String name, @PathVariable int age) {System.out.println("name:" + name);System.out.println("age:" + age);return "testpage";}}@RequestMapping中的{}中即为路径变量,该变量还需要在方法的参数值出现,并且标记@PathVariable。通过URL匹配的方式既可以实现传值,这是REST风格的一种传值方式。上面的例子,只需输入URL:http://127.0.0.1:8080/WebApp/print/ZhangSan/30controller接收到传值,输出:name:ZhangSanage:30@RequestMapping("/print/{name}/{age}")是@RequestMapping(Value="/print/{name}/{age}")的缩写形式,本质上是一样的。方法3参数名匹配的方式:@Controllerpublic class MyTestController {@RequestMapping(value="/print")public String PrintInfo(String name, int age) {System.out.println("name:" +name);System.out.println("age:" + age);return "testpage";}}或者:@Controllerpublic class MyTestController {@RequestMapping(value="/print")public String PrintInfo(@RequestParam("name") String name,@RequestParam("age") int age) {System.out.println("name:" +name);System.out.println("age:" + age);return "testpage";}}当请求传入的参数名字和controller中代码的名字一样的时候,两种方式都可以,区别在于使用了注解@RequestParam,可以设置一个默认值来处理到null值。@RequestParam(value="name", defaultValue="John")但是如果请求中参数的名字和变量名不一样的时候,就只能使用@RequestParam注解。例如请求的参数为如下的时候:http://localhost:8080/WebApp/print?user_name=somename&user_age=30Controller代码只能如下的写法@RequestMapping(value="/print")public String PrintInfo(@RequestParam("user_name") String name, @RequestParam("user_age")int age) {...}尽量使用@RequestParam注解,因为这样可以清晰的知道该参数来自Request,可读性高。方法4传递请求头中的参数,需要用到@RequestHeader注解,该注解将Header中的值绑定到参数上,可以获取一个,多个或者所有的参数。例如@Controllerpublic class MyTestController {@RequestMapping(value="/print")public String PrintInfo(@RequestHeader Map<String, String> headers) {for (String elem: headers.keySet()) {System.out.println(elem + " : " + headers.get(elem));}return "testpage";}}或者@Controllerpublic class MyTestController {@RequestMapping(value="/print")public String PrintInfo(@RequestHeader("User-Agent") String userAgent) {System.out.println("12");System.out.println("name:" +userAgent);//System.out.println("age:" + age);return "testpage";}}方法5使用到@RequestBody注解,得到整个RequestBody的信息@Controllerpublic class MyTestController {@RequestMapping(value="/print")public String PrintInfo(@RequestBody String body) {System.out.println("body:" +body);return "testpage";}}@RequestBody可以将Json数据直接映射程Java对象。例如:方法6采用@ModelAttribute注解,命名匹配,Post中的参数值和Model中的参数值一致的话,会自动绑定到该值。@Controllerpublic class MyTestController {@RequestMapping(value="/print")public String PrintInfo(@ModelAttribute User user) {System.out.println("6");System.out.println("Name:" +user.getName());System.out.println("Age:" +user.getAge());return "testpage";}}public class User {private String name;private int age;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}然后当Post的值中有name和age时,Controller中的user对象会自动附上值。Controller传递到JSP方法1使用ModelAndView类,代码如下:@RequestMapping("/hello")public ModelAndView showMessage() {ModelAndView mv = new ModelAndView("helloworld");mv.addObject("userList", GetUserList());return mv;}public List<User> GetUserList(){List<User> lst=new ArrayList<User>();User user1=new User();user1.setName("zhangsan");user1.setAge(20);lst.add(user1);User user2=new User();user2.setName("lisi");user2.setAge(30);lst.add(user2);return lst;}JSP页面中:<%@ page language="java" contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Spring 4 MVC -HelloWorld</title></head><body><c:forEach items="${userList}" var="user">${user.name} ${user.age}<br /></c:forEach></body></html>ModelAndView 初始化的时候,设置了view的名字,同时也把对象存起来,直接传给view。简单实用。方法2使用Model或者ModelMap(Model是一个接口,ModelMap实现了Model接口)该方法和ModelAndView方法相似,只是Model和View分开来了,通过返回一个String来找到View,Model是注入到Controller的一个参数,通过对它添加属性,在jsp端读取值。代码如下:@Controllerpublic class HelloWorldController {String message = "Welcome to Spring MVC!";@RequestMapping("/hello")public String showMessage(Model model) {model.addAttribute("userList", GetUserList());return "helloworld";}public List<User> GetUserList(){List<User> lst=new ArrayList<User>();User user1=new User();user1.setName("zhangsan");user1.setAge(10);lst.add(user1);User user2=new User();user2.setName("lisi");user2.setAge(33);lst.add(user2);return lst;}}JSP页面中:<%@ page language="java" contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Spring 4 MVC -HelloWorld</title></head><body><c:forEach items="${userList}" var="user">${user.name} ${user.age}<br /></c:forEach></body></html>SpringMVC总结篇 http://www.linuxidc.com/Linux/2016-06/132659.htmSpring+SpringMVC企业快速开发架构搭建 http://www.linuxidc.com/Linux/2015-09/122942.htmSpringMVC的乱码处理 http://www.linuxidc.com/Linux/2015-07/120542.htmSpring MVC整合Freemarker基于注解方式 http://www.linuxidc.com/Linux/2013-02/79660.htm SpringMVC详细示例实战教程 http://www.linuxidc.com/Linux/2015-06/118461.htmSpringMVC 异常处理 http://www.linuxidc.com/Linux/2015-06/119049.htmSpring + Spring MVC + Ibatis + Velocity 框架搭建 http://www.linuxidc.com/Linux/2016-10/135846.htm本文永久更新链接地址:http://www.linuxidc.com/Linux/2017-02/140119.htm