springMVC学习2
参数绑定
默认支持的参数类型
@Override public Item queryItemById(int id) {Item item = this.itemMapper.selectByPrimaryKey(id);return item; }
http://127.0.0.1:8080/springmvc-web/itemEdit.action?id=1
Id包含在Request对象中。可以从Request对象中取id
想获得Request对象只需要在Controller方法的形参中添加一个参数即可。Springmvc框架会自动把Request对象传递给方法
@RequestMapping("/itemEdit") public ModelAndView queryItemById(HttpServletRequest request) {// 从request中获取请求参数String strId = request.getParameter("id");Integer id = Integer.valueOf(strId);// 根据id查询商品数据Item item = this.itemService.queryItemById(id);// 把结果传递给页面ModelAndView modelAndView = new ModelAndView();// 把商品数据放在模型中modelAndView.addObject("item", item);// 设置逻辑视图modelAndView.setViewName("itemEdit");return modelAndView; }
处理器形参中添加如下类型的参数处理适配器会默认识别并进行赋值
Model/ModelMap
除了ModelAndView以外,还可以使用Model来向页面传递数据,
Model是一个接口,在参数里直接声明model即可。
如果使用Model则可以不使用ModelAndView对象,Model对象可以向页面传递数据,View对象则可以使用String返回值替代。
不管是Model还是ModelAndView,其本质都是使用Request对象向jsp传递数据。
@RequestMapping("/itemEdit") public String queryItemById(HttpServletRequest request, Model model) {// 从request中获取请求参数String strId = request.getParameter("id");Integer id = Integer.valueOf(strId);// 根据id查询商品数据Item item = this.itemService.queryItemById(id);// 把结果传递给页面// ModelAndView modelAndView = new ModelAndView();// 把商品数据放在模型中// modelAndView.addObject("item", item);// 设置逻辑视图// modelAndView.setViewName("itemEdit");// 把商品数据放在模型中model.addAttribute("item", item);return "itemEdit"; }
ModelMap
ModelMap是Model接口的实现类,也可以通过ModelMap向页面传递数据
使用Model和ModelMap的效果一样,如果直接使用Model,springmvc会实例化ModelMap。
@RequestMapping("/itemEdit") public String queryItemById(HttpServletRequest request, ModelMap model) {// 从request中获取请求参数String strId = request.getParameter("id");Integer id = Integer.valueOf(strId);// 根据id查询商品数据Item item = this.itemService.queryItemById(id);// 把结果传递给页面// ModelAndView modelAndView = new ModelAndView();// 把商品数据放在模型中// modelAndView.addObject("item", item);// 设置逻辑视图// modelAndView.setViewName("itemEdit");// 把商品数据放在模型中model.addAttribute("item", item);return "itemEdit"; }
绑定简单类型
当请求的参数名称和处理器形参名称一致时会将请求参数与形参进行绑定。
这样,从Request取参数的方法就可以进一步简化。
@RequestMapping("/itemEdit") public String queryItemById(int id, ModelMap model) {// 根据id查询商品数据Item item = this.itemService.queryItemById(id);// 把商品数据放在模型中model.addAttribute("item", item);return "itemEdit"; }
支持的数据类型
参数类型推荐使用包装数据类型,因为基础数据类型不可以为null
整形:Integer、int
字符串:String
单精度:Float、float
双精度:Double、double
布尔型:Boolean、boolean
说明:对于布尔类型的参数,请求的参数值为true或false。或者1或0
请求url:http://localhost:8080/xxx.action?id=2&status=false
处理器方法:public String editItem(Model model,Integer id,Boolean status)
@RequestParam
使用@RequestParam常用于处理简单类型的绑定,否则参数必须和前台的name一样
value:参数名字,即入参的请求参数名字,如value=“itemId”表示请求的参数 区中的名字为itemId的参数的值将传入
required:是否必须,默认是true,表示请求中一定要有相应的参数,否则将报错 HTTP Status 400 - Required Integer parameter 'XXXX' is not present
defaultValue:默认值,表示如果请求中没有同名参数时的默认值
@RequestMapping("/itemEdit") public String queryItemById(@RequestParam(value = "itemId", required = true, defaultValue = "1") Integer id,ModelMap modelMap) {// 根据id查询商品数据Item item = this.itemService.queryItemById(id);// 把商品数据放在模型中modelMap.addAttribute("item", item);return "itemEdit"; }
如果提交的参数很多,或者提交的表单中的内容很多的时候,可以使用简单类型接受数据,也可以使用pojo接收数据。
要求:pojo对象中的属性名和表单中input的name属性一致。
请求的参数名称和pojo的属性名称一致,会自动将请求参数赋值给pojo的属性
void updateItemById(Item item); 接口
使用updateByPrimaryKeySelective(item)方法,忽略空参数
@Override public void updateItemById(Item item) {this.itemMapper.updateByPrimaryKeySelective(item); }
@RequestMapping("/updateItem") public String updateItem(Item item) {// 调用服务更新商品this.itemService.updateItemById(item);// 返回逻辑视图return "success"; }
注意:提交的表单中不要有日期类型的数据,否则会报400错误。如果想提交日期类型的数据需要用到后面的自定义参数绑定的内容。
解决post乱码问题
提交发现,保存成功,但是保存的是乱码
在web.xml中加入:spring-web.jar
<!-- 解决post乱码问题 --> <filter><filter-name>encoding</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><!-- 设置编码参是UTF8 --><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param></filter><filter-mapping><filter-name>encoding</filter-name><url-pattern>/*</url-pattern></filter-mapping>
对于get请求中文参数出现乱码解决方法有两个
修改tomcat配置文件添加编码与工程编码一致,如下
<Connector URIEncoding="utf-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
另外一种方法对参数进行重新编码:
String userName new String(request.getParamter("userName").getBytes("ISO8859-1"),"utf-8")
ISO8859-1是tomcat默认编码,需要将tomcat编码后的内容按utf-8编码
使用包装的pojo接收商品信息的查询条件
public class QueryVo {private Item item; set/get。。。 }
接收查询条件
// 绑定包装数据类型@RequestMapping("/queryItem")public String queryItem(QueryVo queryVo) {System.out.println(queryVo.getItem().getId());System.out.println(queryVo.getItem().getName());return "success";}
自定义参数绑定
在商品修改页面可以修改商品的生产日期,并且根据业务需求自定义日期格式。
由于日期数据有很多种格式,springmvc没办法把字符串转换成日期类型。所以需要自定义参数绑定。
前端控制器接收到请求后,找到注解形式的处理器适配器,对RequestMapping标记的方法进行适配,并对方法中的形参进行参数绑定。可以在springmvc处理器
适配器上自定义转换器Converter进行参数绑定。
一般使用<mvc:annotation-driven/>注解驱动加载处理器适配器,可以在此标签上进行配置。
自定义Converter
//Converter<S, T> //S:source,需要转换的源的类型 //T:target,需要转换的目标类型 public class DateConverter implements Converter<String, Date> {@Overridepublic Date convert(String source) {try {// 把字符串转换为日期类型SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");Date date = simpleDateFormat.parse(source);return date;} catch (ParseException e) {e.printStackTrace();}// 如果转换的时候出现异常则返回空return null;} }
配置Converter
我们同时可以配置多个的转换器
<!-- 配置注解驱动 --> <!-- 如果配置此标签,可以不用配置... --> <mvc:annotation-driven conversion-service="conversionService" /><!-- 转换器配置 --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"><property name="converters"><set><bean class="cn.itcast.springmvc.converter.DateConverter" /></set></property> </bean>
配置方式2(了解)
<!--注解适配器 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"><property name="webBindingInitializer" ref="customBinder"></property> </bean><!-- 自定义webBinder --> <bean id="customBinder" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer"><property name="conversionService" ref="conversionService" /> </bean><!-- 转换器工厂配置 --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"><property name="converters"><set><bean class="cn.itcast.springmvc.convert.DateConverter" />自定义转换</set></property> </bean>
注意:此方法需要独立配置处理器映射器、适配器 不再使用<mvc:annotation-driven/>
springmvc与struts2不同
1、 springmvc的入口是一个servlet即前端控制器,而struts2入口是一个filter过滤器。
2、 springmvc是基于方法开发(一个url对应一个方法),请求参数传递到方法的形参,可以设计为单例或多例(建议单例),struts2是基于类开发,传递
参数是通过类的属性,只能设计为多例。
3、 Struts采用值栈存储请求和响应的数据,通过OGNL存取数据, springmvc通过参数解析器是将request请求内容解析,并给方法形参赋值,将数据和
视图封装成ModelAndView对象,最后又将ModelAndView中的模型数据通过request域传输到页面。Jsp视图解析器默认使用jstl。
转载于:https://www.cnblogs.com/escapist/p/9050519.html
springMVC学习2相关推荐
- SpringMVC:学习笔记(11)——依赖注入与@Autowired
SpringMVC:学习笔记(11)--依赖注入与@Autowired 使用@Autowired 从Spring2.5开始,它引入了一种全新的依赖注入方式,即通过@Autowired注解.这个注解允许 ...
- SpringMVC 学习-异常处理 SimpleMappingExceptionResolver 类
SpringMVC 学习-异常处理 SimpleMappingExceptionResolver 类 参考文章: (1)SpringMVC 学习-异常处理 SimpleMappingException ...
- SpringMVC:学习笔记(10)——整合Ckeditor且实现图片上传
SpringMVC:学习笔记(10)--整合Ckeditor且实现图片上传 配置CKEDITOR 精简文件 解压之后可以看到ckeditor/lang下面有很多语言的js,如果不需要那么多种语言的,可 ...
- (转)SpringMVC学习(三)——SpringMVC的配置文件
http://blog.csdn.net/yerenyuan_pku/article/details/72231527 读者阅读过SpringMVC学习(一)--SpringMVC介绍与入门这篇文章后 ...
- springmvc学习笔记(10)-springmvc注解开发之商品改动功能
springmvc学习笔记(10)-springmvc注解开发之商品改动功能 springmvc学习笔记(10)-springmvc注解开发之商品改动功能 标签: springmvc springmv ...
- SpringMVC学习(五)——零配置实现SpringMVC
文章目录 1.引言 2.搭建过程 2.1 开发环境搭建 2.2 项目搭建 2.2.1 首先看`web.xml`配置 2.2.2 增加`WebApplicationInitializer`的实现类 2. ...
- SpringMVC学习(二)——快速搭建SpringMVC开发环境(注解方式)
文章目录 说明 1.工程搭建 2.注解配置 2.1.context:annotation-config说明 2.2.context:component-scan配置说明 2.3.mvc:annotat ...
- springmvc学习笔记(19)-RESTful支持
springmvc学习笔记(19)-RESTful支持 标签: springmvc springmvc学习笔记19-RESTful支持 概念 REST的样例 controller REST方法的前端控 ...
- SpringMVC:学习笔记(5)——数据绑定及表单标签
SpringMVC--数据绑定及表单标签 理解数据绑定 为什么要使用数据绑定 基于HTTP特性,所有的用户输入的请求参数类型都是String,比如下面表单: 按照我们以往所学,如果要获取请求的所有参数 ...
- (转)SpringMVC学习(一)——SpringMVC介绍与入门
http://blog.csdn.net/yerenyuan_pku/article/details/72231272 SpringMVC介绍 SpringMVC是什么? SpringMVC和Stru ...
最新文章
- Django—Model就是ORM的具体体现
- Hibernate基础小案例
- 2015最火十大Android开源项目,是个程序员你就该看看!
- 关于 java.toString() ,(String),String.valueOf的区别
- Linux的实际操作:用户管理(查看用户和组的配置文件/etc/passwd /etc/group /etc/shadow)
- synchronized(this)、synchronized(class)与synchronized(Object)的区别
- Java数据库编程---JDBC操作步骤及数据库连接操作
- protel99se原理图的元件符号和封装符号大全
- 百度 95 后程序员删库跑路被判刑
- Contrastive Search Decoding——一种对比搜索解码文本生成算法
- Zabbix5.0监控CenterOS(RPM版)
- LAN9252/3 EtherCAT module
- 异常处理(六)--------SpringBoot+Maven项目运行异常:Unable to find a single main class from the following candidat
- 【有感】失去人性,失去很多;失去兽性,失去一切
- c++函数模板--(函数模板的定义)
- iacr crypto 级别_上证综指率先确认日线级别下跌
- linux 使用 mondo rescue 备份 还原系统 iso u盘
- guacamole1.4.0安装记录
- 如实使用Mixly按键控制LED灯
- Latex三线表格(6/8/2022)
热门文章
- Treeview 无限分类非递归终极解决方案VB
- html5图片格式有什么,jpeg是什么?
- 畅享7 plus android8,华为畅享7plus和荣耀8哪个好?荣耀8与畅享7plus详细区别对比评测...
- Android 检索相册视频文件
- python基本类型关键字_python中的关键字---1(基础数据类)
- hacker与cracker区别
- thinkphp5 域名路由
- pdf合并成一个pdf怎么合并
- SSH连接服务器Secure CRT技巧[Secure CRT连接ubuntu显示密钥交换失败][Ubuntu无法使用root用户登陆的解决办法]
- 涨姿势 , JavaScript 玩转多线程编程~