SpringMVC参数绑定(二)
在springMVC中,提交请求的数据是通过方法形参来接收的,从客户端请求的key/value数据,经过参数绑定,将key/value数据绑定到controller形参上,然后再controller就可以直接使用该形参。
默认支持的类型
springMVC有支持的默认参数类型,我们直接在形参上给出这些默认类型的生命,就可以直接使用了。其中httpservletRequest对象需要导入tomcat-servlet包。
1.HttpServletRequest对象
2.HttpSerletResponse对象
3.HttpSession对象
4.Model/ModelMap对象
@RequestMapping("/edit")
public ModelAndView edit(HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model, ModelMap modelMap) throws IOException {
String id = request.getParameter("id");
request.setAttribute("request",id);
response.getWriter().write("response");
session.setAttribute("session",id);
model.addAttribute("model",id);
modelMap.addAttribute("modelMap",id);
ModelAndView mav = new ModelAndView();
mav.setViewName("edit");
return mav;
}
jsp页面
<html>
<head>
<title>edit</title>
</head>
<body>
${request} ${session} ${model} ${modelMap}
</body>
</html>
测试地址:/product/eidt?id=112
Model/ModelMap,ModelMap是Model借口的一个实现类,作用是将Model数据填充到request域,即使使用Model接口,其内部还是由ModelMap来实现。
基本数据类型的绑定
byte、short、int、long、float、double、char、boolean
@RequestMapping("/query")
public ModelAndView Query(Integer id){
System.out.print(id);
return new ModelAndView("edit");
}
输入路径测试http://localhost:9999/product/query?id=123
这里输入的参数值和controller的参数变量名保持一致,就能完成数据绑定,如果不一致可以使用@RequestParam注解来完成
@RequestMapping("/query")
public ModelAndView Query(@RequestParam("username")int id){
System.out.print(id);
return new ModelAndView("edit");
}
因为是基本数据类型,所以如果前台传递的值是?id=null的话就会数据转换异常,所以这里最好将参数类型定义成包装类。
包装类数据类型的绑定
Integer、Long、Byte、Double、Float、Short、String
public ModelAndView Query(@RequestParam("username")Integer id){
虽然可以?id=null 但是不写?id=又会报错 ,可以设定默认值以及是否必传
@RequestMapping(value="/say",method=RequestMethod.GET)
public String say(@RequestParam(value="id",required=false,defaultValue="0") Integer myId)
POJO(实体类)类型的绑定
Product.java
package com.david.pojo;
import java.util.Date;
public class Product {
private Integer id;
private String name;
private String price;private Integer categoryId;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
}
参数要与pojo实体类的属性保持一致即可映射成功
@RequestMapping(value = "/add",method = RequestMethod.POST)
public ModelAndView add(Product product){
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
ProductMapper mapper = ac.getBean(ProductMapper.class);
mapper.addProduct(product);
return new ModelAndView("edit");
}
jsp
<form action="/product/add" method="post">
<input name="id">
name:<input name="name">
price:<input name="price">
<button type="submit">提交</button>
</form>
post数据乱码解决
web.xml
<!--post乱码 -->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
绑定包装pojo类
新建一个包装类 QueryVo 包含Product属性
public class QueryVo {
private Product product;
private String name;
private String img;
}
编辑controller
<form action="/product/query" method="post">
img:<input name="img">
name:<input name="name">
proname:<input name="product.name">
proprice:<input name="product.price">
<button type="submit">提交</button>
</form>
在表单中使用该对象属性名.属性来命名如 product.name
自定义参数类型绑定
由于日期有很多种,springmvc没办法把字符串转换为日期类型,所以需要自定义参数绑定。
1.定义String类型到Date类型的转换器
package com.david.utils; import org.springframework.core.convert.converter.Converter; import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date; public class DateConverter implements Converter<String, Date> {
@Override
public Date convert(String s) {
//实现将字符串转成日期类型(格式是yyyy-MM-dd HH:mm:ss)
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
return dateFormat.parse(s);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//如果参数绑定失败返回null
return null;
}
}
2.在springmvc.xml文件中配置转换器
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<!-- 自定义转换器的类名 -->
<bean class="com.david.utils.DateConverter"></bean>
</property>
</bean>
3.修改queryVo
public class QueryVo {
private Product product;
private String name;
private String img;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date createTime;
。。。
4.jsp
<form action="/product/query" method="post">
createTime:<input name="createTime">
<button type="submit">提交</button>
</form>
数组类型的绑定
@RequestMapping("/query")
public ModelAndView Query(Integer[] nums){
for(int i : nums){
System.out.println(i);
}
return new ModelAndView("edit");
}
<form action="/product/query" method="post">
createTime:<input name="nums"><input name="nums"><input name="nums"><input name="nums">
<button type="submit">提交</button>
</form>
List类型的绑定
需要定义包装类 实现List绑定-不能直接形参List
package com.david.pojo;
import java.util.List;
public class QueryVo {
private List<Product> products;
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
}
@RequestMapping("/query")
public ModelAndView Query(QueryVo vo){
for(Product p : vo.getProducts()){
System.out.println(p);
}
return new ModelAndView("edit");
}
<form action="/product/query" method="post">
createTime:<input name="products[0].name"><input name="products[0].price"> <input name="products[1].name">
<button type="submit">提交</button>
</form>
springMVC和struts2的区别
1.springmvc的入口是一个servlet前端控制器,而struts2入口是一个filter过滤器
2.springmvc是基于方法开发,请求参数传递到方法的形参,可以设计为单例或多例,struts2是基于类开发啊传递参数是通过类的属性,只能设计为多例。
3.struts2采用值栈请求和相应数据,通过ognl存取数据,springmvc通过参数解析器将request请求内容解析,并给方法形参赋值,将数据和视图凤凰族昂成ModelAndView对象,最后又将ModelAndView中的模型数据通过request域传输到页面。
SpringMVC参数绑定(二)的更多相关文章
- SpringMvc参数绑定出现乱码解决方法
在SpringMvc参数绑定过程中出现乱码的解决方法 1.post参数乱码的解决方法 在web.xml中添加过滤器 <!-- 过滤器 处理post乱码 --> <filter> ...
- 一篇文章搞定SpringMVC参数绑定
SpringMVC参数绑定,简单来说就是将客户端请求的key/value数据绑定到controller方法的形参上,然后就可以在controller中使用该参数了 下面通过5个常用的注解演示下如何进行 ...
- [转载]SpringBoot系列: SpringMVC 参数绑定注解解析
本文转载自 https://www.cnblogs.com/morethink/p/8028664.html, 作者写得非常好, 致谢! SpringMVC 参数绑定注解解析 本文介绍了用于参数绑 ...
- SpringMVC参数绑定,这篇就够了!
SpringMVC参数绑定,简单来说就是将客户端请求的key/value数据绑定到controller方法的形参上,然后就可以在controller中使用该参数了 下面通过5个常用的注解演示下如何进行 ...
- SpringMVC参数绑定(未完待续)
1. Strut2与SpringMVC接收请求参数的区别 Struts2通过action类的成员变量接收SpringMVC通过controller方法的形参接收 2. SpringMVC参数绑定流程 ...
- 【工作篇】再次熟悉 SpringMVC 参数绑定
前言 主要现在项目中使用的参数绑定五花八门的,搞得很头大,例如有些用字符串接收日期,用字符串接受数组等等,完全没有利用好 SpringMVC 的优势,这里自己也总结一下,免得到时又要百度谷歌查找. 以 ...
- SpringMVC参数绑定(从请求中接受参数)
参数绑定(从请求中接收参数) 1)默认类型: 在controller方法中可以有也可以没有,看自己需求随意添加. httpservletRqeust,httpServletResponse,httpS ...
- SpringMVC 参数绑定注解解析
本文介绍了用于参数绑定的相关注解. 绑定:将请求中的字段按照名字匹配的原则填入模型对象. SpringMVC就跟Struts2一样,通过拦截器进行参数匹配. 代码在 https://github.co ...
- SpringMVC参数绑定总结
springMvc作用: a) 接收请求中的参数 b) 将处理好的数据返回给页面参数绑定(就是从请求中接收参数): a) 默认支持的类型: request, response, se ...
随机推荐
- @Override注解
@Override注解对于代码可读性的提升十分巨大 而且良好的可读性是一个优秀程序员必备的基础素养
- 解决hibernate删除时的异常 deleted object would be re-saved by cascade (remove deleted object from associa
今天在做项目时,需要删除一个对象,由于关联关系是一对多和多对一的关系,于是在代码中需要删除多的一方的对象时出现了 deleted object would be re-saved by cascade ...
- Lua之尾调函数的用法
Lua之尾调函数的用法 --当函数的最后返回结果调用另一个函数,称之为尾调函数 function f(x) return g(x) end --由于“尾调用”不会耗费栈空间,所以一个程序可以拥有无数嵌 ...
- C#关键字详解第一节
abstract:抽象类: 他表达对问题或者实际中的事物,对象等所设计出的抽象概念,比如一个灵感.生物等,这些都是抽像, 但是他们往往也有具体的指向,比如生物圈有人类,猴子,老虎等等,老虎和人类是实际 ...
- Maven学习总结(8)——使用Maven构建多模块项目
Maven学习总结(八)--使用Maven构建多模块项目 在平时的Javaweb项目开发中为了便于后期的维护,我们一般会进行分层开发,最常见的就是分为domain(域模型层).dao(数据库访问层). ...
- 3、ceph-deploy之配置使用文件系统
我们在admin节点执行下述操作,来配置使用ceph集群的文件系统 必备条件 1.在ceph-client节点安装ceph ceph-deploy install ceph-client 2.确认ce ...
- (39.1) Spring Boot Shiro权限管理【从零开始学Spring Boot】
(本节提供源代码,在最下面可以下载)距上一个章节过了二个星期了,最近时间也是比较紧,一直没有时间可以写博客,今天难得有点时间,就说说Spring Boot如何集成Shiro吧.这个章节会比较复杂,牵涉 ...
- linux下华为HSPA模块MU609的驱动问题
环境: CPU: s3c2416 Linux: 3.6 模块: HUAWEI MU609 SIM卡: 移动3G卡.移动4G卡 首先,拿到MU609模块后,第一要做的是对模块进行一些熟悉与了解,那么资料 ...
- php导入sql文件
php导入sql文件 sql php php导入sql文件 基本思路 1.打开sql文件,放入一个变量(字符串类型)其中 2.使用正则替换掉其中的凝视("--"与"/** ...
- vsftpd出现“Response: 500 OOPS: cannot change directory”解决方法(转载)
vsftpd出现“Response: 500 OOPS: cannot change directory”解决方法 笔者用的Linux发行版本为centos当用FTP客户端连接时,出现如下错误提示 ...