一、前言

之前我们通过springMVC前三章讲解了,springMVC的配置以及与mybatis整合的配置运用。这一章是具体的一些操作,可以直接看看项目,下载下来就ok;

二、Controller的返回结果

我们之前都是用modelAndView

1、现在我们看看所有Controller返回方式:void、String、modelAndView

2、

重定向redirect:request无法共享,url变化 用例:"redirect:url"

页面转发forword:request共享,url不变化 用例:"forward:url"

package com.ycy.controller;import com.ycy.dto.ItemsCustom;
import com.ycy.service.ItemsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;import java.util.List;/*** Created by Administrator on 2015/9/17 0017.*/
@Controller
@RequestMapping("/items")
public class ItemController {//注入service@Autowiredprivate ItemsService itemsService;/*** 商品展示** @param httpServletRequest* @param httpServletResponse* @return* @throws Exception*/@RequestMapping("/queryItems")public ModelAndView queryItems(javax.servlet.http.HttpServletRequest httpServletRequest,javax.servlet.http.HttpServletResponse httpServletResponse) throws Exception {//如果是转发:httpServletRequest的数据是可以共享的ItemsCustom itemsCustom = new ItemsCustom();itemsCustom.setId(1);//商品列表List<ItemsCustom> itemsList = itemsService.findtemsList(null);//创建modelAndView准备填充数据、设置视图ModelAndView modelAndView = new ModelAndView();//填充数据modelAndView.addObject("itemsList", itemsList);//视图modelAndView.setViewName("order/itemsList");return modelAndView;}/*** 修改商品信息1.1* @return* @throws Exception*/@RequestMapping("/editItems1")public ModelAndView editItems() throws Exception {ModelAndView modelAndView = new ModelAndView();ItemsCustom itemsCustom = itemsService.getItemsById(1, null);modelAndView.addObject("item",itemsCustom);modelAndView.setViewName("order/editItem");return modelAndView;}/*** 修改商品信息1.2* @return* @throws Exception*/@RequestMapping("/editItems2")public String editItems(Model model) throws Exception {ModelAndView modelAndView = new ModelAndView();ItemsCustom itemsCustom = itemsService.getItemsById(1, null);model.addAttribute("item", itemsCustom);return "order/editItem";}/*** 修改商品信息1.3* @return* @throws Exception*/@RequestMapping("/editItems")public void editItems(javax.servlet.http.HttpServletRequest httpServletRequest,javax.servlet.http.HttpServletResponse httpServletResponse) throws Exception {ModelAndView modelAndView = new ModelAndView();ItemsCustom itemsCustom = itemsService.getItemsById(1, null);httpServletRequest.setAttribute("item", itemsCustom);httpServletRequest.getRequestDispatcher("/pages/jsp/order/editItem.jsp").forward(httpServletRequest,httpServletResponse);/*** 使用此方法,容易输出json、xml格式的数据:通过response指定响应结果,例如响应json数据如下:response.setCharacterEncoding("utf-8");response.setContentType("application/json;charset=utf-8");response.getWriter().write("json串");*/}/*** 修改商品属性* @return*/@RequestMapping("/editItemSubmit")public String editItemSubmit(){//重定向  request数据无法共享,url地址栏会发生变化的 页面地址:editItemSubmitreturn  "redirect:queryItems";//转发   request数据可以共享,url地址栏不会变化 页面地址:queryItems//return  "forward:queryItems";}
}

三、Controller的参数

来自摘抄:

早期springmvc是使用PropertyEditor属性编辑器进行参数绑定(仅支持由字符串传为其它类型)

后期springmvc是使用converter转换器进行参数绑定(支持任意类型转换)

参数类型:

1、HttpServletRequest:请求信息

2、HttpServletResponse:处理响应

3、HttpSession:得到session中值

4、Model:通过Model向页面传递数据

5、@RequestParam:对应形参一样自动匹配,否则指定匹配。可以设置默认值,可以设定是否必须传递。

6、简单类型与po类型:int 、double、string、 boolean、 实体UserInfo

