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; }
直接给视图
@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; }
传递view对象
@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"})
SpringMVC的数据绑定与视图解析的更多相关文章
- SSM-SpringMVC-12:SpringMVC中BeanNameViewResolver这种视图解析器
------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- 视图解析器,这个很熟悉啊,之间就用过,就是可以简写/和.jsp的InternalResourceViewRes ...
- SpringMVC中支持多视图解析
版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/suo082407128/article/details/70173301 在SpringMVC模式当 ...
- SpringMVC什么时候配置 视图解析器
当Action返回的是一个真实路径的时候,视图解析器可不进行配置 当Action返回的是逻辑路径的时候,我们必须要在配置文件中注册视图解析器并为该逻辑路径添加前缀和后缀
- springMVC源码解析--ViewResolverComposite视图解析器集合(二)
上一篇博客springMVC源码分析--ViewResolver视图解析器(一)中我们介绍了一些springMVC提供的很多视图解析器ViewResolver,在开发的一套springMVC系统中是可 ...
- SpringMVC系列(七)视图解析器和视图
在springmvc.xml里面配置视图解析器 <!-- 配置视图解析器: 如何把 handler 方法返回值解析为实际的物理视图 --> <bean class="org ...
- [刘阳Java]_InternalResourceViewResolver视图解析器_第6讲
SpringMVC在处理器方法中通常返回的是逻辑视图,如何定位到真正的页面,就需要通过视图解析器 InternalResourceViewResolver是SpringMVC中比较常用视图解析器. 网 ...
- day04-视图和视图解析器
视图和视图解析器 1.基本介绍 在SpringMVC中的目标方法,最终返回的都是一个视图(有各种视图) 注意,这里的视图是一个类对象,不是一个页面!! 返回的视图都会由一个视图解析器来处理(视图解析器 ...
- SpringMVC框架——视图解析
SpringMVC视图解析,就是将业务数据绑定给JSP域对象,并在客户端进行显示. 域对象: pageContext.request.session.application 业务数据绑定是有ViewR ...
- SpringMVC视图解析器
SpringMVC视图解析器 前言 在前一篇博客中讲了SpringMVC的Controller控制器,在这篇博客中将接着介绍一下SpringMVC视 图解析器.当我们对SpringMVC控制的资源发起 ...
- 学习SpringMVC——说说视图解析器
各位前排的,后排的,都不要走,咱趁热打铁,就这一股劲我们今天来说说spring mvc的视图解析器(不要抢,都有位子~~~) 相信大家在昨天那篇如何获取请求参数篇中都已经领略到了spring mvc注 ...
随机推荐
- SpringCloud(十一)- 秒杀 抢购
1.流程图 1.1 数据预热 1.2 抢购 1.3 生成订单 (发送订单消息) 1.4 订单入库 (监听 消费订单消息) 1.5 查看订单状态 1.6 支付 (获取支付链接 ) 1.7 支付成功 微信 ...
- ArcObjects SDK开发 008 从mxd地图文件说起
1.Mxd文件介绍 ArcGIS的地图文件为.mxd扩展名.Mxd文件的是有版本的,和ArcGIS的版本对应.可以在ArcMap中的File-Save A Copy,保存一个地图拷贝的时候选择Mxd文 ...
- js-day05-对象
为什么要学习对象 没有对象时,保存网站用户信息时不方便,很难区别 对象是什么 1.对象是一种数据类型 2.无序的数据集合 对象有什么特点 1.无序的数据的集合 2.可以详细的描述某个事物' 对象使用 ...
- Spring04:JdbcTemplate及事务控制(AOP、XML、注解)
今日内容 Spring中的JdbcTemplate 作业:Spring基于AOP的事务控制 Spring中的事务控制 基于XML的 基于注解的 一.JdbcTemplate 1.JdbcTemplat ...
- JavaEE Day02MySQL
今日内容 数据库的基本概念 MySQL数据库软件 安装 卸载 配置 SQL语句 一.数据库的基本概念 1.数据库DataBase,简称DB 2.什么是数据库? 用于存储和管理数据的仓库 ...
- Gepetto:使用chatGPT来对函数功能进行分析并重命名变量的IDA插件
最近OpenAI的chatGPT很火,chatGPT是一个大型的语言模型,能够生成人类语言的文本,主要用于对话式的问答和聊天,以及模拟人类的对话行为 有关chatGPT的介绍就不多赘述了,相关内容很多 ...
- SQLMap入门——获取表中的字段名
查询表名之后,查询表中的字段名 python sqlmap.py -u http://localhost/sqli-labs-master/Less-1/?id=1 -D xssplatform -T ...
- EXACT函数
EXACT函数:EXACT函数是一个文本函数,通过这个函数可以将不同的字符串进行对比,通常用于信息核对. EXACT函数的功能:比较两个字符串是否一致,返回不同的结果. EXACT函数的语法结构:EX ...
- 使用pip命令安装库时提示Could not build wheels for six, since package 'wheel' is not installed
在使用pip命令安装库时提示Could not build wheels for six, since package 'wheel' is not installed 解决以上问题可用 pip in ...
- React报错之React.Children.only expected to receive single React element child
总览 当我们把多个子元素传递给一个只期望有一个React子元素的组件时,会产生"React.Children.only expected to receive single React el ...