一、Springmvc介绍
Springmvc和Struts2都属于表现层的框架
组件说明
1.DispatcherServlet:前端控制器 mvc模式中的c
1)整个流程控制的中心,负责调用其它组件处理用户的请求。
2)降低了组件之间的耦合性
2.HandlerMapping:处理器映射器
1)根据用户请求url找到Handler即处理器。
2)springmvc提供了不同的映射器实现不同的映射方式,例如:配置文件方式,实现接口方式,注解方式等。
3.Handler:处理器 又称后端控制器
1)在DispatcherServlet的控制下Handler完成 对具体的用户请求进行处理。
2)需要程序员自主开发。
4.HandlAdapter:处理器适配器
1)执行对应处理器
5.ViewResolver:视图解析器
1)负责将处理结果生成View视图,
View Resolver首先根据逻辑视图名解析成物理视图名即具体的页面地址,
再生成View视图对象,
最后对View进行渲染将处理结果通过页面展示给用户。
6.View:视图
springmvc框架提供了很多的View视图类型的支持,包括:jstlView、freemarkerView、pdfView等。我们最常用的视图就是jsp。
需要用户开发的组件是 Handler、view(jsp)
springmvc的三大组件(默认配置):处理器映射器、处理器适配器、视图解析器
Springmvc与Struts的区别
1、入口:
springmvc:servlet(前端控制器)
struts2:filter(过滤器)
2、开发模式
springmvc:基于方法开发(一个url对应一个方法),请求参数传递到方法的形参,可以设计为单例或多例(建议单例),
struts2:基于类开发,传递参数是通过类的属性,只能设计为多例。
3、数据存取方式
springmvc:通过参数解析器是将request请求内容解析,并给方法形参赋值,将数据和视图封装成ModelAndView对象,
最后又将ModelAndView中的模型数据通过request域传输到页面。Jsp视图解析器默认使用jstl。
Struts2:采用值栈存储请求和响应的数据,通过OGNL存取数据
Springmvc处理流程
流程解释
1、 用户发送请求至DispatcherServlet(前端控制器)
2、 DispatcherServlet收到请求调用HandlerMapping(处理器映射器)。
3、 处理器映射器 返回 对应Handler(处理器)的路径(包名+类名+方法名)以及处理器拦截器(如果有则生成)
细节: 根据请求url找到对应的的处理器,并实例化处理器对象(Controler),最终返回实例化的处理器对象路径
4、 DispatcherServlet通过HandlerAdapter(处理器适配器)调用处理器
5、 执行Controller(处理器 或 后端控制器)。
6、 执行完成返回ModelAndView
7、 HandlerAdapter将controller执行结果ModelAndView返回给DispatcherServlet
8、 DispatcherServlet将ModelAndView传给ViewReslover(视图解析器)
9、 ViewReslover解析后返回具体View
10、 DispatcherServlet对View进行渲染视图(即将模型数据填充至视图中)。
11、DispatcherServlet响应用户
二、Springmvc入门程序
入门步骤:
第一步:创建Web工程、导Jar包
第二步:web.xml配置前端控制器 servlet
1)<servlet-class> 配置DispatcherServlet类名
2)<init-param>指定上下文路径:classpath:springmvc.xml
3) <servlet-mapping>配置对url的过滤 如:以.action结尾的url进入springmvc
第三步:配置springmvc.xml 配置开启扫描<context:component-scan> 扫描@Controller、@service
第四步:Handler (Controller)
@RequestMapping(value="/路径.action")
Public ModelAndView 方法名(){
modelAndView.setViewName("跳转至jsp");
}
代码示例:
web.xml
<!-- springmvc配置 -->
<!-- 配置spring前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 指定SpringMVC配置文件 -->
<!-- 默认寻找路径是/WEB-INF/${servlet-name}-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结尾的请求进入SpringMVC -->
<url-pattern>*.action</url-pattern>
</servlet-mapping>
springmvc 配置
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
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://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 配置扫描包 可扫描@Controller,@Service -->
<context:component-scan base-package="springmvc" />
<!-- 视图解释器 配置固定前后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
Controller
@Controller
public class ItemController {
// @RequestMapping:里面放的是请求的url,和用户请求的url进行匹配
@RequestMapping(value = "/itemList.action") // action可以写也可以不写
public ModelAndView queryItemList() {
// 创建页面需要显示的商品数据
List<Item> list = new ArrayList<>();
list.add(new Item(1, "1华为 荣耀8", 2399, new Date(), "质量好!1"));
list.add(new Item(2, "2华为 荣耀8", 2399, new Date(), "质量好!2"));
list.add(new Item(3, "3华为 荣耀8", 2399, new Date(), "质量好!3"));
// 创建ModelAndView,用来存放数据和视图
ModelAndView modelAndView = new ModelAndView();
// 设置数据到模型中
modelAndView.addObject("itemList", list);
// 设置视图jsp,需要设置视图的物理地址
// modelAndView.setViewName("/WEB-INF/jsp/itemList.jsp");
// 配置好视图解析器前缀和后缀,这里只需要设置逻辑视图就可以了。
// 视图解析器根据前缀+逻辑视图名+后缀拼接出来物理路径
modelAndView.setViewName("itemList");
return modelAndView;
}
}
三、整合Mybatis-springMVC
整合思想
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配置事务。
Controller层:
1、Springmvc.xml
a) 包扫描器,扫描@Controller注解的类。
b) 配置注解驱动
c) 配置视图解析器
Web.xml文件:
1、配置spring
2、配置前端控制器。
3、配置POST提交乱码问题(Filter过滤器)
注:三个文件也可合并配置
applicationContext-dao.xml 与 applicationContext-trans.xml 与 applicationContext-service.xml
整合代码示例:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns: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_mybatis_merge</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:applicationContext.xml</param-value>
</context-param>
<!-- spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- springmvc配置 -->
<!-- 配置spring前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 指定SpringMVC配置文件 -->
<!-- 默认寻找路径是/WEB-INF/${servlet-name}-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结尾的请求进入SpringMVC -->
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
SqlMapConfig.xml
<?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>
</configuration>
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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
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://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 配置扫描包 可扫描@Controller,@Service -->
<context:component-scan base-package="springmvc" />
<!-- 注解驱动 配置扫描包后可不需要注解驱动 -->
<!-- <mvc:annotation-driven/> -->
<!-- 视图解释器 配置固定前后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
applicationContext.xml
<?xml version="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-placeholder location="classpath:jdbc.properties" />
<!-- 数据库连接池 -->
<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="10" />
<!-- 最大空闲数 -->
<property name="maxIdle" value="5" />
</bean>
<!-- 配置SqlSessionFactory,配置三个属性
加载配置文件
加载数据库源
设置别名包扫描 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:SqlMapConfig.xml"/>
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="springmvc.pojo"/>
</bean>
<!-- 动态代理开发,第二种方式,包扫描器(推荐使用) -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- basePackage:配置映射包装扫描,多个包时用","或";"分隔 -->
<property name="basePackage" value="springmvc.dao" />
</bean>
<!-- 注解方式配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
<property name="dataSource" ref="dataSource"/> <!-- 传入被管理的数据库 -->
</bean>
<!-- 开启对指定事务管理器注解的扫描 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
四、乱码解决,转换器
解决POST/GET乱码问题
1. post乱码
在web.xml中加入:
<!-- 解决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>
2. 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")
ISO8859-1是tomcat默认编码,需要将tomcat编码后的内容按utf-8编码
转换器
案例:根据需求自定义日期格式。
Converter
/**
* 转换日期类型数据
*
* 继承Converter接口
* S:页面传递来的类型
* T:转换后的类型
*
* @author 一万年行不行
*/
public class DateConverter implements Converter<String, Date> {
//默认实现方法
@Override
public Date convert(String source) { //source为页面数据
try {
// 把字符串转换为日期类型
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyy-MM-dd HH_mm:ss");
Date date = simpleDateFormat.parse(source); //将source转换为指定格式
return date;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 如果转换异常则返回空
return null;
}
}
springmvc.xml
<mvc:annotation-driven conversion-service="conversionService" />
<!-- 转换器配置 -->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="springmvc.converter.DateConverter" />
</set>
</property>
</bean>