Spring MVC之数据绑定和模型数据解析
Spring MVC数据绑定
数据绑定:在后端的业务方法中直接获取客户端HTTP请求中的参数,将请求参数映射到业务方法的形参中。
Spring MVC 中的数据绑定的工作是由HandlerAdatper来弯沉的
- 基本数据类型
1 @RequestMapping("/baseType")
2 @ResponseBody // 不会把返回值当视图地址来解析,将返回值以本身形式进行返回
3 public String baseType(int id){
4 return id+"";
5
@ResponseBody表示Spring MVC会直接将业务方法的返回值响应给客户端,但是基本数据类型返回值必须有赋值才能访问
- 包装类
1 @RequestMapping(value = "/packageType")
2 @ResponseBody // 不会把返回值当视图地址来解析,将返回值以本身形式进行返回
3 public String packageType(@RequestParam(value = "num",required = false,defaultValue = "111") Integer id){
4 return id+"";
5
包装类可以接受null,当HTTP请求参数为空时,直接返回为null。
@RequestParam(value="num",required=false,defaultValue="111")
value="num"表示请求参数名;
required=True表示参数必须填写,默认为false;
defaultValue="111"表示参数默认值。
- 数组
1 @RequestMapping(value = "/array")
2 public String array(String[] name){
3 String str = Arrays.toString(name);
4 return str;
5 }
@RestController表示该控制器会直接将业务方法的返回值响应给客户端,不进行视图解析
- List
Spring MVC不支持List类型的直接转换,需要对List集合进行包装
1 package com.wiggin.entity;
2
3 import lombok.AllArgsConstructor;
4 import lombok.Data;
5 import lombok.NoArgsConstructor;
6
7 import java.util.List;
8 @Data
9 @AllArgsConstructor
10 @NoArgsConstructor
11 public class UserList {
12 private List<User> users;
13 }
JSP
1 <%--
2 Created by IntelliJ IDEA.
3 User: Administrator
4 Date: 2020/8/4
5 Time: 0:13
6 To change this template use File | Settings | File Templates.
7 --%>
8 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
9 <html>
10 <head>
11 <title>Title</title>
12 </head>
13 <body>
14 <form action="/data/list" method="post">
15 用户1id:<input type="text" name="users[0].id"></br>
16 用户1名:<input type="text" name="users[0].name"></br>
17 用户2id:<input type="text" name="users[1].id"></br>
18 用户2名:<input type="text" name="users[1].name"></br>
19 用户3id:<input type="text" name="users[2].id"></br>
20 用户3名:<input type="text" name="users[2].name"></br>
21 <input type="submit" value="注册">
22 </form>
23 </body>
24 </html>
业务方法
1 @RequestMapping(value = "/list")
2 public String list(UserList userList){
3
4 StringBuffer str = new StringBuffer();
5 for (User user:userList.getUsers()){
6 str.append(user);
7 }
8 return str.toString();
9
10 }
处理中文乱码,在springmvc.xml中配置
1 <mvc:annotation-driven>
2 <mvc:message-converters register-defaults="true">
3 <bean class="org.springframework.http.converter.StringHttpMessageConverter">
4 <property name="supportedMediaTypes" value="text/html;charset=UTF-8"></property>
5 </bean>
6 </mvc:message-converters>
7 </mvc:annotation-driven>
- Map
自定义封装类
1 package com.wiggin.entity;
2
3 import lombok.Data;
4
5 import java.util.Map;
6
7 @Data
8 public class UserMap {
9 private Map<String,User> users;
10 }
业务方法
1 @RequestMapping(value = "/map")
2 public String list(UserMap userMap){
3
4 StringBuffer str = new StringBuffer();
5 for (String key:userMap.getUsers().keySet()){
6 User user = userMap.getUsers().get(key);
7 str.append(user);
8 }
9 return str.toString();
10
11 }
JSP
1 <%--
2 Created by IntelliJ IDEA.
3 User: Administrator
4 Date: 2020/8/4
5 Time: 17:17
6 To change this template use File | Settings | File Templates.
7 --%>
8 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
9 <html>
10 <head>
11 <title>Title</title>
12 </head>
13 <body>
14 <form action="/data/map" method="post">
15 用户1id:<input type="text" name="users['a'].id"></br>
16 用户1名:<input type="text" name="users['a'].name"></br>
17 用户2id:<input type="text" name="users['b'].id"></br>
18 用户2名:<input type="text" name="users['b'].name"></br>
19 用户3id:<input type="text" name="users['c'].id"></br>
20 用户3名:<input type="text" name="users['c'].name"></br>
21 <input type="submit" value="注册">
22 </form>
23 </body>
24 </html>
- JSON
客户端发送json格式的数据,通过Spring MVC绑定到业务方法的形参中。
处理Spring MVC无法加载静态资源,在web.xml配置
1 <!-- 单独处理js文件 -->
2 <servlet-mapping>
3 <servlet-name>default</servlet-name>
4 <url-pattern>*.js</url-pattern>
5 </servlet-mapping>
JSP
1 <%--
2 Created by IntelliJ IDEA.
3 User: Administrator
4 Date: 2020/8/4
5 Time: 17:27
6 To change this template use File | Settings | File Templates.
7 --%>
8 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
9 <html>
10 <head>
11 <title>Title</title>
12
13 <script src="static/jquery-3.5.1.min.js"></script>
14 <script type="text/javascript">
15 $(function () {
16 var user = {
17 "id" : 1,
18 "name" : "张三";
19
20 }
21 $.ajax({
22 url:"/data/json",
23 data:Json.stringify(user),
24 type:"POST",
25 contentType:"application/json;charset=UTF-8",
26 success:function (data) {
27 alert(data.id+"----"+data.name);
28 }
29 })
30 })
31 </script>
32 </head>
33 <body>
34
35 </body>
36 </html>
业务方法
1 // @RequestBody 接受json数据
2 @RequestMapping("/json")
3 public User json(@RequestBody User user){
4 System.out.println(user);
5 user.setId(6);
6 user.setName("wiggin");
7 return user;
8 }
在Spring MVC中JSON和javaBean的转换需要借助fastjson,pom.xml引入相关依赖
1 <dependency>
2 <groupId>com.alibaba</groupId>
3 <artifactId>fastjson</artifactId>
4 <version>1.2.32</version>
5 </dependency>
在springmvc.xml中配置
1 <mvc:annotation-driven>
2 <mvc:message-converters register-defaults="true">
3 <bean class="org.springframework.http.converter.StringHttpMessageConverter">
4 <property name="supportedMediaTypes" value="text/html;charset=UTF-8"></property>
5 </bean>
6 <!-- 配置fastjson -->
7 <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4"></bean>
8 </mvc:message-converters>
9 </mvc:annotation-driven>
Spring MVC模型数据解析
JSP四大作用域对应的内置对象:pageContext、request、session、application
模型数据的绑定是由VIewResolver来完成的,实际开发中,我们需要先添加模型的数据,再交给ViewResolver来绑定
Spring MVC提供了以下几种方式来添加模型数据
- Map
- Model
- ModelAndView
- HttpServletRequest
- @ModelAttribute
将模型数据绑定到Request对象
1.Map
1 import com.wiggin.entity.User;
2 import org.springframework.stereotype.Controller;
3 import org.springframework.web.bind.annotation.RequestMapping;
4
5 import java.util.Map;
6
7 @Controller
8 @RequestMapping("/view")
9 public class ViewHandler {
10
11 @RequestMapping("/map")
12 public String map(Map<String,User> map){
13 User user = new User();
14 user.setId(1);
15 user.setName("wiggin");
16 map.put("user",user);
17 return "view";
18 }
19 }
JSP
1 <%--
2 Created by IntelliJ IDEA.
3 User: Administrator
4 Date: 2020/8/4
5 Time: 20:51
6 To change this template use File | Settings | File Templates.
7 --%>
8 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
9 <!-- 是否忽略EL表达式 -->
10 <%@ page isELIgnored="false" %>
11 <html>
12 <head>
13 <title>Title</title>
14 </head>
15 <body>
16 ${requestScope.user}
17 </body>
18 </html>
2.Model
1 @RequestMapping("/model")
2 public String map(Model model){
3 User user = new User();
4 user.setId(1);
5 user.setName("wiggin");
6 model.addAttribute("user",user);
7 return "view";
8 }
3.ModelAndView
1 @RequestMapping("/modelAndView")
2 public ModelAndView modelAndView(){
3 User user = new User();
4 user.setId(1);
5 user.setName("wiggin");
6 ModelAndView modelAndView = new ModelAndView();
7 modelAndView.addObject("user",user);
8 modelAndView.setViewName("view");
9 return modelAndView;
10 }
11 @RequestMapping("/modelAndView2")
12 public ModelAndView modelAndView2(){
13 User user = new User();
14 user.setId(1);
15 user.setName("wiggin");
16 ModelAndView modelAndView2 = new ModelAndView();
17 modelAndView2.addObject("user",user);
18 View view = new InternalResourceView("/view.jsp");
19 modelAndView2.setView(view);
20 return modelAndView2;
21 }
22 @RequestMapping("/modelAndView3")
23 public ModelAndView modelAndView3(){
24 User user = new User();
25 user.setId(1);
26 user.setName("wiggin");
27 ModelAndView modelAndView3 = new ModelAndView("view");
28 modelAndView3.addObject("user",user);
29 return modelAndView3;
30 }
31 @RequestMapping("/modelAndView4")
32 public ModelAndView modelAndView4(){
33 User user = new User();
34 user.setId(1);
35 user.setName("wiggin");
36 View view = new InternalResourceView("/view.jsp");
37 ModelAndView modelAndView4= new ModelAndView(view);
38 modelAndView4.addObject("user",user);
39 return modelAndView4;
40 }
41 @RequestMapping("/modelAndView5")
42 public ModelAndView modelAndView5(){
43 User user = new User();
44 user.setId(1);
45 user.setName("wiggin");
46 Map<String,User> map = new HashMap<>();
47 map.put("user",user);
48 ModelAndView modelAndView5= new ModelAndView("view",map);
49
50 return modelAndView5;
51 }
52 @RequestMapping("/modelAndView6")
53 public ModelAndView modelAndView6(){
54 User user = new User();
55 user.setId(1);
56 user.setName("wiggin");
57 ModelAndView modelAndView6= new ModelAndView("view","user",user);
58
59 return modelAndView6;
60 }
4.HttpServletRequest
1 @RequestMapping("/request")
2 public String request(HttpServletRequest request){
3 User user = new User();
4 user.setId(1);
5 user.setName("wiggin");
6 request.setAttribute("user",user);
7
8 return "view";
9 }
5.@ModelAttribute
- 定义一个 方法,该方法专门用来返回要填充到模型数据中的对象
- 业务方法无需再处理视图,只要返回视图就可以
1 @ModelAttribute
2 public User getUser(){
3 User user = new User();
4 user.setId(1);
5 user.setName("wiggin");
6 return user;
7 }
8 // 上面的模型数据已经返回,只要处理视图就行了
9 @RequestMapping("/modelAttribute")
10 public String modelAttribute(){
11 return "view";
12 }
将模型数据绑定到session对象
1.直接用原生的Servlet API
1 public String session(HttpServletRequest request){
2 HttpSession session = request.getSession();
3 User user = new User();
4 user.setId(1);
5 user.setName("wiggin");
6 session.setAttribute("user",user);
7 return "view";
8 }
9 @RequestMapping("/session2")
10 public String session2(HttpSession session){
11 User user = new User();
12 user.setId(1);
13 user.setName("wiggin");
14 session.setAttribute("user",user);
15 return "view";
16 }
2.通过@sessionAttribute
1 @Controller
2 @RequestMapping("/view")
3 // @SessionAttributes(value = "user") // 根据value添加,只要方法里有user对象就直接加到view中的session中
4 //@SessionAttributes(value = {"user","address"}) // 根据value添加,只要方法里有user以及address对象就直接加到view中的session中
5 //@SessionAttributes(types = User.class) // 根据types添加,只要方法里有User类就直接加到view中的session中
6 //@SessionAttributes(types = {User.class,Address.class}) // 根据types添加,只要方法里有User和Address类就直接加到view中的session中
7 public class ViewHandler
全局作用域
将模型数据绑定到application对象
1 @RequestMapping("/application")
2 public String application(HttpServletRequest request){
3 ServletContext application = request.getServletContext();
4 User user = new User();
5 user.setId(1);
6 user.setName("wiggin");
7 application.setAttribute("user",user);
8 return "view";
9 }