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 ...
随机推荐
- EF-Linq
一丶基本语法(from a in Table where a.id="001" select a).Tolist(); 隐式内连接from a in table1 join b i ...
- C# 通知机制 IObserver<T> 和 IObservable<T>
class Program { public static void Main() { // Define a provider and two observers. LocationTracker ...
- 入口文件 index.php
一. 运行流程 The index.php serves as the front controller, initializing the base resources needed to run ...
- CF51F Caterpillar (边双+树形DP)
题目传送门 题目大意:给你一张n个点m条边的图.每次操作可以把两个点合并成一个(与之相连的边也都要连到新点上).求把图中每个联通块都变成“毛毛虫”的最小操作次数.“毛毛虫”必须是一棵树(可以存在自环) ...
- models中,字段参数limit_choices_to的用法
这里,在使用 ModelForm 渲染前端页面的前提下,对于 models 中的 ManyToManyField 类型字段会在 ModelForm 中被转化为 ModelMultipleChoiceF ...
- shell 读取目录指定文件并截取拼接
shell脚本读取指定文件并拼接成指定的版本信息
- zend studio【快捷键】
=================================[快捷键 zend studio]========== 1.调出查找面板[ctrl+f] 2.全文检索[ctrl+h] 3.关闭当前文 ...
- hdu2000 ASCII码排序【C++】
ASCII码排序 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Su ...
- 00107_TCP通信
1.TCP通信的概述 (1)TCP通信同UDP通信一样,都能实现两台计算机之间的通信,通信的两端都需要创建socket对象: (2)区别在于: ①UDP中只有发送端和接收端,不区分客户端与服务器端,计 ...
- 用keil编写的 C51错误 *** WARNING L1: UNRESOLVED EXTERNAL SYMBOL SYMBOL: ?C_START
可能原因: 替换工程的文件未先 remove该文件. 正常替换文件步骤: 1. 右键 欲 替换的文件,remove XXXXX.c from build ----> remove XXXX ...