springmvc-day01
springmvc的基础知识 1.springmvc框架
1.1什么是springmvc
springmvc是spring框架的一个模块,springmvc和spring无需通过中间整合层进行整合。
springmvc是一个基于mvc的web框架。 1.2mvc在B/S系统下的应用
mvc是一个设计模式,mvc在B/S系统下的应用: 1.3springmvc框架
第一步:发起请求到前端控制器(DispatcherServlet)
第二步:前端控制器请求HandlerMapping查找Handler
可以根据xml配置、注解进行查找
第三步:处理器映射器HandlerMapping向前端控制器返回Handler 第四步:前端控制器调用处理器适配器去执行Handler
第五步:处理器适配器去执行Handler
第六步:Handler执行完成给适配器返回ModelAndView
第七步:处理器适配器向前端控制器返回ModelAndView
ModelAndView是springmvc框架的一个底层对象,包括Model和view 第八步:前端控制器请求视图解析器去进行视图解析
根据逻辑视图名解析成真正的视图(jsp) 第九步:视图解析器向前端控制器返回view
第十步:前端控制器进行视图渲染
视图渲染将模型数据(在ModelAndView对象中)填充到request域。 第十一步:前端控制器向用户响应结果。
组件:
1.前端控制器DispatcherServlet(不需要程序员开发)
作用接收请求,响应结果,相当于转发器,中央处理器。
有了DispatcherServlet减少了其他组件之间的耦合度。 2.处理器映射器HandlerMapping(不需要程序员开发)
作用:根据请求的url查找Handler 3.处理器适配器HandlerAdapter
作用:按照特定规则(HandlerAdapter要求的规则)去执行Handler 4.处理器Handler(需要程序员开发)
注意:编写Handler时按照HandlerAdapter的要求去做,这样适配器才可以去正确执行Handler 5.视图解析器View resolver(不需要程序员开发)
作用:进行视图解析,根据逻辑视图名解析成真正的视图(view) 6.视图View(需要程序员开发jsp)
View是一个接口,实现类支持不同的View类型(jsp、freemarker、pdf...) 2.入门程序
2.1需求
以案例作为驱动
springmvc和mybatis使用一个案例(商品订单管理)。
功能需求:商品列表查询 2.2环境准备
数据库环境:mysql
java环境:
jdk
eclipse indigo springmvc版本:spring3.2
需要spring3.2所有jar(一定要包括spring-webmvc-x.x.x.RELEASE.jar)
2.3配置前端控制器
在web.xml中配置前端控制器。
<!-- springmvc前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- contextConfigLocation配置springmvc加载的配置文件(配置处理器、映射器、适配器等等)
如果不配置contextConfigLocation,默认加载的是/WEB-INF/servlet名称-servlet.xml(springmvc-servlet.xml)
-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!--
第一种:*.action,访问以.action结尾由DispatcherServlet进行解析
第二种:/,所有访问的地址都由DispatcherServlet进行解析,对于静态文件的解析需要配置不让DispatcherServlet解析
使用此种方法可以实现RESTful风格的url
第三种:/*,这样配置不对,使用这种配置,最终需要发到一个jsp页面时,
仍然会有DispatcherServlet解析jsp地址值,不能提供jsp页面找到handler,会报错
-->
<url-pattern>*.action</url-pattern>
</servlet-mapping> 2.4配置处理器适配器
在classpath下的springmvc.xml中配置处理器适配器
<!-- 处理器适配器 -->
<!-- 所有处理器适配器都实现HandlerAdapter接口 -->
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean> 通过查看源代码:
public class SimpleControllerHandlerAdapter implements HandlerAdapter { @Override
public boolean supports(Object handler) {
return (handler instanceof Controller);
} @Override
public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception { return ((Controller) handler).handleRequest(request, response);
} @Override
public long getLastModified(HttpServletRequest request, Object handler) {
if (handler instanceof LastModified) {
return ((LastModified) handler).getLastModified(request);
}
return -1L;
} }
此适配器能执行实现Controller接口的Handler
public interface Controller { /**
* Process the request and return a ModelAndView object which the DispatcherServlet
* will render. A {@code null} return value is not an error: it indicates that
* this object completed request processing itself and that there is therefore no
* ModelAndView to render.
* @param request current HTTP request
* @param response current HTTP response
* @return a ModelAndView to render, or {@code null} if handled directly
* @throws Exception in case of errors
*/
ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception; }
2.5开发Handler
需要实现controller接口,才能由org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter适配器执行。
public class ItemsController1 implements Controller { @Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 调用service查找数据库,查询商品列表,这里使用静态数据模拟
List<Items> itemsList = new ArrayList<Items>(); // 向list中填充静态数据
Items items_1 = new Items();
items_1.setName("联想笔记本");
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苹果手机!"); itemsList.add(items_1);
itemsList.add(items_2); // 返回ModelAndView
ModelAndView modelAndView = new ModelAndView();
// 相当于resquest的setAttribute,在jsp页面中通过itemsList取数据
modelAndView.addObject("itemsList", itemsList);
//指定视图
modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp");
return modelAndView;
} }
2.6视图编写
2.7配置Handler
将编写Handler在spring容器中加载。
<!-- 配置Handler -->
<bean id="itemsController1" name="/queryItems.action" class="com.changemax.ssm.controller.ItemsController1"></bean> 2.8配置处理器映射器
在classpath下的springmvc.xml中配置处理器映射器 <!-- 处理器映射器 -->
<!-- 将bean的name作为url进行查找,需要在配置Handler时指定beanname(就是url) beanname的所有映射器都实现了HTTPResultHandler -->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" /> 2.9配置视图解析器
需要配置解析器jsp的视图解析器
<!-- 视图解析器 -->
<!-- 解析jsp视图,默认使用jstl标签,classpath下得有jstl的jar包 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置jsp路径的前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 配置jsp路径的后缀 -->
<property name="suffix" value=".jsp" />
</bean> 2.10部署调试
访问地址:http://localhost:8080/springmvc-day01/queryItems.action 3.非注解的处理器映射器的适配器
3.1非注解的处理器映射器
处理器映射器:
org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping 另一个映射器:
org.springframework.web.servlet.handler.SimpleUrlHandlerMapping <!-- 处理器映射器 -->
<!-- 将bean的name作为url进行查找,需要在配置Handler时指定beanname(就是url) beanname的所有映射器都实现了HTTPResultHandler -->
<bean
class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" /> <!-- 简单url映射 -->
<bean
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
对Itesmcontroller进行url地址映射,url就是queryItems.action
<prop key="/queryItems1.action">itemsController1</prop>
<prop key="/queryItems2.action">itemsController1</prop>
<prop key="/queryItems3.action">itemsController2</prop>
</props>
</property>
</bean> 多个映射器可以并存,前端控制器判断url能让哪些映射器映射,就让正确的映射器处理。
3.2非注解的处理器适配器
org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter
要求编写的Handler实现Controller接口。
public class ItemsController1 implements Controller { @Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 调用service查找数据库,查询商品列表,这里使用静态数据模拟
List<Items> itemsList = new ArrayList<Items>(); org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter
要求编写的Handler实现HttpRequestHandler接口
public class ItemsController2 implements HttpRequestHandler { @Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 调用service查找数据库,查询商品列表,这里使用静态数据模拟
List<Items> itemsList = new ArrayList<Items>();
<!-- 处理器适配器 -->
<!-- 所有处理器适配器都实现HandlerAdapter接口 -->
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean> <!-- 另一个非注解的适配器 -->
<bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter" /> 4.DispatcherServlet.properties
前端控制器从上边的文件中加载处理器映射器、适配器、视图解析器等组件,如果不在springmvc.xml中配置,使用默认加载的配置。 5.注解的处理器映射器和适配器
映射器:
在spring3.1之前使用org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping(过时)
在spring3.1之后使用org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping 适配器:
在spring3.1之前使用org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter(过时)
在spring3.1之后使用org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter 5.1配置注解映射器和适配器
<!-- 注解的映射器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> <!-- 注解的适配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
<!-- mvc:annotation-driven代替上边注解映射器和注解适配器的配置
mvc:annotation-driven默认加载很多的参数绑定方法,比如json转换解析器就默认加载了,
如果使用mvc:annotation-driven不用配置上边的RequestMappingHandlerMapping和RequsetMappingHandleAdaper
实际开发中使用:mvc:annotation-driven
--> 5.2开发注解Handler
使用注解的映射器和注解的适配器。(注解的映射器和注解的适配器必须配对使用)
//使用@Controller注解标识这个是个控制器
@Controller
public class ItemsController3 {
// 商品查询列表
//@RequestMapping实现了对方法和url进行映射,一个方法对应一个url
//一般建议url和方法名一样,便于维护
@RequestMapping("/queryItems")
public ModelAndView queryItems() throws Exception {
// 调用service查找数据库,查询商品列表,这里使用静态数据模拟
List<Items> itemsList = new ArrayList<Items>(); // 向list中填充静态数据
Items items_1 = new Items();
items_1.setName("联想笔记本");
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苹果手机!"); itemsList.add(items_1);
itemsList.add(items_2); ModelAndView modelAndView = new ModelAndView();
// 相当于resquest的setAttribute,在jsp页面中通过itemsList取数据
modelAndView.addObject("itemsList", itemsList); // 指定视图
//通过springmvc配置文件,可以省掉jsp路径的前缀和后缀
modelAndView.setViewName("items/itemsList");
return modelAndView;
}
} 5.3在spring容器中加载Handler
<!-- 对于注解的handler配置可以单个配置
在实际开发中,建议使用组件扫描
-->
<bean id="itemsController3"
class="com.changemax.ssm.controller.ItemsController3"></bean>
<!-- 可以使用扫描controller、service、...
这里让扫描controller,指定controller的包路径
-->
<context:component-scan base-package="com.changemax.ssm.controller"></context:component-scan> 5.4部署调试
访问:http://localhost:8080/springmvc-day01/queryItems.action 6源码分析(了解)
通过前端控制器源码分析springmvc的执行过程。
第一步:前端控制器接收请求
调用doDiapatch 第二步:前端控制器调用处理器映射器查找Handler
第三步:调用处理器适配器执行Handler,得到执行结果ModelAndView
第四步:视图渲染,将model数据填充到request域。
视图解析,得到view。
调用view的渲染方法,将model数据填充到request域 7.入门程序小结
通过入门程序理解springmvc前端控制器、处理器映射器、处理器适配器、视图解析器用法。
前端控制器配置:
第一种:*.action,访问以.action结尾 由DispatcherServlet进行解析 第二种:/,所以访问的地址都由DispatcherServlet进行解析,对于静态文件的解析需要配置不让DispatcherServlet进行解析
使用此种方式可以实现RESTful风格的url 处理器映射器:
非注解处理器映射器(了解)
注解的处理器映射器(掌握)
对标记@Controller类中标识有@RequestMapping的方法进行映射。在@RequestMapping里边定义映射的url。
使用注解的映射器不用再xml中配置url和Handler的映射关系。 处理器适配器:
非注解的处理器适配器(了解)
注解的处理器适配器(掌握)
注解处理器适配器的注解的处理器映射器是配对使用。理解为不能使用非注解映射器进行映射。 <mvc:annotation-driven></mvc:annotation-driven>可以替代下边的配置:
<!--注解映射器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
<!--注解适配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> 实际开发使用:mvc:annotation-driven
视图解析器配置前缀和后缀:
<!-- 视图解析器 -->
<!-- 解析jsp视图,默认使用jstl标签,classpath下得有jstl的jar包 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置jsp路径的前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 配置jsp路径的后缀 -->
<property name="suffix" value=".jsp" />
</bean> 如此配置之后,就可以在程序中不用指定前缀和后缀
8.springmvc和mybatis整合
8.1需求
使用springmvc和mybatis完成商品列表查询。 8.2整合思路
spring将各层进行整合
通过spring管理持久层的mapper(相当于dao接口)
通过spring管理业务层service,service中可以调用mapper接口。
spring进行事物控制。 通过spirng管理表现层Handler,Handler中可以调用service接口。
mapper、service、Handler都是javabean。
第一步:整合dao层:
mybatis和spring整合,通过spring管理mapper接口。
使用mapper的扫描器自动扫描mapper接口在spring中进行注册。 第二步:整合service层
通过spring管理service接口。
使用配置方式将service接口配置在spring配置文件中。
实现事务控制。 第三步:整合springmvc
由于springmvc是spring的模块,不需要整合。 8.3准备环境
数据库环境:mysql
Java环境:
jdk1.8
eclipse indigo
springmvc4.3 所需要jar包;
数据库驱动包:mysql
mybatis的jar包
mybatis和spring的整合包
log4j包
dbcp数据库连接池包
spring3.2所有jar包
jstl包 8.4整合dao
mybatis和spring进行整合 8.4.1sqlMapConfig.xml
mybatis自己的配置文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 全局的setting配置,根据需要添加 --> <!-- 别名定义 -->
<typeAliases>
<package name="com.changemax.ssm.po" />
</typeAliases> <!-- 加载 映射文件 由于使用spring和mybatis的整合包进行mapper扫描,这里不需要配置了 -->
<mappers>
<!-- <mapper resource="sqlmap/User.xml" /> -->
<!-- 批量加载mapper 指定mapper接口的包名,mybatis自动扫描包下边所有mapper接口进行加载 遵循一些规范: 需要将mapper接口类名和mapper.xml映射文件名称保持一致,且在一个目录
中 上边规范的前提是:使用的是mapper代理方法 和spring整合后,使用mapper扫描器,这里不需要配置了 -->
<!-- <package name="com.changemax.ssm.mapper" /> -->
</mappers>
</configuration> 8.4.2applicationContext-jdbc.xml
配置:
数据源
SqlSessionFactory
mapper扫描器 <?xml version="1.0" encoding="UTF-8"?>
<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/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <!-- 和jdbc配置相关的 -->
<!-- 加载db.properties文件中的内容,db.properties文件中的key命名要具有一定的特殊规则 -->
<context:property-placeholder
location="classpath:db.properties" /> <!-- 配置数据源,c3p0连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maxActive" value="30" />
<property name="maxIdle" value="5" />
</bean> <!-- 配置sqlSessionFactory -->
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据库连接池 -->
<property name="dataSource" ref="dataSource" />
<!-- 加载mybatis的全局配置文件 -->
<property name="configLocation"
value="classpath:mybatis/sqlMapConfig.xml" />
</bean> <!-- mapper扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 扫描包路径,如果需要扫描多个包,中间使用半角逗号隔开 -->
<property name="basePackage" value="com.changemax.ssm.mapper"></property>
<property name="sqlSessionFactoryBeanName"
value="sqlSessionFactory" />
</bean> </beans>
8.4.3applicationContext-transaction.xml
8.4.4逆向工程生成po类及mapper(单表增删改查)
将生成的文件拷贝至工程中。 8.4.5手动定义商品查询mapper
针对综合查询mapper,一般情况会有关联查询,建议自定义mapper 8.4.5.1ItemsMapperCustom.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.changemax.ssm.mapper.ItemsMapperCustom" > <!-- 定义商品查询的sql片段,就是商品查询条件 -->
<sql id="query_items_where">
<!-- 使用动态sql,通过if判断,满足条件进行sql拼接 -->
<!-- 商品查询条件通过ItemsQueryVo包装对象 中itemsCustom属性传递 -->
<if test="itemsCustom!=null">
<if test="itemsCustom.name!=null and itemsCustom.name!=''">
items.name LIKE '%${itemsCustom.name}%'
</if>
</if>
</sql>
<!-- 商品列表查询 -->
<!-- parameterType传入包装对象(包装了查询条件)
resultType建议使用扩展对象
-->
<select id="findItemsList" parameterType="com.changemax.ssm.po.ItemsQueryVo"
resultType="com.changemax.ssm.po.ItemsCustom">
SELECT items.* FROM items
<where>
<include refid="query_items_where"></include>
</where>
</select>
</mapper> 8.4.5.2ItemsMapperCustom.java
package com.changemax.ssm.mapper; import java.util.List;
import com.changemax.ssm.po.ItemsCustom;
import com.changemax.ssm.po.ItemsQueryVo; public interface ItemsMapperCustom {
//商品查询列表
public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo)throws Exception;
} 8.5整合service
让spring关联service接口。 8.5.1定义service接口
public interface ItemsService {
/**
* 商品查询列表
* <p>
* Title: findItemsList
* </p>
* <p>
* Description:
* </p>
*
* @param itemsQueryVo
* @return
* @throws Exception
*/
public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception; /**
* 根据id查询商品信息
* <p>
* Title: selectItemById
* </p>
* <p>
* Description:
* </p>
*
* @param id
* @return
* @throws Exception
*/
public ItemsCustom selectItemById(Integer id) throws Exception; /**
* 根据id更新商品信息s
* <p>
* Title: updateItemsById
* </p>
* <p>
* Description:
* </p>
*
* @param id
* @param itemsCustom
* @return
* @throws Exception
*/
public Integer updateItemsById(Integer id, ItemsCustom itemsCustom) throws Exception;
} @Service("itemsService")
public class ItemsServiceImpl implements ItemsService { @Autowired
private ItemsMapperCustom itemsMapperCustom; @Autowired
ItemsMapper itemsMapper; @Override
public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception {
// 通过ItemsMappCustom查询
return itemsMapperCustom.findItemsList(itemsQueryVo);
} @Override
public ItemsCustom selectItemById(Integer id) throws Exception {
Items items = itemsMapper.selectByPrimaryKey(id);
// 通过ItemsMappCustom查询
ItemsCustom itemsCustom = new ItemsCustom();
BeanUtils.copyProperties(items, itemsCustom);
return itemsCustom; }
@Override
public Integer updateItemsById(Integer id, ItemsCustom itemsCustom) throws Exception { // 添加业务检验,通常在service接口对关键参数进行校验
// 校验id是否为空,如果为空则抛出异常 // 更新商品信息使用updateByParimaryKeyWithBLOBs根据id更新items表中的所有字段,包括大文本类型字段
// updateByPrimaryKeyWithBLOBs要求必须转入id
itemsCustom.setId(id);
Integer i = itemsMapper.updateByPrimaryKeyWithBLOBs(itemsCustom);
return i;
} }
8.5.2在spring容器配置service(applictionContext-service.xml)
略,通过注解配置 8.5.3事务控制(applicationContext-transaction.xml)
<?xml version="1.0" encoding="UTF-8"?>
<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/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<!-- 和事务相关的配置 -->
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean> <!-- 配置事务的通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED" read-only="false" />
<tx:method name="update*" propagation="REQUIRED" read-only="false" />
<tx:method name="delete*" propagation="REQUIRED" read-only="false" />
<tx:method name="insert*" propagation="REQUIRED" read-only="false" />
<tx:method name="find*" propagation="SUPPORTS" read-only="true" />
<tx:method name="get*" propagation="SUPPORTS" read-only="true" />
<tx:method name="select*" propagation="SUPPORTS" read-only="true" />
</tx:attributes>
</tx:advice>
<!-- 配置aop -->
<aop:config>
<!-- 配置切入点表达式 -->
<aop:pointcut
expression="execution(* com.changemax.ssm.service.impl.*.*(..))" id="pt1" />
<!-- 建立切入点表达式和事务通知的关联 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1" />
</aop:config>
</beans> 8.6整合springmvc
8.6.1springmvc.xml
创建springmvc.xml文件,配置处理器映射器、适配器、视图解析器。
<?xml version="1.0" encoding="UTF-8"?>
<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/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <!-- 对于注解的handler配置可以单个配置 在实际开发中,建议使用组件扫描 -->
<!-- <bean id="itemsController3" class="com.changemax.ssm.controller.ItemsController3"></bean> -->
<!-- 可以使用扫描controller、service、... 这里让扫描controller,指定controller的包路径 -->
<context:component-scan
base-package="com.changemax.ssm.controller"></context:component-scan> <!-- 注解的映射器 -->
<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> --> <!-- 注解的适配器 -->
<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> --> <!-- mvc:annotation-driven代替上边注解映射器和注解适配器的配置 mvc:annotation-driven默认加载很多的参数绑定方法,比如json转换解析器就默认加载了,
如果使用mvc:annotation-driven不用配置上边的RequestMappingHandlerMapping和RequsetMappingHandleAdaper
实际开发中使用:mvc:annotation-driven -->
<mvc:annotation-driven
conversion-service="conversionService">
</mvc:annotation-driven> <!-- 视图解析器 -->
<!-- 解析jsp视图,默认使用jstl标签,classpath下得有jstl的jar包 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置jsp路径的前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 配置jsp路径的后缀 -->
<property name="suffix" value=".jsp" />
</bean> <!-- 自定义参数绑定 -->
<bean id="conversionService" class="">
<!-- 转换器 -->
<property name="converters">
<list>
<!-- 日期类型转换 -->
<bean class="com.changemax.ssm.controller.CustomDateConverter" />
</list>
</property>
</bean>
</beans> 8.6.2配置前端控制器
参考以上 8.6.3编写Controller(就是Handler)
package com.changemax.ssm.controller; import java.util.List;
import javax.servlet.http.HttpServletRequest;
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.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView; import com.changemax.ssm.po.ItemsCustom;
import com.changemax.ssm.service.ItemsService; /**
* <p>
* Title: ItemsController.java
* </p>
* <p>
* Description:
* </p>
* <p>
* Company: www.changemax.com
* </p>
*
* @author WangJi
* @date 2018年11月22日
* @version 1.0
*/
@Controller
//为了对url进行分类管理,可以在这里定义根路径,最终访问url是根路径+子路径
@RequestMapping("/items")
public class ItemsController { @Autowired
private ItemsService itemsService; // 商品查询
@RequestMapping("/queryItems")
public ModelAndView queryItems(HttpServletRequest request) throws Exception {
// 调用service查找数据库,查询商品列表
List<ItemsCustom> itemsList = itemsService.findItemsList(null); ModelAndView modelAndView = new ModelAndView();
// 相当于resquest的setAttribute,在jsp页面中通过itemsList取数据
modelAndView.addObject("itemsList", itemsList); // 指定视图
// 通过springmvc配置文件,可以省掉jsp路径的前缀和后缀
modelAndView.setViewName("items/itemsList"); return modelAndView;
}
}
8.6.4编写jsp 8.7加载spring容器
将mapper、service、controller加载到spring容器中。
建议使用通配符加载上边的配置文件。
在web.xml中,添加spring容器监听器,加载spring容器。 <!-- 加载spring容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- <param-value>/WEB-INF/classes/spring/applicationContext-*.xml</param-value> -->
<param-value>/WEB-INF/classes/spring/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> 9.商品修改功能开发
9.1需求:
操作流程:
1.进入商品查询列表页面
2.点击修改,进入商品修改页面,页面中显示了要修改的商品(从数据库查询),要修改的商品从数据库查询,根据商品id(主键)查询商品信息。
3.在商品修改页面,修改商品信息,修改后,点击提交。 9.2开发mapper
mapper:
根据id查询商品新
根据id更新Items表的数据
不用开发了,使用逆向工程生成的代码。 9.3开发service
接口功能:
根据id查询商品新
修改商品信息
/**
* 根据id查询商品信息
* <p>
* Title: selectItemById
* </p>
* <p>
* Description:
* </p>
*
* @param id
* @return
* @throws Exception
*/
public ItemsCustom selectItemById(Integer id) throws Exception; /**
* 根据id更新商品信息s
* <p>
* Title: updateItemsById
* </p>
* <p>
* Description:
* </p>
*
* @param id
* @param itemsCustom
* @return
* @throws Exception
*/
public Integer updateItemsById(Integer id, ItemsCustom itemsCustom) throws Exception; 9.4开发controller
方法:
商品信息修改页面显示
商品信息修改提交 10@RequestMapping
*url映射
定义controller方法对应的url,进行处理器映射使用。 *窄化请求映射
@Controller
//为了对url进行分类管理,可以在这里定义根路径,最终访问url是根路径+子路径
@RequestMapping("/items")
public class ItemsController { *限制http请求方法
出于安全性考虑,对http的链接进行方法限制。
如果限制请求为post方法,进行get请求,报错,
@RequestMapping(value = "/editItems", method = { RequestMethod.GET, RequestMethod.POST })
11.controller方法的返回值
*返回ModelAndView
需要方法结束时,定义ModelAndView,将model和view分别进行设置。 *返回String
如果controller方法返回string 1.表示返回逻辑视图名。
真正视图(jsp路径) = 前缀 + 逻辑视图名 + 后缀 // 商品修改页面显示
// @RequestMapping("/editItems")
// 限制http的请求方法
@RequestMapping(value = "/editItems", method = { RequestMethod.GET, RequestMethod.POST })
// @@RequestParam里面指定request传入参数名称和形参进行形参绑定
// 通过required属性指定参数是否传入
// 通过defaultValue可以设置默认值,如果id参数没有传入,将默认值和形参绑定
public String editItems(Model model,
@RequestParam(value = "id", required = true/* , defaultValue="" */) Integer items_id) throws Exception { // 调用sevice根据商品id查询商品信息
ItemsCustom itemsCustom = itemsService.selectItemById(items_id); // ModelAndView modelAndView = new ModelAndView();
//
// // 相当于resquest的setAttribute,在jsp页面中通过itemsList取数据
// modelAndView.addObject("itemsCustom", itemsCustom);
//
// // 指定视图
// // 通过springmvc配置文件,可以省掉jsp路径的前缀和后缀
// modelAndView.setViewName("items/editItems"); model.addAttribute("itemsCustom", itemsCustom);
return "items/editItems";
} 2.redirect重定向
商品修改提交后,重定向到商品查询列表。
redirect重定向特点:浏览器地址栏中的url会变化,修改提交的request数据无法传到重定向的地址。因为重定向后重新进行request(request无法共享)
// 重定向
// return "redirect:queryItems.action"; 3.forward页面转发
通过forward进行页面转发,浏览器地址栏url不变,request可以共享。
// 请求转发·
return "forword:queryItems.action"; *返回void
在controller方法形参上可以定义request和response,使用request或response指定响应结果:
1.使用request转向页面,如下:
request.getRequestDispatcher("页面路径").forward(request,response); 2.也可以通过response页面重定向:
response.sendRedirect("url"); 3.也可以通过response指定响应结果,例如响应json数据如下:
response.setCharacterEncoding("utf-8");
response.setContentType("application/json:charset=utf-8");
response.getWriter().write("json串"); 12参数绑定
12.1spring参数绑定过程
从客户端请求key/value数据,经过参数绑定,将key/value数据绑定到controller方法的形参上。 springmvc中,接收页面提交的数据是通过方法形参来接收。而不是在controller类定义成员变更接收
处理器适配器调用springmvc提供参数绑定组件将key/value数据转成controller方法的形参
参数绑定组件:在spirngmvc早期版本使用PropertyEditor(只能将字符串传成java对象)
后期使用converter(进行任意类型的传换)
spirngmvc提供了很多converter(转换器)
在特殊情况下需要自定义converter
对日期数据绑定需要自定义converter 12.2默认支持的类型
直接在controller方法形参上定义下边类型的对象,就可以使用这些对象。在参数绑定过程中,如果遇到下边类型直接进行绑定。 12.2.1HttpServletRequest
通过request对象获取请求信息 12.2.2HttpServletResponse
通过response处理响应信息 12.2.3HttpSession
通过session对象得到session中存放的对象 12.2.4Model/ModelMap
model是一个接口,modelMap是一个接口实现。
作用:将model数据填充到request域。 12.3简单类型
通过@RequestParam对简单类型的参数进行绑定。
如果不使用@RequestParam,要求request传入参数名称和controller方法的形参名称一致,方可绑定成功。 如果使用@RequestParam,不用限制request传入参数名称和controller方法的形参名称一致。
通过required属性指定参数是否必须要传入,如果设置true,没有传入参数,报下边错误:
@RequestParam(value = "id", required = true/* , defaultValue="" */) Integer items_id) throws Exception { 12.4pojo绑定
页面中的input的name和controller的pojo形参中的属性名称一致,将页面中数据绑定到pojo。 页面定义:
<form id="itemForm"
action="${pageContext.request.contextPath }/items/editItems.action"
method="post" enctype="multipart/form-data">
<input type="hidden" name="id" value="${itemsCustom.id }" /> 修改商品信息:
<table width="100%" border=1>
<tr>
<td>商品名称</td>
<td><input type="text" name="name" value="${itemsCustom.name }" /></td>
</tr>
<tr>
<td>商品价格</td>
<td><input type="text" name="price"
value="${itemsCustom.price }" /></td>
</tr>
<tr>
<td>商品生产日期</td>
<td><input type="text" name="createtime"
value="<fmt:formatDate value="${itemsCustom.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/>" /></td>
</tr>
<tr>
<td>商品图片</td>
<td><c:if test="${itemsCustom.pic !=null}">
<img src="/pic/${itemsCustom.pic}" width=100 height=100 />
<br />
</c:if> <input type="file" name="pictureFile" /></td>
</tr>
<tr>
<td>商品简介</td>
<td><textarea rows="3" cols="30" name="detail">${itemsCustom.detail }</textarea>
</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="提交" />
</td>
</tr>
</table> </form>
controller的pojo形参的定义:
public class Items {
private Integer id; private String name;
private Float price;
private String pic;
private Date createtime;
private String detail;
12.5自定义参数绑定实现日期类型绑定
对于controller形参中pojo对象,如果属性中有日期类型,需要自定义参数绑定。
所以自定义参数绑定将日期转换成java.util.Date类型。
需要向处理器适配器中注入自定义的参数绑定组件。 12.5.1自定义日期类型绑定:
public class CustomDateConverter implements Converter<String, Date> { @Override
public Date convert(String source) {
// 实现将日期串转成util包下的日期类型(格式为:yyyy-MM-dd HH:mm:ss)
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss"); try {
// 转成直接返回
return simpleDateFormat.parse(source);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 如果参数绑定失败放回null
return null;
} }
12.5.2配置方式:
<mvc:annotation-driven
conversion-service="conversionService">
</mvc:annotation-driven> <!-- 自定义参数绑定 -->
<bean id="conversionService" class="">
<!-- 转换器 -->
<property name="converters">
<list>
<!-- 日期类型转换 -->
<bean class="com.changemax.ssm.controller.converter.CustomDateConverter" />
</list>
</property>
</bean> 13.springmvc和struts2的区别
1.springmvc基于方法开发的,struts2基于类开发的。
springmvc将url和controller方法映射。映射成功后springmvc生成一个Handler对象,对象中只包括了一个method。方法执行结束,形参数据销毁。
springmvc的controller开发类似service开发。 2.springmvc可以进行单例开发,并且建议使用单例开发,struts2通过类的成员变量接收参数,无法使用单例,只能使用多例。
3.经过实际测试,struts2速度慢,在于使用struts标签,如果使用struts建议使用jstl。
14.问题
14.1post乱码
在web.xml添加post乱码filter
在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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> 以上就可以解决post请求乱码问题。
对于get请求中文参数乱码问题解决方法有两个:
1.修改tomcat配置文件添加编码与工程编码一致,如下:
<Connector URIEncoding="utf-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/> 2.另外一种方法对参数进行重新编码:
String userName = new String(request.getParamter("userName").getBytes("ISO8859-1"),"utf-8")