刚学完SSM框架的整合,想找个项目玩玩,网上一搜资源一大把,把项目直接搬进开发工具里,总是遇到各种各样的问题,一方面是项目本身需要结合环境重新配置,一方面自己没办法理解别人的思想。不如从头开始梳理一下SSM框架的配置整合方法,温故而知新!
1. 配置项目对象模型文件pom.xml
使用IEDA基于maven-archetype-webapp模板新建maven项目后,这时候先检查项目的目录结构是否完整,检查java源代码文件库和resources资源库的类型是否正确。检查自动生成的pom.xml文件,先删除里面一些不必要的项如旧版的junit、多余的项目信息后。
由于我们习惯把部分资源文件放在java源代码文件库里如mapper.xml文件,为了保证让maven打包时扫描到,先在build标签下增加这些代码,把xml文件包括进去。
<build>
<finalName>ssm-00</finalName>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
然后,就是最重要的一步,导入所需的jar包,根据需求所用的框架、功能以groupId分类,分别列出artifactId清单,如下;在MyEclipse里可以点击dependencies标签出现界面选择导包,而IDEA里貌似只能通过增加dependency标签的方式来导包。
-
Spring框架的各个组件:org.springframework
spring-core
spring-context
spring-tx
spring-jdbc
spring-test
spring-web
spring-webmvc
spring-aop
spring-context-support
-
面向切面编程:org.aspectj
aspectjweaver
-
Mybatis框架,支持到Spring中:org.mybatis
mybatis
mybatis-spring
-
servelt、jsp组件:servletjavax.servlet
servlet-api
servlet.jsp-api
-
数据库驱动:mysql
mysql-connector-java
-
使用阿里巴巴的连接池和fastjson:com.alibaba
druid
fastjson
-
日志记录:log4j
log4j
-
日志输出:org.slf4j
slf4j-log4j12
-
阿帕奇shiro权限管理:org.apache.shiro
shiro-core
-
引入jackson:org.codehaus.jackson
jack-mapper-asl
-
io流:commons-io
commons-io
-
模板语言:commons-code
commons-codec
-
阿帕奇模板引擎:org.apache.velocity
velocity-tools
velocity
-
文件上传:commons-fileupload
commons-fileupload
-
maven源代码编译插件:org.apache.maven.plugins
maven-compiler-plugins
-
Mybatis-genenerator插件:org.mybatis.generator
mybatis-generator-core
最后一步,在第一步的build标签下增加Mybatis-generator和maven编译源代码插件的配置,pom.xml就配置完成了。
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
2. Spring整合Mybatis配置
Spring就是一个轻量级的控制反转和面向切面的容器框架,IOC容器将对象之间的依赖关系交由Spring进行控制,Spring框架提供了对其他优秀开源框架的接口支持。MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架。
首先,使用Mybatis-generator插件自动生成实体类、DAO接口实现类和Mapper,配置方法已在另一篇博文中。此方法修改路径后,试验证明仍能在项目中使用。但为了在Maven中运行Mybatis-generator插件,需再新建一个Configuration,配置方法如下。确定后,点击新生成的按钮即可运行Mybatis-generator生成代码。
然后,在resources目录下新建spring-config.xml,用来整合Mybatis,作为新手,先理清思路再写代码。配置步骤如下:
- 删除旧版的xml约束,使用完整的新版spring4.0;
- 打开切面编程;
- 打开扫描注解生成bean;
- 包扫描路径;
- 在Spring工厂接口中实现Mybatis整合;
- 设置Mapper接口的路径;
- 配置数据源dataSource,使用阿里巴巴连接池;
- 在6与7之间增加声明事务管理;
- 在4与5之间增加占位符,声明jdbc.properties的位置。
具体代码:
<?xml version="1.0" encoding="UTF-8"?>
<!--1. xml约束-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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"
>
<!--2. 开启切面编程自动代理-->
<aop:aspectj-autoproxy proxy-target-class="true"/>
<!--3. 扫描注解生成bean-->
<context:annotation-config/>
<!--4. 包扫描-->
<context:component-scan base-package="com.me"/>
<!--9. 占位符-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--5. 整合mybatis-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:com/me/**/**.xml"/>
</bean>
<!--6. 设置mapper接口的位置;-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.me.*.dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
<!--8. 声明事务管理 采用注解方式-->
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--7. 配置dataSource,使用阿里巴巴连接池-->
<!--数据库设置-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
destroy-method="close" init-method="init">
<property name="url" value="${jdbc_url}"/>
<property name="username" value="${jdbc_username}"/>
<property name="password" value="${jdbc_password}"/>
<property name="initialSize" value="0"/>
<!-- 最大使用连接数 -->
<property name="maxActive" value="20"/>
<property name="minIdle" value="0"/>
<property name="maxWait" value="60000"/>
<property name="validationQuery" value="${validationQuery}"/>
<property name="testOnBorrow" value="false"/>
<property name="testOnReturn" value="false"/>
<property name="testWhileIdle" value="true"/>
<property name="timeBetweenEvictionRunsMillis" value="60000"/>
<property name="minEvictableIdleTimeMillis" value="25200000"/>
<property name="removeAbandoned" value="true"/>
<property name="removeAbandonedTimeout" value="1800"/>
<property name="logAbandoned" value="true"/>
<!-- <property name="filters" value="stat" /> -->
<property name="filters" value="mergeStat"/>
</bean>
</beans>
在同目录下新建jdbc.properties文件,键入各JDBC参数即可。
3. SpringMVC配置
SpringMVC是一个基于DispatcherServlet的MVC框架,每一个请求最先访问的都是DispatcherServlet。它负责转发每一个Request请求给相应的Handler,Handler处理以后再返回相应的视图和模型。
在resources目录新建spring-mvc.xml文件,开始配置:
- SpringMVC框架的XML约束;
- 包扫描的位置;
- 开启MVC注解扫描
- 配置velocityConfigurer引擎;
- 配置试图解析器
spring-mvc.xml具体代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<!--1. xml约束-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!--2. 包扫描-->
<context:component-scan base-package="com.me.*.controller">
</context:component-scan>
<!--3. 开启注解扫描-->
<mvc:annotation-driven/>
<--4. 配置velocityConfigurer引擎;-->
<bean id="velocityConfigurer" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
<property name="resourceLoaderPath" value="/WEB-INF/views"/>
<property name="velocityProperties">
<props>
<prop key="input.encoding">utf-8</prop>
<prop key="output.encoding">utf-8</prop>
<prop key="file.resource.loader.cache">false</prop>
<prop key="file.resource.loader.modificationCheckInterval">1</prop>
<prop key="velocimacro.library.autoreload">false</prop>
</props>
</property>
</bean>
<--5. 配置视图解析-->
<bean class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
<property name="suffix" value=".vm"/>
<property name="contentType" value="text/html;charset=utf-8"/>
<!--日期函数名称-->
<property name="dateToolAttribute" value="date"/>
</bean>
</beans>
然后在webapp/WEB-INF目录下新建web.xml文件,用于初始化web配置信息:
web.xml
- spring-config.xml配置所在的位置;
- 编码过滤器;
- spring监听器;
- springMVC配置servlet,使用dispatcherServlet启动分发请求;
<?xml version="1.0" encoding="UTF-8"?>
<!--声明web-app的版本,使用3.0的xsd-->
<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_3_0.xsd"
version="3.0">
<display-name>ssm-0</display-name>
<!--2. spring-config.xml配置所在的位置;-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-config.xml</param-value>
</context-param>
<!-- 3. 编码过滤器 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<async-supported>true</async-supported>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 4. Spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 5. Spring MVC servlet-->
<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:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
最后一步,用标题2. 中配置Mybatis-generator运行按钮类似的方法配置Tomcat,新建按钮。
4. 建立service接口和实现类
在user/service路径下分别建立一个接口及其实现类,用于将用户对象的信息插入到数据库中。
UserServiceImpl.java
@Service("UserServiceImpl") public class UserServiceImpl implements UserTeacherService{ @Autowired private UserMapper userMapper; @Override @Transactional(propagation = Propagation.REQUIRED) public int createUser(User user) { userMapper.insertSelective(user); return 0; } }
5. 代码测试
测试Tomcat服务器和MVC是否正常连通,在用户目录下新建一个UserController.java类,在WEB-INF/views下新建test.vm。打上断点,debug模式运行Tomcat,在浏览器地址键入相应映射的路径,访问后查看控制台信息,具体代码:
UserController.java
@Controller @RequestMapping("log") public class UserController { @RequestMapping("/test") public String user(){ User user = new User(); user.setID("13900000000"); user.setAge(100); return "test"; } }
test.vm
<html> <head> <title>Title</title> </head> <body> TESTING! </body> </html>
再测试能否将用户对象信息插入到数据库。对上面的UserController.java这个类稍加修改,引入4. 中的对象,在user()方法内调用creatUser(User user)方法。
UserController.java
@Controller @RequestMapping("log") public class UserController { @Autowired private UserService userService; @RequestMapping("/test") public String user(){ User user = new User(); user.setID("13900000000"); user.setAge(100); userService.createUser(user); return "test"; } }
同样debug调试,用浏览器访问映射地址,运行后查看对应数据库有无增加一条记录。
(完)