目录
1.导入jar包
- 导入spring相关jar包
- 导入AOP联盟jar包
- 导入mybatis及其整合spring的jar包
- 导入数据库驱动包和dbcp连接池包
- 导入pageHelper分页插件
- 导入log4j日志包
- 导入文件上传jar包
- 导入json包
- 导入JSTL包(如果需要)
2.编辑web.xml
主要配置springMVC的核心控制器和加载spring配置文件等。
<?xml version="1.0" encoding="UTF-8"?>
<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_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>SSM</display-name>
<!-- 配置spring提供的编码过滤器 -->
<filter>
<filter-name>encodeFilter</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>encodeFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置springMVC的核心控制器 -->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 如果spring配置文件命名为"<servlet-name>-servlet.xml",那么以下的初始化不用写 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- 配置异常跳转页面 -->
<!-- <error-page> -->
<!-- <error-code>404</error-code> -->
<!-- <location>/errorPage404.jsp</location> -->
<!-- </error-page> -->
<!-- <error-page> -->
<!-- <error-code>500</error-code> -->
<!-- <location>/errorPage500.jsp</location> -->
<!-- </error-page> -->
</web-app>
3.编写applicationContext.xml
和web.xml同级,这里的applicationContext.xml被用于加载多个资源文件,名字与web.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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
">
<import resource="application-mybatis.xml"/>
<import resource="application-spring.xml"/>
<import resource="application-springMVC.xml"/>
</beans>
3.1编写application-spring.xml
和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: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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
">
<!-- 启动spring的扫描注解 -->
<context:component-scan base-package="com.gjy"></context:component-scan>
<!-- 配置事务管理器 -->
<bean id="transactionManager_bean" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dbcp_bean"></property>
</bean>
<!-- 事务的传播规则 -->
<tx:advice id="tx_advice" transaction-manager="transactionManager_bean">
<tx:attributes>
<!-- 以下method name为方法名的前缀,根据需要修改;propagation为传播规则,
一般默认REQUIRED;isolation为事务隔离级别;rollback-for表示在指定的异常
出现后回滚 -->
<tx:method name="add*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="java.lang.NullPointerException" />
<tx:method name="modify*" propagation="REQUIRED" isolation="READ_COMMITTED" no-rollback-for="java.lang.NullPointerException"/>
<tx:method name="remove*" propagation="REQUIRED"/>
<!-- 写下边这个其实就可以了,别整那些花里胡哨的 -->
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!-- aop实现事务管理 -->
<aop:config>
<!-- 切入点(方法的集合)
expression的第一个"*"表示方法返回类型,"com.gjy.serviceImpl.*"表示
"com.gjy.serviceImpl"包下的所有类,再".*"表示类中的所有方法,"()"里的
".."表示方法的参数 -->
<aop:pointcut id="aop_pointcut" expression="execution(* com.gjy.serviceImpl.*.*(..))"/>
<!-- 通知 -->
<aop:advisor pointcut-ref="aop_pointcut" advice-ref="tx_advice"/>
</aop:config>
</beans>
3.2编写application-springMVC.xml
和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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
">
<!-- 启动springMVC的注解方式 -->
<!--
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
-->
<!-- 或者用下边的方式 -->
<mvc:annotation-driven conversion-service="conversionService_bean" />
<!-- 配置springMVC的拦截器 -->
<mvc:interceptors>
<bean class="com.gjy.interceptor.MyInterceptor"></bean>
</mvc:interceptors>
<!-- 配置数据类型转换器 -->
<bean id="conversionService_bean" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<!-- 配置日期类型转换器 -->
<bean class="com.gjy.converter.DateConverter"></bean>
</list>
</property>
</bean>
<!-- 配置文件上传解析器 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="utf-8">
</bean>
</beans>
3.3编写application-mybatis.xml
和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: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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
">
<!-- 加载properties配置文件 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:db.properties</value>
</list>
</property>
</bean>
<!-- 数据库信息存入dbcp -->
<bean id="dbcp_bean" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${db_driver}"></property>
<property name="url" value="${db_url}"></property>
<property name="username" value="${db_username}"></property>
<property name="password" value="${db_password}"></property>
</bean>
<!-- 加载mybatis的org.mybatis.spring.SqlSessionFactoryBean -->
<!-- 如果使用加载资源文件的方式指定数据源,bean的id必须为sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入dbcp -->
<property name="dataSource" ref="dbcp_bean"></property>
<!-- 为"com.gjy.model"包下的实体类起别名,根据需要修改value -->
<property name="typeAliasesPackage" value="com.gjy.model.*"></property>
<property name="plugins">
<list>
<!-- 添加分页插件 -->
<ref bean="pageHelper_bean"/>
</list>
</property>
</bean>
<!-- 扫描"com.gjy.dao"包下的映射文件,根据需要修改value -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.gjy.dao"></property>
<!-- 如果使用加载资源文件的方式指定数据源,SqlSessionFactoryBean的beanID强制为
"sqlSessionFactory",那么下边这行不用且不能写;如果不使用加载资源文件的方式指定数据
源,即不使用"$",那么SqlSessionFactoryBean的beanID不强制为"sqlSessionFactory",
下边这行必须写,ref的值与SqlSessionFactoryBean的beanID保持一致 -->
<!--
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
-->
</bean>
<!-- 配置mybatis的分页插件 -->
<bean id="pageHelper_bean" class="com.github.pagehelper.PageHelper">
<property name="properties">
<props>
<!-- 配置方言 -->
<prop key="dialect">mysql</prop>
</props>
</property>
</bean>
</beans>
4.编写数据源db.properties
该文件放于src目录下。
db_driver=com.mysql.jdbc.Driver
db_url=jdbc:mysql://localhost:3306/db_ssm?useUnicode=true&characterEncoding=UTF-8
db_username=root
db_password=root
附录:
1.log4j配置文件log4j.properties
该文件放于src目录下,文件名必须为log4j.properties,按需更改配置内容。
log4j.rootLogger=debug,stdout,file
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{YYYY-MM-dd HH:mm:ss.SSS} [%-5p]--[%-40.40c{39}:%3L]--%m%n
### direct log messages to file ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=mylog
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{YYYY-MM-dd HH:mm:ss.SSS} [%-5p]--[%-40.40c{39}:%3L]--%m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=DEBUG, stdout
log4j.logger.org.apache=ERROR
log4j.logger.org.apache.ibatis=INFO
log4j.logger.org.springframework=ERROR
log4j.logger.org.mybatis=DEBUG
log4j.logger.org.apache.http=ERROR
log4j.logger.com.netflix=ERROR
2.日期转换器
package com.gjy.converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.core.convert.converter.Converter;
public class DateConverter implements Converter<String, Date> {
@Override
public Date convert(String strDate) {
if ("".equals(strDate) || strDate == null) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = sdf.parse(strDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return date;
}
}
3.springMVC拦截器
package com.gjy.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class MyInterceptor implements HandlerInterceptor {
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
// TODO Auto-generated method stub
System.out.println("最后执行,一般用来释放资源。。。");
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
// TODO Auto-generated method stub
System.out.println("在controller之后执行");
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
// TODO Auto-generated method stub
System.out.println("在controller之前执行");
System.out.println(request.getQueryString());
return true;
}
}