Spring3 + Spring MVC+ Mybatis 3+Mysql 项目整合(注解及源码)

时间:2024-01-03 23:06:08

Spring3 + Spring MVC+ Mybatis 3+Mysql 项目整合(注解及源码)

备注:

之前在Spring3 + Spring MVC+ Mybatis 3+Mysql 项目整合中写到的框架只是用于测试使用,隔了一段时间之后回头看看,发现有许多需要改进的地方,最近项目中刚好用到,再次补充下!

1.项目目录:

Spring3 + Spring MVC+ Mybatis 3+Mysql 项目整合(注解及源码)

2.需要的jar包列表:

Spring3 + Spring MVC+ Mybatis 3+Mysql 项目整合(注解及源码)

Spring3 + Spring MVC+ Mybatis 3+Mysql 项目整合(注解及源码)

3.spring bean 配置文件applicationContext.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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd"
default-init-method="init"> <!-- 引入jdbc配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!--创建jdbc数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean> <!-- 创建SqlSessionFactory,同时指定数据源 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis.xml"></property>
<property name="dataSource" ref="dataSource" />
</bean> <!-- 可通过注解控制事务 -->
<tx:annotation-driven transaction-manager="transactionManager"/> <!-- 配置事务的传播特性 -->
<!--
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="create*" propagation="REQUIRED" />
<tx:method name="modify*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="*" read-only="true" />
</tx:attributes>
</tx:advice>
-->
<!-- 配置事务的切入点 -->
<!--
<aop:config>
<aop:pointcut id="targetMethod" expression="execution(* com.matol.service.*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="targetMethod" />
</aop:config>
-->
<!-- Mapper接口所在包名,Spring会自动查找其下的Mapper -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.sgl.mapper" />
</bean>
<!-- 负责注册JSR-250 的注释生效 @Resource MapperScannerConfigurer配置会自动启用mapper注解,可省略当前配置
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/>
-->
</beans>

5.spring mvc配置文件springmvc-dispatcher.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans default-lazy-init="true"
xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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-3.0.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.0.xsd"> <!-- 通过注解,把URL映射到Controller上,该标签默认注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter -->
<mvc:annotation-driven />
<!-- annotation默认的方法映射适配器 mvc:annotation-driven注册后可以省略当前配置
<bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean id="handlerAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
--> <!-- 探测注解的包,包括子集, 在JUnit测试的时候需要 --> <!-- 自动扫描bean,把作了注解的类转换为bean -->
<context:component-scan base-package="com.sgl" />
<!-- 加载组装所以配置文件 context:component-scan注册后可以省略当前配置
<context:annotation-config/>
-->

