SpringMVC的数据绑定与视图解析
作者:互联网
SpringMVC的数据绑定:
在后端直接得到前端的HTTP中的数据。
HTTP请求中的传输的参数都是String类型,Handler业务方法中的参数是开发者指定的数据类型,int Integer,,因此要进行数据类型的绑定
由HabderAdapter完成参数的绑定:
-
基本数据类型:
@RequestMapping("/baseType")
@ResponseBody
public String baseType(int id){return "id="+id; }
请求必须由id参数,否则500错误,同时id的值 , 必须为数值不然为400异常。
-
包装类
@RequestMapping("/baseType1")
@ResponseBody
public String baseType(Integer id){return "id="+id; }
请求必须由id参数,否则500错误,同时id的值 , 必须为数值不然为400异常。不传为null。
-
利用@RequestParam处理参数(设置默认值)
@RequestMapping("/baseType1")
@ResponseBody
public String baseType(@RequestParam(value = "id",required = true,defaultValue = "0") Integer id){return "id="+id; }
-
数组
@RequestMapping("/arrayType")
@ResponseBody
public String arrayType(String[] names){
StringBuffer stringBuffer =new StringBuffer();
for(String str:names){
stringBuffer.append(str).append(" ");
}
return "names: "+stringBuffer.toString();
} -
POJO
package com.southwind.entity;import lombok.Data; @Data public class User { private Integer id; private String name; private Address address; } @RequestMapping("/add") public String add(User user){ System.out.println(user); return "redirect:/addUser.jsp"; }
乱码;
<mvc:annotation-driven>
<!-- 消息转换器-->
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value="text/html;charset=utf-8"></property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
List
SpringMVC不支持直接转换Lis类型,需要包装成Object
List的自定义包装类
控制类:
@RequestMapping("/listType")
@ResponseBody
public String listType(UserList users){
StringBuffer stringBuffer =new StringBuffer();
for(User user:users.getList()){
stringBuffer.append(user);
}
return "用户"+stringBuffer.toString();
}
实体类:
package com.southwind.entity;
import lombok.Data;
import java.util.List;
@Data
public class UserList {
private List<User> list;
}
jsp
<%--
Created by IntelliJ IDEA.
User: 郝泾钊
Date: 2022-04-06
Time: 17:34
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/listType">
<input type="text" name="list[0].id">
<input type="text" name=" list[0].name">
<input type="text" name="list[1].id">
<input type="text" name=" list[1].name">
<input type="submit" value=" 提交">
</form>
</body>
</html>
注意;User要有无参构造
JSON
1.对于返回是text:
<script type="text/javascript">
$(function () {
var user= {
"id":1,
"name":"张三"
}
$.ajax({
url:"/jsonType",
data:JSON.stringify(user),
type:"POST",
contentType:"application/json;charset=UTF-8",
dataType:"text",
success:function (data) {
// console.log(data);
var obj=eval("("+data+")")
alert(obj.id)
alert(obj.name)
}
})
})
</script>
2.直接是json
页面:
<%--
Created by IntelliJ IDEA.
User: 郝泾钊
Date: 2022-04-06
Time: 17:34
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script type="text/javascript" src="js/jquery-3.6.0.min.js"></script>
<script type="text/javascript">
$(function () {
var user= {
"id":1,
"name":"张三"
}
$.ajax({
url:"/jsonType",
data:JSON.stringify(user),
type:"POST",
contentType:"application/json;charset=UTF-8",
dataType:"JSON",
success:function (data) {
// console.log(data);
// var obj=eval("("+data+")")
alert(data.id)
alert(data.name)
}
})
})
</script>
</head>
<body>
</body>
</html>
controller:业务方法:
@RequestMapping("/jsonType")
@ResponseBody
public User jsonType(@RequestBody User user){
System.out.println(user);
user.setId(2);
return user;
}
配置:
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--json依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.32</version>
</dependency>
</dependencies>
<mvc:annotation-driven>
<!-- 消息转换器-->
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value="text/html;charset=utf-8"></property>
</bean>
<!-- fastjson-->
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4">
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
注意;
- JSON数据必需用JSON。stringify()妆化成字符串
- contentType:"application/json;charset=UTF-8"不能省略
Spring mvc 的视图层解析
调用web资源给域对象传值
page
request
session
application
业务数据的绑定是指将业务的数据绑定给jsp对象,业务数据的绑定是由ViewResolver来完成,开发时,我们先添加业务数据,在交给ViewResolve来绑定数据,因此学习的重点在于如何的添加数据,Springmvc提供了一下几中的方式来添加业务:
- Map
- Model
- ModelAndView
- @SessionAttribute
- @ModelAttribute
- Servlet API
业务绑定到request对象
Map
springmvc 在调用业务方法之前会创建一个隐含的对象作为业务的数据的容器,设置业务方法的入参为Maq类型,springmvc会将隐含的对象的引用传递格入参(默认是给Request)
@RequestMapping("/map")
public String map(Map<String,Object> map) {
User user =new User();
user.setId(1);
user.setName("张三");
map.put("user",user);
return "show";
}
Model
@RequestMapping("/model")
public String model(Model model) {
User user =new User();
user.setId(1);
user.setName("张三");
model.addAttribute("user",user);
return "show";
}
Mo'delAndView
Mo'delAndView不但包含业务数据也包括了视图信息,如果用Mo'delAndView来处理业务数据,业务数据的返回值必需是Mo'delAndView对象
操作;
1.填充业务数据
2.绑定业务信息
-
完整路径@RequestMapping("/modelAndView1") public ModelAndView modelAndView1() { ModelAndView modelAndView =new ModelAndView(); User user =new User(); user.setId(1); user.setName("张三"); modelAndView.addObject("user",user); modelAndView.setViewName("show"); return modelAndView; }
-
直接给视图@RequestMapping("/modelAndView2") public ModelAndView modelAndView2() { ModelAndView modelAndView =new ModelAndView(); User user =new User(); user.setId(1); user.setName("张三"); modelAndView.addObject("user",user); View view =new InternalResourceView("/show.jsp"); modelAndView.setView(view); return modelAndView; }
-
传递view对象@RequestMapping("/modelAndView3") public ModelAndView modelAndView3() { ModelAndView modelAndView =new ModelAndView("show"); User user =new User(); user.setId(1); user.setName("张三"); modelAndView.addObject("user",user); return modelAndView; }
-
@RequestMapping("/modelAndView4") public ModelAndView modelAndView4() { View view =new InternalResourceView("/show.jsp"); ModelAndView modelAndView =new ModelAndView(view); User user =new User(); user.setId(1); user.setName("张三"); modelAndView.addObject("user",user); return modelAndView; }
使用Map集合
-
@RequestMapping("/modelAndView5") public ModelAndView modelAndView5() { Map<String,Object> map =new HashMap<>(); User user =new User(); user.setId(1); user.setName("张三"); map.put("user",user); ModelAndView modelAndView =new ModelAndView("show",map); return modelAndView; }
直接map和view
@RequestMapping("/modelAndView6")
public ModelAndView modelAndView6() {
Map<String,Object> map =new HashMap<>();
User user =new User();
user.setId(1);
user.setName("张三");
map.put("user",user);
View view =new InternalResourceView("/show.jsp");
ModelAndView modelAndView =new ModelAndView(view,map);
return modelAndView;
}
...
HttpServletRequest
Spring mvc 在业务方法中直接得到Servlet的原生web资源,只需要在方法的定义时添加HttpServletRequest入参即可,在方法体中直接使用request
<!--导入servlet的api-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
@RequestMapping("/request")
public String request(HttpServletRequest request) {
User user =new User();
user.setId(1);
user.setName("张三");
request.setAttribute("user",user);
return "show";
}
@ModelAttribute
- 定义一个方法来要填充到业务数据中的对线
- 给方法添加@ModelAttribute,只是添加对象,不做业务
@ModelAttribute
public User getUser(){
User user =new User();
user.setId(1);
user.setName("张三");
return user;
}
@RequestMapping("/modelAttribute")
public String ModelAttribute() {
return "show";
}
@ModelAttribute,当Handler无论接受到哪格方法都会先调用@ModelAttribute修饰的方法,并将返回值作为业务数据,此时业务方法只需要返回试图即可。
假如返回数据,还是会被@ModelAttribute的数据据覆盖。
而如果没有返回值,要手动填充Map或Model
直接给Model的优先级更高
key-value
key值默认是:对应类的小写首字母
业务数据绑定到Session
- HttpSession
@RequestMapping("/session")
public String session(HttpSession httpSession){
User user =new User();
user.setId(1);
user.setName("张三");
httpSession.setAttribute("user",user);
return "show";
}
} - @SessionAttributes注解
默认都是在request下添加,但是注解了@SessionAttributes都会自动的添加到Session中
@SessionAttributes(value = "user")
@SessionAttributes(type = User.Class)
多个:
@SessionAttributes(value = {"user","students"})
标签:return,SpringMVC,绑定,视图,user,ModelAndView,new,public,User 来源: https://www.cnblogs.com/HJZ114152/p/16406798.html