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 ...
随机推荐
- BZOJ 2626: JZPFAR KDtree + 堆
Code: #include<bits/stdc++.h> #define maxn 200000 #define inf 1000000000000000 #define mid ((l ...
- hdu 4870
Rating Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Sub ...
- 洛谷 2387 NOI2014魔法森林 LCT
[题解] 我们先把边按照$a$值从小到大排序,并按照这个顺序加边. 如果当前要加入的边连接的两点$u$与$v$已经是连通的,那么直接加入这条边就会出现环.这时我们需要删除这个环中$b$值最大的边.因此 ...
- BZOJ 1452 Count 【模板】二维树状数组
对每种颜色开一个二维树状数组 #include<cstdio> #include<algorithm> using namespace std; ; ][maxn][maxn] ...
- PAT 1108 Finding Average
The basic task is simple: given N real numbers, you are supposed to calculate their average. But wha ...
- zoj 3693
#include<stdio.h> #include<string.h>//进位问题如3.985 应该进位3.99 int main() { int n,k,i; ...
- springCloud学习-服务消费者(rest+ribbon)
1.ribbon简介 spring cloud的Netflix中提供了两个组件实现软负载均衡调用:ribbon和feign. Ribbon 是一个基于 HTTP 和 TCP 客户端的负载均衡器 它可以 ...
- Spring整体架构
Spring整体架构 Spring的整体架构 Spring框架是分层架构的,它包含了一系列的功能要素. Spring整体架构图 模块分类 1. Core Container Core Containe ...
- ZooKeeper动态增加Server(动态增加节点)的研究(待实践)
说明:是动态增加Server,不是动态增加连接到ZK Server的Client. 场景如下(转自外文): 1.在t=t_1->[peer-1(Leader),peer-2],peer-1是主节 ...
- N天学习一个linux命令之xz
前言 最近使用gitbook写接口文档,gitbook需要nodejs执行环境.安装nodejs时,发现安装包使用的是xz后缀,它是使用LZMA无损数据压缩算法生成的文件,压缩率很高.GNU已经内置了 ...