Spring4+SpringMVC+MyBatis整合思路
admin
2023-04-11 06:42:51
0

本文主要简单讲解框架整合的思路。
1、Spring框架的搭建

这个很简单,只需要web容器中注册org.springframework.web.context.ContextLoaderListener,并指定spring加载配置文件,那么spring容器搭建完成。(当然org.springframework的核心jar包需要引入)

当然为了更加易用支持J2EE应用,一般我们还会加上如下:

Spring监听HTTP请求事件:org.springframework.web.context.request.RequestContextListener



contextConfigLocation
classpath:webconfig/service-all.xml


org.springframework.web.context.ContextLoaderListener








org.springframework.web.context.request.RequestContextListener


org.springframework.web.util.IntrospectorCleanupListener


encodingFilter
org.springframework.web.filter.CharacterEncodingFilter

encoding
UTF-8


forceEncoding
false



encodingFilter
/


2、Spring MVC的搭建

首先我们知道Spring MVC的核心是org.springframework.web.servlet.DispatcherServlet,所以web容器中少不了它的注册。(当然org.springframework的web、mvc包及其依赖jar包需要引入)



Spring-MVC
org.springframework.web.servlet.DispatcherServlet

contextConfigLocation
classpath:spring/spring-mvc.xml

1


Spring-MVC
.do

同时为了更好使用MVC,spring-mvc.xml需要配置以下:

1)(可选)多部分请求解析器(MultipartResolver)配置,与上传文件有关 需要类库commons-io、commons-fileupload





2)(可选)本地化(LocaleResolver)配置

3)(可选)主题解析器(ThemeResolver)配置

4)(必选)处理器映射器(HandlerMapping)配置,可以配置多个,一般采用RequestMappingHandlerMapping或者自定义

这里我们自定义了一个处理器映射器,继承重写RequestMappingHandlerMapping,支持@RequestMapping无需任何path参数自动装载类名或方法作为url路径匹配。

class="io.flysium.framework.web.servlet.mvc.method.annotation.CustomHandlerMapping">

CustomHandlerMapping实现:@Override
br/>@Override
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,可以更方便地在参数处理方面着手自定义。

class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">








class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">



class="org.springframework.format.support.FormattingConversionServiceFactoryBean">






class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">


static-field="com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS" />




yyyy-MM-dd HH:mm:ss




class="io.flysium.framework.http.converter.json.CustomJackson2HttpMessageConverter">



text/html;charset=UTF-8
application/json;charset=UTF-8


6)(可选)处理器异常解析器(HandlerExceptionResolver)配置,可以配置多个,配置Controller异常抛出后,我们是怎么样处理的,一般需要日志或做反馈的可以自定义。

7)(可选)请求到视图名翻译器(RequestToViewNameTranslator)配置,RequestToViewNameTranslator可以在处理器返回的View为空时使用它根据Request获得viewName。

8)(可选)视图解析器(ViewResolver)配置,可以配置多个,定义跳转的文件的前后缀 ,视图模式配置,主要针对@Controller返回ModelAndView的视图路径解析,动给后面控制器的方法return的字符串 加上前缀和后缀,变成一个 可用的url地址 。

class="org.springframework.web.servlet.view.InternalResourceViewResolver">


value="org.springframework.web.servlet.view.JstlView" />

最后给Controller加入组件扫描吧,这样减少xml配置,直接在Java代码中加入注解即可。



expression="org.springframework.stereotype.Controller" />
expression="org.springframework.web.bind.annotation.RestController" />
expression="org.springframework.web.bind.annotation.ControllerAdvice" />

3、Mybatis整合

整合mybatis到Spring框架,我们需要mybatis的jar包,及mybatis-spring整合jar包。然后在Spring容器中注册配置org.mybatis.spring.SqlSessionFactoryBean(需要数据源,及指定Mybatis配置文件)及org.mybatis.spring.SqlSessionTemplate即可。

相关内容

热门资讯

实探杭州“被电商拉黑”街道:随... 据扬子晚报报道,5月6日,一名网友在社媒发帖称,自己在某电商平台看中了一款商品,商品界面却显示其地址...
大连女子烧烤店内用铁签喂狗,十... 5月11日,一段网传视频显示,女子让宠物狗坐在辽宁大连一家烧烤店的卡座上,并用铁签将肉串喂给宠物狗,...
沃尔核材获得实用新型专利授权:... 证券之星消息,根据天眼查APP数据显示沃尔核材(002130)新获得一项实用新型专利授权,专利名为“...
科技伦理审查助力人工智能产业高... 转自:证券日报     本报记者 郭冀川     随着AI(人工智能)技术迭代加速,相关伦理审查的重...
捷昌驱动获得实用新型专利授权:... 证券之星消息,根据天眼查APP数据显示捷昌驱动(603583)新获得一项实用新型专利授权,专利名为“...
2026云手机为什么这么火?这... 你是否也有过这样的念头:想试试云手机,但一看价格,月付几十甚至上百元,立马打了退堂鼓?又或者,你曾贪...
OPPO失智,武大失格,舆论失... 无知,无品,无趣。文 | 佘宗明小说《围城》里,方鸿渐在张家跟张小姐相亲,看到书架上有本《怎样去获得...
百名上海交大学子携40项科研成... 中新网上海5月11日电(记者 许婧)未来电池如何破解“放着也会老化”的难题?免疫细胞与癌细胞的“对话...
你的蓝牙耳机正在 “偷听”?这... 在科技飞速发展的当下,无线耳机、智能手表、无线键盘等蓝牙设备凭借“一键连接”带来的便捷优势,已广泛应...
微信状态能看访客了?热搜爆了!... 5月11日晚间,#微信状态 访客记录#话题冲上微博热搜,引发大量网友讨论。 有网友发帖询问:“微信...