前面学习了 MyBatis 的相关知识,今天带大家一起来学习一下关于表现层的另一个框架 - SpringMVC。
Spring web mvc 和 Struts2 都属于表现层的框架, 它是 Spring 框架的一部分, 我们可以从 Spring 的整体结构中看得出来:
1、springmvc 的入口是一个 servlet 即前端控制器,而 struts2 入口是一个 filter 过虑器。
2、springmvc 是基于方法开发 (一个 url 对应一个方法),请求参数传递到方法的形参,可以设计为单例或多例 (建议单例),struts2 是基于类开发,传递参数是通过类的属性,只能设计为多例。
3、Struts 采用值栈存储请求和响应的数据,通过 OGNL 存取数据, springmvc 通过参数解析器是将 request 请求内容解析,并给方法形参赋值,将数据和视图封装成 ModelAndView 对象,最后又将 ModelAndView 中的模型数据通过 reques 域传输到页面。Jsp 视图解析器默认使用 jstl。
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
- <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <
- meta
- http-equiv
- =
- "Content-Type"
- content
- =
- "text/html; charset=UTF-8"
- >
- <title>查询商品列表</title>
- </head>
- <body>
- <
- form
- action
- =
- "${pageContext.request.contextPath }/item/queryitem.action"
- method
- =
- "post"
- >
- 查询条件:
- <
- table
- width
- =
- "100%"
- border
- =
- 1
- >
- <tr>
- <td>
- <
- input
- type
- =
- "submit"
- value
- =
- "查询"
- />
- </td>
- </tr>
- </table>
- 商品列表:
- <
- table
- width
- =
- "100%"
- border
- =
- 1
- >
- <tr>
- <td>商品名称</td>
- <td>商品价格</td>
- <td>生产日期</td>
- <td>商品描述</td>
- <td>操作</td>
- </tr>
- <
- c:forEach
- items
- =
- "${itemList }"
- var
- =
- "item"
- >
- <tr>
- <td>${item.name }</td>
- <td>${item.price }</td>
- <td>
- <
- fmt:formatDate
- value
- =
- "${item.createtime}"
- pattern
- =
- "yyyy-MM-dd HH:mm:ss"
- />
- </td>
- <td>${item.detail }</td>
- <td><a href="${pageContext.request.contextPath }/itemEdit.action?id=${item.id}">修改</a></td>
- </tr>
- </c:forEach>
- </table>
- </form>
- </body>
- </html>
ItemController 是一个普通的 java 类,不需要实现任何接口,只需要在类上添加 @Controller 注解即可。@RequestMapping 注解指定请求的 url,其中 ".action" 可以加也可以不加。在 ModelAndView 对象中,将视图设置为 "/WEB-INF/jsp/itemList.jsp"。
- @Controller publicclass ItemController {
- @RequestMapping("/itemList") public ModelAndView itemList() throws Exception {
- List < Items > itemList = new ArrayList < >();
- //商品列表
- Items items_1 = new Items();
- items_1.setName("联想笔记本_3");
- items_1.setPrice(6000f);
- items_1.setDetail("ThinkPad T430 联想笔记本电脑!");
- Items items_2 = new Items();
- items_2.setName("苹果手机");
- items_2.setPrice(5000f);
- items_2.setDetail("iphone6苹果手机!");
- itemList.add(items_1);
- itemList.add(items_2);
- //创建modelandView对象
- ModelAndView modelAndView = new ModelAndView();
- //添加model
- modelAndView.addObject("itemList", itemList);
- //添加视图
- modelAndView.setViewName("/WEB-INF/jsp/itemList.jsp");
- //modelAndView.setViewName("itemsList");
- return modelAndView;
- }
- }
商品数据使用 Items 类描述,可以使用提供的 pojo 类
- public class Items {
- private Integer id;
- private String name;
- private Float price;
- private String pic;
- private Date createtime;
- private String detail;
- 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 == null ? null: name.trim();
- }
- public Float getPrice() {
- return price;
- }
- public void setPrice(Float price) {
- this.price = price;
- }
- public String getPic() {
- return pic;
- }
- public void setPic(String pic) {
- this.pic = pic == null ? null: pic.trim();
- }
- public Date getCreatetime() {
- return createtime;
- }
- public void setCreatetime(Date createtime) {
- this.createtime = createtime;
- }
- public String getDetail() {
- return detail;
- }
- public void setDetail(String detail) {
- this.detail = detail == null ? null: detail.trim();
- }
- }
- <?xmlversion="1.0"encoding="UTF-8"?>
- <beansxmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"xmlns:mvc="http://www.springframework.org/schema/mvc"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
- http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
- http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
- <context:component-scanbase-package="cn.zy.springmvc.controller"/>
- </beans>
在 web.xml 中添加 DispatcherServlet 的配置。
- <!-- 前端控制器 -->
- <servlet>
- <servlet-name>springmvc</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <init-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:springmvc.xml</param-value>
- </init-param>
- </servlet>
- <servlet-mapping>
- <servlet-name>springmvc</servlet-name>
- <url-pattern>*.action</url-pattern>
- </servlet-mapping>
1、用户发送请求至前端控制器 DispatcherServlet
2、DispatcherServlet 收到请求调用 HandlerMapping 处理器映射器。
3、处理器映射器根据请求 url 找到具体的处理器,生成处理器对象及处理器拦截器 (如果有则生成) 一并返回给 DispatcherServlet。
4、DispatcherServlet 通过 HandlerAdapter 处理器适配器调用处理器
5、执行处理器 (Controller,也叫后端控制器)。
6、Controller 执行完成返回 ModelAndView
7、HandlerAdapter 将 controller 执行结果 ModelAndView 返回给 DispatcherServlet
8、DispatcherServlet 将 ModelAndView 传给 ViewReslover 视图解析器
9、ViewReslover 解析后返回具体 View
10、DispatcherServlet 对 View 进行渲染视图(即将模型数据填充至视图中)。
11、DispatcherServlet 响应用户
以下组件通常使用框架提供实现:
用户请求到达前端控制器,它就相当于 mvc 模式中的 c,dispatcherServlet 是整个流程控制的中心,由它调用其它组件处理用户的请求,dispatcherServlet 的存在降低了组件之间的耦合性。
HandlerMapping 负责根据用户请求找到 Handler 即处理器,springmvc 提供了不同的映射器实现不同的映射方式,例如:配置文件方式,实现接口方式,注解方式等。
Handler 是继 DispatcherServlet 前端控制器的后端控制器,在 DispatcherServlet 的控制下 Handler 对具体的用户请求进行处理。
由于 Handler 涉及到具体的用户业务请求,所以一般情况需要程序员根据业务需求开发 Handler。
通过 HandlerAdapter 对处理器进行执行,这是适配器模式的应用,通过扩展适配器可以对更多类型的处理器进行执行。
View Resolver 负责将处理结果生成 View 视图,View Resolver 首先根据逻辑视图名解析成物理视图名即具体的页面地址,再生成 View 视图对象,最后对 View 进行渲染将处理结果通过页面展示给用户。
springmvc 框架提供了很多的 View 视图类型的支持,包括:jstlView、freemarkerView、pdfView 等。我们最常用的视图就是 jsp。
一般情况下需要通过页面标签或页面模版技术将模型数据通过页面展示给用户,需要由程序员根据业务需求开发具体的页面。
说明:在 springmvc 的各个组件中,处理器映射器、处理器适配器、视图解析器称为 springmvc 的三大组件。
需要用户开放的组件有 handler、view
使用组件扫描器省去在 spring 容器配置每个 controller 类的繁琐。使用
自动扫描标记 @controller 的控制器类,配置如下:
- <context:component-scan>
- <!-- 扫描controller注解,多个包中间使用半角逗号分隔 -->
- <context:component-scanbase-package="cn.zy.springmvc.controller.first"/>
注解式处理器映射器,对类中标记 @ResquestMapping 的方法进行映射,根据 ResquestMapping 定义的 url 匹配 ResquestMapping 标记的方法,匹配成功返回 HandlerMethod 对象给前端控制器,HandlerMethod 对象中封装 url 对应的方法 Method。
从 spring3.1 版本开始,废除了 DefaultAnnotationHandlerMapping 的使用,推荐使用 RequestMappingHandlerMapping 完成注解式处理器映射。
配置如下:
- <!--注解映射器 -->
- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
注解描述:
@RequestMapping:定义请求 url 到处理器功能方法的映射
注解式处理器适配器,对标记 @ResquestMapping 的方法进行适配。
从 spring3.1 版本开始,废除了 AnnotationMethodHandlerAdapter 的使用,推荐使用 RequestMappingHandlerAdapter 完成注解式处理器适配。
配置如下:
- <!--注解适配器 -->
- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
- <mvc:annotation-driven>
springmvc 使用自动加载 RequestMappingHandlerMapping 和 RequestMappingHandlerAdapter,可用在 springmvc.xml 配置文件中使用
替代注解处理器和适配器的配置。
- <mvc:annotation-driven>
在 springmvc.xml 文件配置如下:
- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <propertyname="viewClass" value="org.springframework.web.servlet.view.JstlView"
- />
- <propertyname="prefix" value="/WEB-INF/jsp/" />
- <propertyname="suffix" value=".jsp" />
- </bean>
InternalResourceViewResolver:支持 JSP 视图解析
viewClass:JstlView 表示 JSP 模板页面需要使用 JSTL 标签库,所以 classpath 中必须包含 jstl 的相关 jar 包。此属性可以不设置,默认为 JstlView。
prefix 和 suffix:查找视图页面的前缀和后缀,最终视图的址为:
前缀 + 逻辑视图名 + 后缀,逻辑视图名需要在 controller 中返回 ModelAndView 指定,比如逻辑视图名为 hello,则最终返回的 jsp 视图地址 "WEB-INF/jsp/hello.jsp"
为了更好的学习 springmvc 和 mybatis 整合开发的方法,需要将 springmvc 和 mybatis 进行整合。
整合目标:控制层采用 springmvc、持久层使用 mybatis 实现。
Dao 层:
1、SqlMapConfig.xml,空文件即可。需要文件头。
2、applicationContext-dao.xml。
a) 数据库连接池
b)SqlSessionFactory 对象,需要 spring 和 mybatis 整合包下的。
c) 配置 mapper 文件扫描器。
Service 层:
1、applicationContext-service.xml 包扫描器,扫描 @service 注解的类。
2、applicationContext-trans.xml 配置事务。
表现层:
Springmvc.xml
1、包扫描器,扫描 @Controller 注解的类。
2、配置注解驱动。
3、视图解析器
Web.xml
配置前端控制器。
在 classpath 下创建 mybatis/sqlMapConfig.xml
- <?xmlversion="1.0"encoding="UTF-8"?>
- <!DOCTYPEconfiguration
- PUBLIC"-//mybatis.org//DTD Config 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-config.dtd">
- <configuration>
- </configuration>
配置数据源、配置 SqlSessionFactory、mapper 扫描器。
- <?xmlversion="1.0"encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:context="http://www.springframework.org/schema/context"xmlns:p="http://www.springframework.org/schema/p"
- xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
- http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
- <!-- 加载配置文件 -->
- <context:property-placeholderlocation="classpath:db.properties"/>
- <!-- 数据库连接池 -->
- <bean id="dataSource"class="org.apache.commons.dbcp.BasicDataSource"
- destroy-method="close">
- <propertyname="driverClassName"value="${jdbc.driver}"/>
- <propertyname="url"value="${jdbc.url}"/>
- <propertyname="username"value="${jdbc.username}"/>
- <propertyname="password"value="${jdbc.password}"/>
- <propertyname="maxActive"value="10"/>
- <propertyname="maxIdle"value="5"/>
- </bean>
- <!-- mapper配置 -->
- <!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
- <
- bean
- id
- =
- "sqlSessionFactory"
- class
- =
- "org.mybatis.spring.SqlSessionFactoryBean"
- >
- <!-- 数据库连接池 -->
- <propertyname="dataSource"ref="dataSource"/>
- <!-- 加载mybatis的全局配置文件 -->
- <propertyname="configLocation" value="classpath:mybatis/SqlMapConfig.xml"/>
- </bean>
- <!-- 配置Mapper扫描器 -->
- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
- <propertyname="basePackage"value="cn.zy.springmvc.mapper"/>
- </bean>
- </beans>
Db.properties
- jdbc.driver=com.mysql.jdbc.Driver
- jdbc.url=jdbc:mysql://localhost:3306/springmvc?characterEncoding=utf-8
- jdbc.username=root
- jdbc.password=root
- <?xmlversion="1.0"encoding="UTF-8"?>
- <beansxmlns="http://www.springframework.org/schema/beans"
- xmlns:context="http://www.springframework.org/schema/context"xmlns:p="http://www.springframework.org/schema/p"
- xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
- http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
- <context:component-scanbase-package="cn.zy.springmvc.service"/>
- </beans>
- <?xmlversion="1.0"encoding="UTF-8"?>
- <beansxmlns="http://www.springframework.org/schema/beans"
- xmlns:context="http://www.springframework.org/schema/context"xmlns:p="http://www.springframework.org/schema/p"
- xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
- http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
- <!-- 事务管理器 -->
- <beanid="transactionManager"
- class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
- <!-- 数据源 -->
- <propertyname="dataSource"ref="dataSource"/>
- </bean>
- <!-- 通知 -->
- <tx:adviceid="txAdvice"transaction-manager="transactionManager">
- <tx:attributes>
- <!-- 传播行为 -->
- <tx:methodname="save*"propagation="REQUIRED"/>
- <tx:methodname="insert*" propagation="REQUIRED"/>
- <tx:methodname="delete*" propagation="REQUIRED"/>
- <tx:methodname="update*" propagation="REQUIRED"/>
- <
- tx:methodname="find*"
- propagation
- =
- "SUPPORTS"
- read-only="true"
- />
- <
- tx:methodname="get*"
- propagation
- =
- "SUPPORTS"
- read-only="true"
- />
- </tx:attributes>
- </tx:advice>
- <!-- 切面 -->
- <aop:config>
- <aop:advisoradvice-ref="txAdvice"
- pointcut="execution(* cn.zy.springmvc.service.*.*(..))"/>
- </aop:config>
- </beans>
- <?xmlversion="1.0" encoding="UTF-8" ?>
- <beansxmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
- xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:mvc="http://www.springframework.org/schema/mvc"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
- http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
- http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
- <!-- 扫描带Controller注解的类 -->
- <context:component-scanbase-package="cn.zy.springmvc.controller" />
- <!-- 加载注解驱动 -->
- <mvc:annotation-driven/>
- <!-- 视图解析器 -->
- <beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <propertyname="viewClass" value="org.springframework.web.servlet.view.JstlView"
- />
- <!-- jsp前缀 -->
- <propertyname="prefix" value="/WEB-INF/jsp/" />
- <!-- jsp后缀 -->
- <propertyname="suffix" value=".jsp" />
- </bean>
- </beans>
- <?xmlversion="1.0"encoding="UTF-8"?>
- <web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
- id="WebApp_ID"version="2.5">
- <display-name>springmvc-web</display-name>
- <welcome-file-list>
- <welcome-file>index.html</welcome-file>
- <welcome-file>index.htm</welcome-file>
- <welcome-file>index.jsp</welcome-file>
- <welcome-file>default.html</welcome-file>
- <welcome-file>default.htm</welcome-file>
- <welcome-file>default.jsp</welcome-file>
- </welcome-file-list>
- <!-- 加载spring容器 -->
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:spring/applicationContext-*.xml</param-value>
- </context-param>
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- <servlet>
- <servlet-name>springmvc</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <init-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:spring/springmvc.xml</param-value>
- </init-param>
- </servlet>
- <servlet-mapping>
- <servlet-name>springmvc</servlet-name>
- <url-pattern>*.action</url-pattern>
- </servlet-mapping>
- </web-app>
1、Service 由 spring 管理
2、spring 对 Service 进行事务控制。
- publicinterface ItemService {
- List < Items > getItemsList();
- }
- @Service
- publicclass ItemServiceImpl implements ItemService {
- @Autowired
- private ItemMapper itemMapper;
- @Override
- public List<Items> getItemsList() {
- List<Items>itemList = itemMapper.getItemList();
- returnitemList;
- }
- }
- @Controller
- publicclass ItemController {
- @Autowired
- private ItemService itemService;
- @RequestMapping("/itemList")
- public ModelAndView getItemList() {
- List<Items>list = itemService.getItemsList();
- ModelAndView modelAndView = new ModelAndView();
- modelAndView.addObject("itemList", list);
- modelAndView.setViewName("itemList");
- returnmodelAndView;
- }
- }
到这里我们呢可以将项目部署到 tomcat 服务器上,打开浏览器进行访问,例如
- 访问:http://localhost:8080/springmvc-web/itemList.action
- @Override
- public Items getItemById(intid) {
- Items items = itemMapper.getItemById(id);
- return items;
- }
要根据 id 查询商品数据,需要从请求的参数中把请求的 id 取出来。Id 应该包含在 Request 对象中。可以从 Request 对象中取 id。
- @RequestMapping("/itemEdit") public ModelAndView itemEdit(HttpServletRequest request) {
- //从Request中取id
- String strId = request.getParameter("id");
- Integer id = null;
- //如果id有值则转换成int类型
- if (strId != null && !"".equals(strId)) {
- id = newInteger(strId);
- } else {
- //出错
- returnnull;
- }
- Items items = itemService.getItemById(id);
- //创建ModelAndView
- ModelAndView modelAndView = new ModelAndView();
- //向jsp传递数据
- modelAndView.addObject("item", items);
- //设置跳转的jsp页面
- modelAndView.setViewName("editItem");
- return modelAndView;
- }
如果想获得 Request 对象只需要在 Controller 方法的形参中添加一个参数即可。Springmvc 框架会自动把 Request 对象传递给方法。
处理器形参中添加如下类型的参数处理适配器会默认识别并进行赋值。
HttpServletRequest
通过 request 对象获取请求信息
HttpServletResponse
通过 response 处理响应信息
HttpSession
通过 session 对象得到 session 中存放的对象
Model/ModelMap
ModelMap 是 Model 接口的实现类,通过 Model 或 ModelMap 向页面传递数据,如下:
- //调用service查询商品信息
- Items item = itemService.findItemById(id);
- model.addAttribute("item", item);
页面通过 ${item.XXXX} 获取 item 对象的属性值。
使用 Model 和 ModelMap 的效果一样,如果直接使用 Model,springmvc 会实例化 ModelMap。
如果使用 Model 则可以不使用 ModelAndView 对象,Model 对象可以向页面传递数据,View 对象则可以使用 String 返回值替代。不管是 Model 还是 ModelAndView,其本质都是使用 Request 对象向 jsp 传递数据。
如果使用 Model 则方法可以改造成:
- @RequestMapping("/itemEdit") public String itemEdit(HttpServletRequest request, Model model) {
- //从Request中取id
- String strId = request.getParameter("id");
- Integer id = null;
- //如果id有值则转换成int类型
- if (strId != null && !"".equals(strId)) {
- id = newInteger(strId);
- } else {
- //出错
- returnnull;
- }
- Items items = itemService.getItemById(id);
- //创建ModelAndView
- //ModelAndView modelAndView = new ModelAndView();
- //向jsp传递数据
- //modelAndView.addObject("item", items);
- model.addAttribute("item", items);
- //设置跳转的jsp页面
- //modelAndView.setViewName("editItem");
- //return modelAndView;
- return "editItem";
- }
当请求的参数名称和处理器形参名称一致时会将请求参数与形参进行绑定。从 Request 取参数的方法可以进一步简化。
- @RequestMapping("/itemEdit")
- public String itemEdit(Integer id, Model model) {
- Items items = itemService.getItemById(id);
- //向jsp传递数据
- model.addAttribute("item", items);
- //设置跳转的jsp页面
- return "editItem";
- }
参数类型推荐使用包装数据类型,因为基础数据类型不可以为 null
整形:Integer、int
字符串:String
单精度:Float、float
双精度:Double、double
布尔型:Boolean、boolean
说明:对于布尔类型的参数,请求的参数值为 true 或 false。 处理器方法: public String editItem(Model
model,Integer id,Boolean status) throws Exception 请求 url:
http://localhost:8080/xxx.action?id=2&status=false
如果提交的参数很多,或者提交的表单中的内容很多的时候可以使用 pojo 接收数据。要求 pojo 对象中的属性名和表单中 input 的 name 属性一致。
页面定义如下;
- <input type="text" name="name" />
- <input type="text" name="price" />
Pojo 定义:
- public class Items{
- private Integer id;
- private String name;
- private Float price;
- private String pic;
- private Date createtime;
- ……
- }
请求的参数名称和 pojo 的属性名称一致,会自动将请求参数赋值给 pojo 的属性。
- @RequestMapping("/updateitem")
- public String updateItem(Items items) {
- itemService.updateItem(items);
- return"success";
- }
注意:提交的表单中不要有日期类型的数据,否则会报 400 错误。如果想提交日期类型的数据需要用到后面的自定义参数绑定的内容。
在 web.xml 中加入:
- <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>
- </filter>
- <filter-mapping>
- <filter-name>CharacterEncodingFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
以上可以解决 post 请求乱码问题。
对于 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 编码
包装对象定义如下:
- Public class QueryVo {
- private Items items;
- ......
- }
页面定义:
- <input type="text" name="items.name" />
- <input type="text" name="items.price" />
Controller 方法定义如下:
- public String useraddsubmit(Model model, QueryVoqueryVo) throws Exception {
- System.out.println(queryVo.getItems());
- }
- @RequestMapping("/queryitem")
- public String queryItem(QueryVo queryVo) {
- System.out.println(queryVo.getItems().getName());
- System.out.println(queryVo.getItems().getPrice());
- return null;
- }
由于日期数据有很多种格式,所以 springmvc 没办法把字符串转换成日期类型。所以需要自定义参数绑定。前端控制器接收到请求后,找到注解形式的处理器适配器,对 RequestMapping 标记的方法进行适配,并对方法中的形参进行参数绑定。在 springmvc 这可以在处理器适配器上自定义 Converter 进行参数绑定。如果使用
可以在此标签上进行扩展。
- <mvc:annotation-driven/>
- public
- class
- DateConverter
- implements
- Converter
- <
- String
- ,
- Date
- > {
- @Override
- public Date convert(String source) {
- SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- try {
- return simpleDateFormat.parse(source);
- } catch (ParseException e) {
- e.printStackTrace();
- }
- return null;
- }
- }
- <!-- 加载注解驱动 -->
- <mvc:annotation-drivenconversion-service="conversionService"/>
- <!-- 转换器配置 -->
- <beanid="conversionService"
- class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
- <propertyname="converters">
- <set>
- <beanclass="cn.zy.springmvc.convert.DateConverter"/>
- </set>
- </property>
- </bean>
好了,今天的关于 SpringMVC 框架的第一章的内容就写到这儿,欢迎大家有问题留言,如果有错误的地方能够指出改正,一起进步,么么哒~
来源: http://blog.csdn.net/woshizisezise/article/details/78822109