示例如下:

  @RequestMapping("/testRequestParam")public  void testRequestParam(@RequestParam(value="queryName", required=true,defaultValue = "") String name ){// 上面的对传入参数指定为queryName,如果前端不传queryName参数名,会报错// required=false表示不传的话,会给参数赋值为null,required=true就是必须要有}@RequestMapping("/testModel")public  String testModel(Model model )throws Exception {ModelAndView modelAndView = new ModelAndView();ItemsCustom itemsCustom = itemsService.getItemsById(1, null);model.addAttribute("item", itemsCustom);return "order/editItem";}@RequestMapping("/testHttpSession")public  void testHttpSession(HttpSession  httpSession )throws Exception {httpSession.getAttribute("username");}@RequestMapping("/testHttpSession")public  void testHttprequest(javax.servlet.http.HttpServletRequest httpServletRequest,javax.servlet.http.HttpServletResponse httpServletResponse)throws Exception {httpServletRequest.setAttribute("obj", null);httpServletRequest.getRequestDispatcher("/pages/jsp/XXX/XXXX.jsp").forward(httpServletRequest,httpServletResponse);}

2.1自定义参数(了解)

例如:springMvc没定义日期类型绑定。需要自定义!!!

2.1.1 Controller内自定义属性编辑器

在每一个Controller类里面加一个这样的方法就可以转换日期格式了哦,或者用在父类写入这个方法,继承一个父类就OK。
 //自定义编辑器/*** 注册属性编辑器(字符串转换为日期)*/@InitBinderpublic void initBinder(WebDataBinder binder) throws Exception {binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH-mm-ss"),true));//System.out.println("init binder =======================");binder.registerCustomEditor(BigDecimal.class, new CustomNumberEditor(BigDecimal.class, false));binder.registerCustomEditor(Integer.class, null,new CustomNumberEditor(Integer.class, null, true));binder.registerCustomEditor(Long.class, null, new CustomNumberEditor(Long.class, null, true));binder.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class, true));binder.registerCustomEditor(Double.class, new CustomNumberEditor(Double.class, true));binder.registerCustomEditor(BigInteger.class, new CustomNumberEditor(BigInteger.class, true));}

2.1.2属性 配置编译器xml

1、编写属性编译器java类:propertyeditor
package com.ycy.propertyeditor;import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistry;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;import java.beans.PropertyEditor;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;/**自定义属性编辑器* Created by Administrator on 2015/9/24 0024.*/
public class CustomPropertyEditor implements PropertyEditorRegistrar {@Overridepublic void registerCustomEditors(PropertyEditorRegistry binder) {binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH-mm-ss"),true));//System.out.println("init binder =======================");binder.registerCustomEditor(BigDecimal.class, new CustomNumberEditor(BigDecimal.class, false));binder.registerCustomEditor(Integer.class, null,new CustomNumberEditor(Integer.class, null, true));binder.registerCustomEditor(Long.class, null, new CustomNumberEditor(Long.class, null, true));binder.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class, true));binder.registerCustomEditor(Double.class, new CustomNumberEditor(Double.class, true));binder.registerCustomEditor(BigInteger.class, new CustomNumberEditor(BigInteger.class, true));}
}

2、在handlerAdapter适配器中加入我们的属性适配器

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-4.0.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-4.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.0.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-4.0.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-4.0.xsd "><!--1、=========================dispatcher已经在web.xml里面配置==================================--><!-- 使用spring组件扫描 --><context:component-scan base-package="com.ycy.controller"/><!-- 2、3 通过annotation-driven可以替代下边的处理器映射器和适配器 --><!--     <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>--><!--2、=======================使用注解RequestMappingInfoHandlerMapping映射器======================--><bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/><!--3、=============================处理器适配器HandlerAdapter====================================--><bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"><!--注解适配器:加入我们的属性解析器 --><property name="webBindingInitializer" ref="customBinder"></property></bean><!--4、============================视图解析器ViewResolver======================================--><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/><property name="prefix" value="/pages/jsp/"/><property name="suffix" value=".jsp"/></bean><!--5、视图view与hanlder需要自己实现--><!-- ================================自定义webBinder:属性编辑器===================================--><bean id="customBinder"class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer"><property name="propertyEditorRegistrars"><list><!-- 注册属性编辑器 --><bean id="customPropertyEditor" class="com.ycy.propertyeditor.CustomPropertyEditor" /></list></property></bean></beans>

2.2参数转换器(必须掌握)

2.2.1 配置方式1针对不使用<mvc:annotation-driven>

1首先编写java转换器
package com.ycy.controller.converter;import org.springframework.core.convert.converter.Converter;import java.text.SimpleDateFormat;
import java.util.Date;/*** Created by Administrator on 2015/9/24 0024.*/
public class CustomDateConverter implements Converter<String, Date> {@Overridepublic Date convert(String source) {try {SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");return simpleDateFormat.parse(source);} catch (Exception e) {e.printStackTrace();}return null;}}</span>

2其次根据写的Jva类配置springMcv.xml

 <bean id="customBinder"class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer"><property name="conversionService" ref="conversionService" /></bean><!-- conversionService --><bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"><!-- 转换器 --><property name="converters"><list><bean class="com.ycy.controller.converter.CustomDateConverter"/></list></property></bean>

3加入适配器

 <!--3、=============================处理器适配器HandlerAdapter====================================--><bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"><!--注解适配器:加入我们的属性解析器 --><property name="webBindingInitializer" ref="customBinder"></property></bean>

2.2.2 配置方式2针对使用<mvc:annotation-driven>的配置

1首先编写java转换器同上

2配置xml

<!-- conversionService --><bean id="conversionService"class="org.springframework.format.support.FormattingConversionServiceFactoryBean"><!-- 转换器 --><property name="converters"><list><bean class="com.ycy.controller.converter.CustomDateConverter"/></list></property></bean>

3加入适配器

<mvc:annotation-driven conversion-service="conversionService">
</mvc:annotation-driven>

四、Controller的总结

这一讲主要讲解Controlleer的返回结果,传入参数。加上mybatis的缓存等等(看mybatis篇先),基本上能够应对你的项目开发的全部。但是发现没有,你熟悉的Json转换器怎么不出现在参数转换与结果返回里面??下一章开始进行中级讲解,就会有一些好用的图片上传、拦截器之类的。

springMVC教程初级(四)Controller篇(结果、参数 )相关推荐

  1. 最全面的SpringMVC教程(四)——Controller 与 RestFul

    前言 本文为 [SpringMVC教程]Controller 与 RestFul 相关内容介绍,具体将对控制器Controller,实现Controller接口,使用注解@Controller,Req ...

  2. Express全系列教程之(四):获取Post参数的两种方式

    一.关于POST请求 post方法作为http请求很重要的一部分,几乎所有的网站都有用到它,与get不同,post请求更像是在服务器上做修改操作,它一般用于数据资源的更新. 相比于get请求,post ...

  3. AI绘图软件分享:Midjourney 基础教程(四)参数进阶

    大家好,我是网媒智星,今天我们继续来学习Midjourney 基础教程(四):Midjourney 参数进阶. 通过前⼏篇⽂章的学习,我们知道了,想要掌握 Midjourney AI 绘画技术,先需要 ...

  4. MVC教程第四篇:传递表单数据

    MVC教程第四篇:传递表单数据     摘要 本文将完成我们"MVC公告发布系统"的公告发布功能,以此展示在ASP.NET MVC中如何传递处理表单的数据. 前言 通过前几篇文章, ...

  5. SpringCloud核心教程 | 第四篇:服务注册与发现 Consul篇

    Spring Cloud简介 Spring Cloud是一个基于Spring Boot实现的云应用开发工具,它为基于JVM的云应用开发中涉及的配置管理.服务发现.断路器.智能路由.微代理.控制总线.全 ...

  6. 史上最简单的SpringCloud教程 | 第四篇:断路器(Hystrix)

    转:https://blog.csdn.net/forezp/article/details/69934399 最新版本: 史上最简单的SpringCloud教程 | 第四篇:断路器(Hystrix) ...

  7. SpringCloud教程 | 第四篇:断路器(Hystrix)

    SpringCloud教程 | 第四篇:断路器(Hystrix) 在微服务架构中,根据业务来拆分成一个个的服务,服务与服务之间可以相互调用(RPC),在Spring Cloud可以用RestTempl ...

  8. matlab最基础教程(四):常用的系统自带函数,符号变量与字符串篇

    matlab最基础教程(四):常用的系统自带函数,符号变量与字符串篇 前言:matlab字面意思是矩阵实验室,软件重点是数值变量的运算.所以在符号变量和字符串的运算上,功能并不强大,我用的也不是很多, ...

  9. 【C# 教程系列第 4 篇】什么是 c# 中的 ref 参数?

    这是[C# 教程系列第 4 篇],如果觉得有用的话,欢迎关注专栏. 写这篇博客之前,本来想把标题写成 "ref参数与out参数的区别",但想了想还是分开写吧,以免更混淆大家. 首先 ...

最新文章

  1. python画图标题_使用pyplot.matshow()函数添加绘图标题
  2. jenkins+docker部署java项目
  3. IIS6配置Asp.net MVC运行环境
  4. kibana使用_手把手教你使用Nginx实现Kibana的安全认证
  5. Spark Streaming(四)kafka搭建(单节点,单broker)
  6. 在PAT上提交Java代码
  7. 网站搜索功能怎么实现_电商网站上的搜索功能是如何实现的?
  8. MySQL优化调优有没有做过_MySQL 调优/优化的 100 个建议
  9. 【测试方法篇】效率测试
  10. 不会Python爬虫?教你一个通用爬虫思路轻松爬取网页数据,赶紧收藏!!
  11. 2020年Java程序员应该学习的10大技术
  12. 本地调试微信接口方法
  13. netty心跳过程中 发送消息失败_netty心跳机制和断线重连(四)
  14. MySQL check table/optimize table/analyze table/REPAIR TABLE
  15. MyEclipse下连接Mysql
  16. R语言向matlab转化,我有一段MATLAB的程序,现在想转换成R语言代码
  17. 收藏夹吃灰系列(五):解决Win10插入U盘不显示磁盘可用容量且打不开卡死问题 | 超级详细,建议收藏
  18. 网页上的文本不让你复制下载?老司机教你几招,轻松免费复制
  19. DHCP报文及其格式
  20. 电脑版微信,QQ语音通话耳机听不到对方声音

热门文章

  1. Tomcat 的三种(bio,nio.apr) 高级 Connector 运行模式
  2. Android 攻城狮的进击 1 开发环境搭建HelloWorld.apk
  3. 芯片的英文手册需要全部看吗?
  4. 财政部发布美国主要贸易伙伴宏观经济和MogaFX外汇政策报告
  5. IntelliJ IDEA中的disconnect和terminate
  6. 安卓手机文件系统 roots recovery bootimg
  7. 日本计算机博士回国就业情况,海归就业创业调查 海归博士就业真实现状
  8. RK3399 io操作GPIO
  9. Before start of result set报错
  10. PayPal收款流程