springmvc基础知识
2016-07-25 15:08
239 查看
SpringMVC基础
一、SpringMVC介绍
SpringMVC与Struts2一样都是表现层框架 SpringMVC一般采用注解开发,开发效率相比于Struts2较快,配置文件相对较少,开发方便。
二、SpringMVC开发DEMO
2.1 导入相应的jar包
2.2 创建Conteoller类
该类不需要实现任何接口,只需要在类上添加@Controller注解即可。 @RequestMapping注解指定请求的url,其中“.action”可以加也可以不加。 ModelAndView对象中,将视图设置为“/WEB-INF/jsp/itemList.jsp”,相当于对应的物理视图 举例代码如下:
@Controller public class 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"); return modelAndView; } }
2.3 配置sptingmvc.xml
在springmvc.xml文件中主要配置SpringMVC使用的各种处理器,在DEMO案例中只需要声明注解扫描即可。<?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: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-scan base-package="cn.lx.springmvc.controller"/> </beans>
2.4 配置web.xml中配置整合SpringMVC
<!-- 前端控制器 DispatcherServlet 即为SpringMVC的核心控制器 --> <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>
2.5 访问测试
访问路径为 localhost:8080/项目名/itemList.action三、SpringMVC详解
3.1 执行流程图
![](http://i.imgur.com/42FuGLF.png)
3.2 执行流程详解
1、 用户发送请求至前端控制器DispatcherServlet2、 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响应用户
3.3 组件说明
1、DispatcherServlet:前端控制器用户请求到达前端控制器,它就相当于mvc模式中的c,dispatcherServlet是整个流程控制的中心,由它调用其它组件处理用户的请求,dispatcherServlet的存在降低了组件之间的耦合性。
2、HandlerMapping:处理器映射器
HandlerMapping负责根据用户请求找到Handler即处理器,springmvc提供了不同的映射器实现不同的映射方式,例如:配置文件方式,实现接口方式,注解方式等。
3、Handler:处理器(后端控制器Controller)
Handler 是继DispatcherServlet前端控制器的后端控制器,在DispatcherServlet的控制下Handler对具体的用户请求进行处理。
由于Handler涉及到具体的用户业务请求,所以一般情况需要程序员根据业务需求开发Handler。
4、HandlAdapter:处理器适配器
通过HandlerAdapter对处理器进行执行,这是适配器模式的应用,通过扩展适配器可以对更多类型的处理器进行执行。
5、View Resolver:视图解析器
View Resolver负责将处理结果生成View视图,View Resolver首先根据逻辑视图名解析成物理视图名即具体的页面地址,再生成View视图对象,最后对View进行渲染将处理结果通过页面展示给用户。
6、View:视图
springmvc框架提供了很多的View视图类型的支持,包括:jstlView、freemarkerView、pdfView等。我们最常用的视图就是jsp。 一般情况下需要通过页面标签或页面模版技术将模型数据通过页面展示给用户,需要由程序员根据业务需求开发具体的页面。
7、说明:在springmvc的各个组件中,处理器映射器、处理器适配器、视图解析器称为springmvc的三大组件。
需要用户实现的组件有handler(也即Controller)、view(jsp页面)
3.4 映射器和适配器详解
1、注解扫描使用组件扫描器省去在spring容器配置每个controller类的繁琐。使用<context:component-scan>自动扫描标记@controller的控制器类,配置如下:
<!-- 扫描controller注解,多个包中间使用半角逗号分隔 --> <context:component-scan base-package="cn.lx.springmvc.controller"/>
2、RequestMappingHandlerMapping 处理器映射器
注解式处理器映射器,对类中标记@ResquestMapping的方法进行映射,根据ResquestMapping定义的url匹配ResquestMapping标记的方法,匹配成功返回HandlerMethod对象给前端控制器,HandlerMethod对象中封装url对应的方法Method。 从spring3.1版本开始,废除了DefaultAnnotationHandlerMapping的使用,推荐使用RequestMappingHandlerMapping完成注解式处理器映射。 配置如下:
<!--注解映射器 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> 注解描述: @RequestMapping:定义请求url到处理器功能方法的映射
3、RequestMappingHandlerAdapter 处理器适配器
注解式处理器适配器,对标记@ResquestMapping的方法进行适配。
从spring3.1版本开始,废除了AnnotationMethodHandlerAdapter的使用,推荐使用RequestMappingHandlerAdapter完成注解式处理器适配。 配置如下:
<!--注解适配器 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
4、注解驱动配置
springmvc使用<mvc:annotation-driven>自动加载RequestMappingHandlerMapping和RequestMappingHandlerAdapter,可用在springmvc.xml配置文件中使用<mvc:annotation-driven>替代注解处理器和适配器的配置。 配置方式如下:、
<mvc:annotation-driven>
使用该配置之后就不需要手动配置处理器映射器和处理器适配器,会自动使用最新的映射器和适配器,开发中一般这么配置
3.4 视图解析器配置
InternalResourceViewResolver:支持JSP视图解析 viewClass:JstlView表示JSP模板页面需要使用JSTL标签库,所以classpath中必须包含jstl的相关jar 包。此属性可以不设置,默认为JstlView。 prefix 和suffix:查找视图页面的前缀和后缀,最终视图的址为: 前缀+逻辑视图名+后缀,逻辑视图名需要在controller中返回ModelAndView指定,比如逻辑视图名为hello,则最终返回的jsp视图地址 “WEB-INF/jsp/hello.jsp”
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean>
四、SSM整合
4.1 web.xml文件中配置
1、整合Spring整合Spring主要是配置SpringMVC的核心配置文件applicationContext.xml的位置,具体代码如下
<!--加载spring配置文件 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--配置spring配置文件位置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param>
2、整合SpringMVC
整合SpringMVC的关键是配置SpringMVC的核心控制器DispatcherServlet,并指明SpringMVC的配置文件springmvc.xml的位置,具体配置如下:
<!-- 配置springmvc前端控制器 配置方式和struts的前端控制器类似 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置初始化参数,指明springmvc配置文件位置 默认会加载web-inf/servletname-servlet.xml --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <!-- 配置Servlet加载时机,服务器启动时加载 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <!-- /*拦截所有请求 包括jsp html css js jpg /拦截除了jsp外的所有请求 ,包括html css js jpg 但可以通过配置<mvc:resources> --> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 使用spring中的编码过滤器解决post请求乱码问题 -->
3、一般还需要配置Spring解决post请求乱码的过滤器
<filter> <filter-name>ecode</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <!-- 指定使用utf-8编码 --> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>ecode</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
4.2 springmvc.xml配置文件
springmvc.xml配置文件中主要配置mvc注解驱动,视图解析器,如有需要还需要配置异常处理器、文件上传处理器、自定义拦截器、转换器、静态资源访问等。
<?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: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-scan base-package="cn.lx.springmvc.controller"/> <!-- 加载注解驱动 配置注解驱动就不需要手动配置处理映射器和处理适配器 自动进行配置处理映射器和处理适配器 conversion-service="conversionService" 声明转换器 --> <mvc:annotation-driven conversion-service="conversionService"/> <!-- 转换器配置 --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="cn.lx.springmvc.util.DateConverter"/> </set> </property> </bean> <!-- 配置视图解析器 --> <!-- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> --> <!-- 异常处理器 --> <bean id="handlerExceptionResolver" class="cn.lx.springmvc.exception.MyExceptionHandlerResolver"/> <!-- 文件上传 图片上传处理器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 设置上传文件的最大尺寸为5MB --> <property name="maxUploadSize"> <value>5242880</value> </property> </bean> <!-- 配置拦截器 --> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="cn.lx.springmvc.exception.LoginInterceptor"></bean> </mvc:interceptor> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="cn.lx.springmvc.interceptor.MyInteceptor"></bean> </mvc:interceptor> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="cn.lx.springmvc.interceptor.MyInteceptor2"></bean> </mvc:interceptor> </mvc:interceptors> <!--配置静态资源访问 --> <mvc:resources location="/js/" mapping="/js/**"/> </beans>
4.3整合Mybatis
整合Mybatis只需要在applicationContext-dao.xml中配置数据源、SqlSessionFactory,使用包扫描的方式配置mapper代理对象
<?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:db.properties" /> --> <!-- 数据库连接池 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/spring_mvc?characterEncoding=utf-8" /> <property name="username" value="root" /> <property name="password" value="root" /> <property name="maxActive" value="10" /> <property name="maxIdle" value="5" /> </bean> <!-- mapper配置 --> <!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 数据库连接池 --> <property name="dataSource" ref="dataSource" /> <!-- 加载mybatis的全局配置文件 --> <property name="configLocation" value="classpath:SqlMapConfig.xml" /> </bean> <!-- 使用包扫描的方式配置mapper代理对象--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- basePackage配置要扫描的包 如果有多个包,用,进行分割 --> <property name="basePackage" value="cn.lx.springmvc.mapper"></property> <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> </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:component-scan base-package="cn.lx.springmvc.service.impl"/> </beans>
在applicationContext.xml中配置事务处理器、事务行为、AOP切面等内容
<?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"> <!--配置事务管理器 --> <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" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="find*" propagation="SUPPORTS" read-only="true" /> <tx:method name="get*" propagation="SUPPORTS" read-only="true" /> </tx:attributes> </tx:advice> <!-- 事务行为与切面整合 --> <aop:config> <aop:pointcut expression="execution(* cn.lx.springmvc.service.impl.*.*(..))" id="pointcut"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" /> </aop:config> <import resource="spring/applicationContext-dao.xml"/> <import resource="spring/applicationContext-service.xml"/> </beans>
相关文章推荐
- java正则表达式校验移动电话、固话、邮编的校验
- 23种java设计模式之工厂模式
- java线程学习——线程安全(同步)
- eclipse workplace 路径
- struts2环境配置
- Realm Java 你需要知道的所有信息都在这里
- 阿里云oss springMVC+ajax后台和前端上传文件
- java线程学习——创建线程的两种方法
- Java NIO系列教程(2):Channel
- JAVA解析JSON
- springmvc拦截器,用户登录拦截过程
- java的quartz定时调度
- Java容器源码解析
- Eclipse快捷键
- java(web) url问号传值,中文乱码解决办法
- Java序列化与反序列化
- java concurrent包介绍及使用
- java cmd命令行初识helloworld
- byte[]与String互相转换
- JAVA垃圾回收GC