Spring4+SpringMVC+MyBatis整合思路(山东数漫江湖)
1、Spring框架的搭建
这个很简单,只需要web容器中注册org.springframework.web.context.ContextLoaderListener,并指定spring加载配置文件,那么spring容器搭建完成。(当然org.springframework的核心jar包需要引入)
当然为了更加易用支持J2EE应用,一般我们还会加上如下:
Spring监听HTTP请求事件:org.springframework.web.context.request.RequestContextListener
<!-- spring配置文件开始 -->
<context-param>
<param-name>contextConfigLocation</param-name><!-- spring配置文件,请根据需要选取 -->
<param-value>classpath*:webconfig/service-all.xml</param-value>
</context-param>
<listener><!-- Spring负责监听web容器启动和关闭的事件 --><!-- Spring ApplicationContext载入 -->
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener><!-- Spring监听HTTP请求事件 -->
<!-- 使spring支持request与session的scope,如: -->
<!-- <bean id="loginAction" class="com.foo.LoginAction" scope="request"/> -->
<!-- 使用: -->
<!-- 1、注解获取:@Autowired HttpServletRequest request; -->
<!-- 2、java代码:HttpServletRequest request =
((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); -->
<!-- 3、直接在参数中传递:public String sayHi(HttpServletRequest request) -->
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<listener><!-- Spring 刷新Introspector防止内存泄露 -->
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<filter>
<filter-name>encodingFilter</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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>false</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- spring配置文件结束 -->
2、Spring MVC的搭建
首先我们知道Spring MVC的核心是org.springframework.web.servlet.DispatcherServlet,所以web容器中少不了它的注册。(当然org.springframework的web、mvc包及其依赖jar包需要引入)
<!-- spring mvc配置开始 -->
<servlet>
<servlet-name>Spring-MVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring/spring-mvc.xml</param-value><!-- spring mvc配置文件 -->
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Spring-MVC</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- spring mvc配置结束 -->
同时为了更好使用MVC,spring-mvc.xml需要配置以下:
1)(可选)多部分请求解析器(MultipartResolver)配置,与上传文件有关 需要类库commons-io、commons-fileupload
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property><!-- 默认编码-->
<property name="maxUploadSize" value="104857600"></property><!-- 文件大小最大值-->
<property name="maxInMemorySize" value="40960"></property><!-- 内存中的最大值-->
</bean>
2)(可选)本地化(LocaleResolver)配置
3)(可选)主题解析器(ThemeResolver)配置
4)(必选)处理器映射器(HandlerMapping)配置,可以配置多个,一般采用RequestMappingHandlerMapping或者自定义
这里我们自定义了一个处理器映射器,继承重写RequestMappingHandlerMapping,支持@RequestMapping无需任何path参数自动装载类名或方法作为url路径匹配。
<bean id="handlerMapping"
class="io.flysium.framework.web.servlet.mvc.method.annotation.CustomHandlerMapping">
<property name="order" value="-1" />
</bean>
CustomHandlerMapping实现:
@Override
protected RequestMappingInfo getMappingForMethod(Method method, Class handlerType) {
RequestMappingInfo info = createRequestMappingInfoDefault(method);
if (info != null) {
RequestMappingInfo typeInfo = createRequestMappingInfoDefault(handlerType);
if (typeInfo != null)
info = typeInfo.combine(info);
}
return info;
}
private RequestMappingInfo createRequestMappingInfoDefault(AnnotatedElement element) {
RequestMapping requestMapping = AnnotatedElementUtils.findMergedAnnotation(element,
RequestMapping.class);
RequestCondition condition = (element instanceof Class)
? getCustomTypeCondition((Class) element)
: getCustomMethodCondition((Method) element);
/**
* 以类名和方法名映射请求,参照@RequestMapping
* 默认不需要添加任何参数(如:/className/methodName.do)
*/
String defaultName = (element instanceof Class)
? ((Class) element).getSimpleName()
: ((Method) element).getName();
return requestMapping == null
? null
: createRequestMappingInfo(requestMapping, condition, defaultName);
}
protected RequestMappingInfo createRequestMappingInfo(RequestMapping annotation,
RequestCondition<?> customCondition, String defaultName) {
String[] patterns = resolveEmbeddedValuesInPatterns(annotation.value());
if (patterns != null && (patterns.length == 0)) {
patterns = new String[]{defaultName};
}
return new RequestMappingInfo(
new PatternsRequestCondition(patterns, getUrlPathHelper(), getPathMatcher(),
this.useSuffixPatternMatch, this.useTrailingSlashMatch,
this.fileExtensions),
new RequestMethodsRequestCondition(annotation.method()),
new ParamsRequestCondition(annotation.params()),
new HeadersRequestCondition(annotation.headers()),
new ConsumesRequestCondition(annotation.consumes(), annotation.headers()),
new ProducesRequestCondition(annotation.produces(), annotation.headers(),
this.contentNegotiationManager),
customCondition);
}
5)(必选)处理器适配器(HandlerAdapter)配置,可以配置多个,主要是配置messageConverters,其主要作用是映射前台传参与handler处理方法参数。一般扩展RequestMappingHandlerAdapter,或者自定义。如果我们需要json请求的处理,这里必须扩展。同时我们需要注意的是日期格式的转换。
另外Spring 4.2新特性,加之注解会自动注入@ControllerAdvice,可以定义RequestBodyAdvice、ResponseBodyAdvice,可以更方便地在参数处理方面着手自定义。
<bean id="handlerAdapter"
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="order" value="-1" />
<property name="messageConverters">
<list>
<!-- <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"
/> -->
<ref bean="mappingJacksonHttpMessageConverter" />
</list>
</property>
<property name="webBindingInitializer">
<bean
class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="conversionService">
<!-- 针对普通请求(非application/json) 前台的日期字符串与后台的Java Date对象转化,
此情况,应使用spring
mvc本身的内置日期处理 -->
<!-- 可以在VO属性上加注解:@DateTimeFormat 需要类库joda-time -->
<bean
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
</bean>
</property>
</bean>
</property>
</bean>
<!-- json请求(application/json)返回值Date转String,全局配置 -->
<bean name="jacksonObjectMapper"
class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="featuresToDisable">
<array>
<util:constant
static-field="com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS" />
</array>
</property>
<!-- 如果想自定义,可以在VO属性上加注解:@JsonFormat(shape = JsonFormat.Shape.STRING, pattern
= Consts.DATE_PATTERN.DATE_PATTERN_OBLIQUE,timezone = "GMT+8") -->
<property name="simpleDateFormat">
<value>yyyy-MM-dd HH:mm:ss</value>
</property>
</bean>
<!--避免IE执行Ajax时,返回JSON出现下载文件 -->
<!-- 自定义 -->
<bean id="mappingJacksonHttpMessageConverter"
class="io.flysium.framework.http.converter.json.CustomJackson2HttpMessageConverter">
<property name="objectMapper" ref="jacksonObjectMapper" />
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
6)(可选)处理器异常解析器(HandlerExceptionResolver)配置,可以配置多个,配置Controller异常抛出后,我们是怎么样处理的,一般需要日志或做反馈的可以自定义。
7)(可选)请求到视图名翻译器(RequestToViewNameTranslator)配置,RequestToViewNameTranslator可以在处理器返回的View为空时使用它根据Request获得viewName。
8)(可选)视图解析器(ViewResolver)配置,可以配置多个,定义跳转的文件的前后缀 ,视图模式配置,主要针对@Controller返回ModelAndView的视图路径解析,动给后面控制器的方法return的字符串 加上前缀和后缀,变成一个 可用的url地址 。
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
</bean>
最后给Controller加入组件扫描吧,这样减少xml配置,直接在Java代码中加入注解即可。
<!-- 自动扫描类包,将标志Spring注解的类自动转化为Bean,同时完成Bean的注入 -->
<!-- 扫描控制器 -->
<context:component-scan base-package="io.flysium" use-default-filters="false">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
<context:include-filter type="annotation"
expression="org.springframework.web.bind.annotation.RestController" />
<context:include-filter type="annotation"
expression="org.springframework.web.bind.annotation.ControllerAdvice" />
</context:component-scan>
3、Mybatis整合
整合mybatis到Spring框架,我们需要mybatis的jar包,及mybatis-spring整合jar包。然后在Spring容器中注册配置org.mybatis.spring.SqlSessionFactoryBean(需要数据源,及指定Mybatis配置文件)及org.mybatis.spring.SqlSessionTemplate即可。
更多整合请参照Git项目:https://git.oschina.net/svenaugustus/app-ss4m-less
目前除了ssm,另外整合redis(支持切换单节点配置、主从哨兵配置,集群配置)、spring session方案。
其中包括spring MVC的简单demo,用于学习交流。
Spring4+SpringMVC+MyBatis整合思路(山东数漫江湖)的更多相关文章
- Spring+SpringMVC+MyBatis整合(山东数漫江湖)
Spring+SpringMVC+MyBatis(SSM)在我们项目中是经常用到的,这篇文章主要讲解使用Intellij IDEA整合SSM,具体环境如下: 数据库:MySQL5.7 依赖管理:Mav ...
- SSM三大框架整合详细总结(Spring+SpringMVC+MyBatis)(山东数漫江湖)
使用 SSM ( Spring . SpringMVC 和 Mybatis )已经很久了,项目在技术上已经没有什么难点了,基于现有的技术就可以实现想要的功能,当然肯定有很多可以改进的地方.之前没有记录 ...
- Spring与MyBatis的整合(山东数漫江湖)
首先看一下项目结构图: 具体步骤如下: 1.建立JDBC属性文件 jdbc.properties (文件编码修改为 utf-8 ) driver=com.mysql.jdbc.Driver url=j ...
- IDEA下使用maven构建web项目(SpringMVC+Mybatis整合)
需求背景:由于最近总是接到一些需求,需要配合前端团队快速建设移动端UI应用或web应用及后台业务逻辑支撑的需求,若每次都复用之前复杂业务应用的项目代码,总会携带很多暂时不会用到的功能或组件,这样的初始 ...
- idea+spring4+springmvc+mybatis+maven实现简单增删改查CRUD
在学习spring4+springmvc+mybatis的ssm框架,idea整合简单实现增删改查功能,在这里记录一下. 原文在这里:https://my.oschina.net/finchxu/bl ...
- Spring+springmvc+Mybatis整合案例 annotation版(myeclipse)详细版
Spring+springmvc+Mybatis整合案例 Version:annotation版 文档结构图: 从底层开始做起: 01.配置web.xml文件 <?xml version=&qu ...
- Spring+springmvc+Mybatis整合案例 xml配置版(myeclipse)详细版
Spring+springmvc+Mybatis整合案例 Version:xml版(myeclipse) 文档结构图: 从底层开始做起: 01.配置web.xml文件 <?xml version ...
- 框架篇:Spring+SpringMVC+Mybatis整合开发
前言: 前面我已搭建过ssh框架(http://www.cnblogs.com/xrog/p/6359706.html),然而mybatis表示不服啊. Mybatis:"我抗议!" ...
- 学习笔记_J2EE_SSM_01_spring+springMVC+Mybatis整合_XML配置示例
spring+springMVC+Mybatis整合_XML配置示例 1.概述 spring+springMVC+Mybatis整合 XML配置方式 1.1 测试环境说明 名称 版本 备注 操作系统 ...
随机推荐
- C#,Winform 文件的导入导出 File
1.导入 导入对话框:OpenFileDialog private void sbtnsb_Click(object sender, EventArgs e) { try { OpenFileDial ...
- Qt Creator子目录项目-类似VS解决方案
版权声明:若无来源注明,Techie亮博客文章均为原创. 转载请以链接形式标明本文标题和地址: 本文标题:Qt Creator子目录项目-类似VS解决方案 本文地址:http://techie ...
- Dubbo分享
1. Dubbo是什么? Dubbo是一个分布式服务框架,致力于提供高性能和透明化的RPC远程服务调用方案,以及SOA服务治理方案.简单的说,dubbo就是个服务框架,如果没有分布式的需求,其实是不需 ...
- Git更新github项目
1. 把github上你想要更新修改的项目克隆到本地 $ git clone https://github.com/delav/test.git 2. 根据自己需求对项目进行修改 3. 把项目放到缓存 ...
- Python列表去重的三种方法
1. 列表去重 li = [] for item in my_list: if item not in li: li.append(item) 2.集合去重 list(set(my_list)) 3. ...
- hadoop 使用map将SequenFile里的小文件解压出来
上例中将HDFS里小文件通过mapper压缩到一个文件中,本例将这些小文件解压出来. mapreduce可以按SequenceFile的key进行分片. 1.mapper public class M ...
- [Leetcode] search for a range 寻找范围
Given a sorted array of integers, find the starting and ending position of a given target value. You ...
- 牛客网 Wannafly挑战赛27 蓝魔法师
蓝魔法师 链接: https://www.nowcoder.com/acm/contest/215/C 来源:牛客网 题目描述 "你,你认错人了.我真的,真的不是食人魔."--蓝魔 ...
- NOIP2018普及&提高题解
第一次考$NOIP$的我已经自闭了 $CCF$告诉我们了一件事情,要对自己写的程序有信仰,相信$CCF$的数据是水的 普及组: 分数:$100+100+30+100=330$ $1.titile$: ...
- js正则:两边字符固定,中间任意字符
求些一个js正则!两边字符固定,中间任意字符.在一个长字符串里面匹配一小段,这一小段字符串开头和结尾都是固定的字符,就是中间是任意长度的字符.怎么写? /aa.+aa/ aa是你的固定字符,如果是反斜 ...