静态资源文件访问条件
<mvc:default-servlet-handler/> <!-- 视图解析器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 使用JSP页面进行输出 -->
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/cms/" />
<!-- 指定了表示层的后缀 -->
<property name="suffix" value=".jsp"></property>
</bean> <!-- 处理文件上传处理 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="UTF-8" /> 此处可配置自定义拦截器 
<!-- <mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/*/**" />
<mvc:exclude-mapping path="/cms/login.jsp"/>
<bean class="com.sgl.interceptor.LinkInterator"></bean>
</mvc:interceptor>
</mvc:interceptors> -->
</beans>

6.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>
<typeAliases>
<typeAlias alias="manager" type="com.sgl.model.ManagerInfo" />
</typeAliases>
<mappers>
<mapper resource="com/sgl/mapping/ManagerInfo.xml" />
</mappers>
</configuration>

7.web.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name>mySpring3 and myBatis3 Project</display-name> <!-- 配置文件位置,默认为/WEB-INF/applicationContext.xml -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param> <!-- 字符集过滤器 -->
<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> <!-- 上下文Spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!-- servlet控制跳转 -->
<servlet>
<servlet-name>spring3</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-dispatcher.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>spring3</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> <!-- 激活静态资源的默认配置,解决Rest风格兼容 -->
<!-- <servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.gif</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.swf</url-pattern>
</servlet-mapping> -->
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>SSM.root</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>WEB-INF/classes/log4j.properties</param-value>
</context-param>
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>600000</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

7.log4j配置(可能比较多,可以选择性使用):

 ### set log levels ###
log4j.rootLogger = ALL , stdout, D , DE
#log4j.rootLogger = ALL, console,allR #system logger
log4j.logger.SysInfoLogger = INFO, SYS_INFO, SYS_ERROR
#log4j.logger.SysErrorLogger = ERROR, SYS_ERROR #business logger
log4j.logger.BizInfoLogger = INFO, BIZ_INFO, BIZ_ERROR
#log4j.logger.BizErrorLogger = ERROR, BIZ_ERROR #gm business logger
log4j.logger.GmBizInfoLogger = INFO, GM_BIZ_INFO, GM_BIZ_ERROR ### \u8F93\u51FA\u5230\u63A7\u5236\u53F0 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Encoding = UTF-8
log4j.appender.stdout.File = ${catalina.home}/logs/output.log
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.Threshold = INFO
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss:SSS} [ %p ] %m%n ### \u8F93\u51FA\u5230\u65E5\u5FD7\u6587\u4EF6 ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.Encoding=UTF-8
log4j.appender.D.File = ${catalina.home}/logs/all_debug.log
log4j.appender.D.MaxFileSize=100KB
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss:SSS} [ %p ] - [ %l ] %m%n ### \u8F93\u51FA\u5230\u65E5\u5FD7\u6587\u4EF6 ###
log4j.appender.DE = org.apache.log4j.DailyRollingFileAppender
log4j.appender.DE.Encoding=UTF-8
log4j.appender.DE.File = ${catalina.home}/logs/all_error.log
log4j.appender.DE.Append = true
log4j.appender.DE.Threshold = ERROR
log4j.appender.DE.layout = org.apache.log4j.PatternLayout
log4j.appender.DE.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %p ] - [ %l ] %m%n ### \u4FDD\u5B58\u5F02\u5E38\u4FE1\u606F\u5230\u5355\u72EC\u6587\u4EF6 ###
log4j.appender.SYS_INFO = org.apache.log4j.DailyRollingFileAppender
log4j.appender.SYS_INFO.Encoding=UTF-8
log4j.appender.SYS_INFO.File = ${catalina.home}/logs/system_info.log
log4j.appender.SYS_INFO.Append = true
log4j.appender.SYS_INFO.Threshold = INFO
log4j.appender.SYS_INFO.layout = org.apache.log4j.PatternLayout
log4j.appender.SYS_INFO.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %p ] %m%n ### \u4FDD\u5B58\u5F02\u5E38\u4FE1\u606F\u5230\u5355\u72EC\u6587\u4EF6 ###\uFFE5\uFFE5
log4j.appender.SYS_ERROR = org.apache.log4j.DailyRollingFileAppender
log4j.appender.SYS_ERROR.Encoding=UTF-8
log4j.appender.SYS_ERROR.File = ${catalina.home}/logs/system_error.log
log4j.appender.SYS_ERROR.Append = true
log4j.appender.SYS_ERROR.Threshold = ERROR
log4j.appender.SYS_ERROR.layout = org.apache.log4j.PatternLayout
log4j.appender.SYS_ERROR.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %p ] %m%n ### \u4FDD\u5B58\u5F02\u5E38\u4FE1\u606F\u5230\u5355\u72EC\u6587\u4EF6 ###
log4j.appender.BIZ_INFO = org.apache.log4j.DailyRollingFileAppender
###log4j.appender.BIZ_INFO = org.apache.log4j.RollingFileAppender
log4j.appender.BIZ_INFO.Encoding=UTF-8
log4j.appender.BIZ_INFO.File = ${catalina.home}/logs/business_info.log
log4j.appender.BIZ_INFO.Append = true
log4j.appender.BIZ_INFO.Threshold = INFO
log4j.appender.BIZ_INFO.layout = org.apache.log4j.PatternLayout
log4j.appender.BIZ_INFO.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss:SSS} [ %p ] %m%n ### \u4FDD\u5B58\u5F02\u5E38\u4FE1\u606F\u5230\u5355\u72EC\u6587\u4EF6 ###\uFFE5\uFFE5
log4j.appender.BIZ_ERROR = org.apache.log4j.DailyRollingFileAppender
log4j.appender.BIZ_ERROR.Encoding=UTF-8
log4j.appender.BIZ_ERROR.File = ${catalina.home}/logs/business_error.log
log4j.appender.BIZ_ERROR.Append = true
log4j.appender.BIZ_ERROR.Threshold = ERROR
log4j.appender.BIZ_ERROR.layout = org.apache.log4j.PatternLayout
log4j.appender.BIZ_ERROR.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %p ] %m%n log4j.appender.GM_BIZ_ERROR = org.apache.log4j.DailyRollingFileAppender
log4j.appender.GM_BIZ_ERROR.Encoding=UTF-8
log4j.appender.GM_BIZ_ERROR.File = ${catalina.home}/logs/gm_business_error.log
log4j.appender.GM_BIZ_ERROR.Append = true
log4j.appender.GM_BIZ_ERROR.Threshold = ERROR
log4j.appender.GM_BIZ_ERROR.layout = org.apache.log4j.PatternLayout
log4j.appender.GM_BIZ_ERROR.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %p ] %m%n

8.控制器:

@Controller
@RequestMapping("/manager")
public class ManagerAction {
private final static String className = ManagerAction.class.getName();
/*可使用@Resource替代@Autowired 例如:@Resource(name = "managerServiceImpl")*/
@Autowired
private ManagerService managerService; @RequestMapping("/login")
public String checkLogin(ModelAndView model) {
ManagerInfo managerInfo=managerService.checkLogin("shupao");
System.out.println(managerInfo.getManagerName());
model.setViewName("index");
LogUtil.businessInfo(className, "manager "+managerInfo.getManagerName()+"login success");
return "index";
}
}

service:

/*@Service(value = "managerService")*/
public interface ManagerService {
public ManagerInfo checkLogin(String name);
}

serviceImpl:

/*@Repository(value = "managerServiceImpl")*/
@Service(value = "managerService")
public class ManagerServiceImpl implements ManagerService {
@Resource(name = "managerMapper")
private ManagerMapper managerMapper;
public ManagerInfo checkLogin(String name) {
// TODO Auto-generated method stub
return managerMapper.checkLogin(name);
} }

mapper:

@Repository(value = "managerMapper")
@Transactional
public interface ManagerMapper{
public ManagerInfo checkLogin(String name);
}

mapping:

<?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.sgl.mapper.ManagerMapper">
<sql id="all_column">
id id,
manager_code managerCode,
manager_name managerName,
status status,
remarks remarks,
deleted deleted,
create_time createTime,
modify_time modifyTime,
password password
</sql>
<select id="checkLogin" parameterType="String" resultType="com.sgl.model.ManagerInfo">
select <include refid="all_column" />
from t_manager_info where manager_name=#{name,jdbcType=VARCHAR}
</select>
</mapper>

总结

知识只有在用的时候才能变得活起来!与上篇文章相比,本次程序搭建的过程更加细致,考虑的东西也更加全面。不过还有许多需要探索的地方,还得加油!