使用maven整合Spring+SpringMVC+Mybatis框架详细步骤(图文)
(项目结构图参照文章末尾)
1、创建maven工程,在pom.xml文件中导入需要的jar包依赖:
<project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelversion>4.0.0</modelversion> <groupid>com.test</groupid> <artifactid>ssm</artifactid> <version>0.0.1-snapshot</version> <packaging>war</packaging> <!-- 集中定义版本号 --> <properties> <junit.version>4.12</junit.version> <spring.version>4.1.3.release</spring.version> <mybatis.version>3.2.8</mybatis.version> <mybatis.spring.version>1.2.2</mybatis.spring.version> <mybatis.paginator.version>1.2.15</mybatis.paginator.version> <mysql.version>5.1.32</mysql.version> <slf4j.version>1.6.4</slf4j.version> <jackson.version>2.4.2</jackson.version> <druid.version>1.0.9</druid.version> <httpclient.version>4.3.5</httpclient.version> <jstl.version>1.2</jstl.version> <servlet-api.version>2.5</servlet-api.version> <jsp-api.version>2.0</jsp-api.version> <joda-time.version>2.5</joda-time.version> <commons-lang3.version>3.3.2</commons-lang3.version> <commons-io.version>1.3.2</commons-io.version> <commons-net.version>3.3</commons-net.version> <!-- 因为官方的不支持mybatis逆向工程,在源码上有修改,需要自己手动编译 --> <pagehelper.version>3.4.2-fix</pagehelper.version> <commons-fileupload.version>1.3.1</commons-fileupload.version> <jedis.version>2.7.2</jedis.version> <solrj.version>4.10.3</solrj.version> <swagger.version>2.4.0</swagger.version> </properties> <dependencies> <!-- 时间操作组件 --> <dependency> <groupid>joda-time</groupid> <artifactid>joda-time</artifactid> <version>${joda-time.version}</version> </dependency> <!-- apache工具组件 --> <dependency> <groupid>org.apache.commons</groupid> <artifactid>commons-lang3</artifactid> <version>${commons-lang3.version}</version> </dependency> <dependency> <groupid>org.apache.commons</groupid> <artifactid>commons-io</artifactid> <version>${commons-io.version}</version> </dependency> <dependency><!-- 通信使用的,如http,ftp --> <groupid>commons-net</groupid> <artifactid>commons-net</artifactid> <version>${commons-net.version}</version> </dependency> <!--jackson json处理工具包 --> <dependency> <groupid>com.fasterxml.jackson.core</groupid> <artifactid>jackson-databind</artifactid> <version>${jackson.version}</version> </dependency> <!-- httpclient --> <dependency> <groupid>org.apache.httpcomponents</groupid> <artifactid>httpclient</artifactid> <version>${httpclient.version}</version> </dependency> <!-- 单元测试 --> <dependency> <groupid>junit</groupid> <artifactid>junit</artifactid> <version>${junit.version}</version> <scope>test</scope> </dependency> <!-- 日志处理 --> <dependency> <groupid>org.slf4j</groupid> <artifactid>slf4j-log4j12</artifactid> <version>${slf4j.version}</version> </dependency> <!-- mybatis --> <dependency> <groupid>org.mybatis</groupid> <artifactid>mybatis</artifactid> <version>${mybatis.version}</version> </dependency> <dependency> <groupid>org.mybatis</groupid> <artifactid>mybatis-spring</artifactid> <version>${mybatis.spring.version}</version> </dependency> <dependency> <groupid>com.github.miemiedev</groupid> <artifactid>mybatis-paginator</artifactid> <version>${mybatis.paginator.version}</version> </dependency> <!-- 分页插件 --> <dependency> <groupid>com.github.pagehelper</groupid> <artifactid>pagehelper</artifactid> <version>${pagehelper.version}</version> </dependency> <!-- mysql --> <dependency> <groupid>mysql</groupid> <artifactid>mysql-connector-java</artifactid> <version>${mysql.version}</version> </dependency> <!-- 连接池 --> <dependency> <groupid>com.alibaba</groupid> <artifactid>druid</artifactid> <version>${druid.version}</version> </dependency> <!-- spring --> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-context</artifactid> <version>${spring.version}</version> </dependency> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-beans</artifactid> <version>${spring.version}</version> </dependency> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-webmvc</artifactid> <version>${spring.version}</version> </dependency> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-jdbc</artifactid> <version>${spring.version}</version> </dependency> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-aspects</artifactid> <version>${spring.version}</version> </dependency> <!-- jsp相关 --> <dependency> <groupid>jstl</groupid> <artifactid>jstl</artifactid> <version>${jstl.version}</version> </dependency> <dependency> <groupid>javax.servlet</groupid> <artifactid>servlet-api</artifactid> <version>${servlet-api.version}</version> <scope>provided</scope> </dependency> <dependency> <groupid>javax.servlet</groupid> <artifactid>jsp-api</artifactid> <version>${jsp-api.version}</version> <scope>provided</scope> </dependency> <!-- 文件上传组件 --> <dependency> <groupid>commons-fileupload</groupid> <artifactid>commons-fileupload</artifactid> <version>${commons-fileupload.version}</version> </dependency> <!-- redis客户端 --> <dependency> <groupid>redis.clients</groupid> <artifactid>jedis</artifactid> <version>${jedis.version}</version> </dependency> <!-- solr客户端 --> <dependency> <groupid>org.apache.solr</groupid> <artifactid>solr-solrj</artifactid> <version>${solrj.version}</version> </dependency> <!-- springfox-swagger2 --> <dependency> <groupid>io.springfox</groupid> <artifactid>springfox-swagger2</artifactid> <version>${swagger.version}</version> </dependency> <dependency> <groupid>io.springfox</groupid> <artifactid>springfox-swagger-ui</artifactid> <version>${swagger.version}</version> </dependency> </dependencies> <build> <plugins> <!-- 配置tomcat插件 --> <plugin> <groupid>org.apache.tomcat.maven</groupid> <artifactid>tomcat7-maven-plugin</artifactid> <version>2.2</version> </plugin> <!-- java编译插件 --> <plugin> <groupid>org.apache.maven.plugins</groupid> <artifactid>maven-compiler-plugin</artifactid> <version>3.2</version> <configuration> <source>1.7</source> <target>1.7</target> <encoding>utf-8</encoding> </configuration> </plugin> </plugins> </build> </project>
2、整合springmvc:
(1)在web.xml文件中配置前端控制器:
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="servicemarket" version="2.5"> <display-name>ssm-test</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <!-- 加载spring相关配置文件 --> <context-param> <param-name>contextconfiglocation</param-name> <param-value>classpath:spring/applicationcontext*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.contextloaderlistener</listener-class> </listener> <!-- 解决post乱码 --> <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> <!-- springmvc的前端控制器 --> <servlet> <servlet-name>ssm-test</servlet-name> <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class> <!-- 加载springmvc的配置文件(处理器映射器、处理器适配器等等) --> <init-param> <param-name>contextconfiglocation</param-name> <param-value>classpath:spring/springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>ssm-test</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
(2)编写springmvc.xml文件:
在文件中配置与springmvc框架相关的配置,比如:springmvc.xml约束、处理器映射器、处理器适配器、视图解析器、handler等配置。
<?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:mvc="http://www.springframework.org/schema/mvc" 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-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 使用注解驱动:自动配置处理器映射器与处理器适配器 --> <mvc:annotation-driven /> <!-- 注解方式:配置handler,自动扫描该包,使springmvc认为包下用了@controller注解的类是控制器 --> <!-- 批量加载:组件扫描方式: --> <context:component-scan base-package="com.zwp.controller" /> <!-- 视图解析器:解析jsp页面,默认使用jstl标签,classpath下得有jstl的包 --> <bean class="org.springframework.web.servlet.view.internalresourceviewresolver"> <!-- 配置前后缀 --> <property name="prefix" value="/web-inf/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 静态资源处理,不拦截静态资源,如css、js、imgs --> <mvc:resources location="/static/css/" mapping="/static/css/**"/> <mvc:resources location="/static/js/" mapping="/static/js/**"/> <mvc:resources location="/static/img/" mapping="/static/img/**"/> <!-- 文件上传相关配置 --> <bean id="multipartresolver" class="org.springframework.web.multipart.commons.commonsmultipartresolver"> <property name="defaultencoding" value="utf-8"></property> <property name="maxuploadsize" value="10240000"></property> </bean> </beans>
(3)编写handler:
//user类的handler //需要在类上面加@controller注解,这样才能被自动扫描到 @controller @requestmapping("/user") public class usercontroller { private static logger log=loggerfactory.getlogger(usercontroller.class); @requestmapping(value="/login",method=requestmethod.get) public string login(httpservletrequest request,model model){ string username = request.getparameter("username"); string password = request.getparameter("password"); system.out.println("username:"+username+";password:"+password); user user=null; if (username.equals("zwp") && password.equals("123456")) { user = new user(); user.setage(11); user.setid(1); user.setpassword("123456"); user.setusername("zwp"); log.debug(user.tostring()); } model.addattribute("user", user); return "index"; } }
//user实体类 public class user { private integer id; private string username; private string password; private integer age; public integer getid() { return id; } public void setid(integer id) { this.id = id; } public string getusername() { return username; } public void setusername(string username) { this.username = username; } public string getpassword() { return password; } public void setpassword(string password) { this.password = password; } public integer getage() { return age; } public void setage(integer age) { this.age = age; } @override public string tostring() { return "user [id=" + id + ", username=" + username + ", password=" + password + ", age=" + age + "]"; } }
(4)配置日志文件:
在项目根目录下面创建log4j.properties日志文件,下面是日志文件的基本配置,可以满足大多数项目的需求。
log4j.rootlogger=info,console,file #定义日志输出目的地为控制台 log4j.appender.console=org.apache.log4j.consoleappender log4j.appender.console.target=system.out #可以灵活地指定日志输出格式,下面一行是指定具体的格式 log4j.appender.console.layout = org.apache.log4j.patternlayout log4j.appender.console.layout.conversionpattern=[%c] - %m%n #文件大小到达指定尺寸的时候产生一个新的文件 log4j.appender.file = org.apache.log4j.rollingfileappender #指定输出目录 log4j.appender.file.file = logs/ssm.log #定义文件最大大小 log4j.appender.file.maxfilesize = 10mb # 输出所以日志,如果换成debug表示输出debug以上级别日志 log4j.appender.file.threshold = all log4j.appender.file.layout = org.apache.log4j.patternlayout log4j.appender.file.layout.conversionpattern =[%p] [%d{yyyy-mm-dd hh\:mm\:ss}][%c]%m%n
(5)启动项目,进行测试:
访问地址:http://localhost:8080/ssm/user/login?username=zwp&password=123456,如果出现下面页面则代表映射成功。
至此,springmvc的配置就已经成功。
3、spring和mybatis框架的整合:
整合思路:由spring通过单例方式管理sqlsessionfactory;spring和mybatis整合生成代理对象,使用sqlsessionfactory创建sqlsession,持久层的mapper都需要有spring进行管理。
(1)配置dao层,即配置sqlsessionfactory:(我的配置在applicationcontext-dao.xml文件中)
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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-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 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> <!-- 1.加载配置文件 --> <!-- 第一种加载多个.properties文件的方法 --> <context:property-placeholder location="classpath:resource/*.properties"/> <!-- 2.配置数据库连接池 --> <bean id="datasource" class="com.alibaba.druid.pool.druiddatasource" destroy-method="close"> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="driverclassname" value="${jdbc.driver}" /> <property name="maxactive" value="10" /> <property name="minidle" value="5" /> </bean> <!-- 3.让spring创建并管理sqlsessionfactory,使用mybatis和spring整合包中的 --> <bean id="sqlsessionfactory" class="org.mybatis.spring.sqlsessionfactorybean"> <!-- 配置数据源,数据库连接池 --> <property name="datasource" ref="datasource" /> <!-- 加载mybatis的全局配置文件 --> <property name="configlocation" value="classpath:mybatis/sqlmapconfig.xml" /> </bean> <!-- 4.mapper批量扫描:从mapper包中扫描出mapper,自动创建代理对象并且在spring容器中注册 需要遵循规范:mapper接口类名和mapper.xml映射文件名称一致,且在同一目录下, 自动扫描出来的mapper的bean的id为类名(首字母小写)--> <bean class="org.mybatis.spring.mapper.mapperscannerconfigurer"> <property name="basepackage" value="com.zwp.mapper" /> </bean> </beans>
创建并编写sqlmapconfig.xml文件:
<?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> <plugins> <!-- com.github.pagehelper为pagehelper类所在包名 --> <plugin interceptor="com.github.pagehelper.pagehelper"> <!-- 设置数据库类型 oracle,mysql,mariadb,sqlite,hsqldb,postgresql六种数据库 --> <property name="dialect" value="mysql" /> </plugin> </plugins> </configuration>
(2)配置service层:(我的配置在applicationcontext-service.xml文件中)
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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-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 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> <!-- 自动扫描service层的接口与实现类 --> <context:component-scan base-package="com.zwp.service" /> </beans>
(3)配置事务:(我的配置在applicationcontext-trans.xml文件中)
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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-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 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> <!-- 事务管理器 --> <bean id="transactionmanager" class="org.springframework.jdbc.datasource.datasourcetransactionmanager"> <!-- 数据源 --> <property name="datasource" ref="datasource" /> </bean> <!-- 通知 --> <tx:advice id="txadvice" transaction-manager="transactionmanager"> <tx:attributes> <!-- 传播行为 --> <tx:method name="add*" propagation="required" /> <tx:method name="create*" propagation="required" /> <tx:method name="insert*" propagation="required" /> <tx:method name="save*" propagation="required" /> <tx:method name="update*" propagation="required" /> <tx:method name="delete*" propagation="required" /> <tx:method name="find*" propagation="supports" read-only="true" /> <tx:method name="select*" propagation="supports" read-only="true" /> <tx:method name="get*" propagation="supports" read-only="true" /> </tx:attributes> </tx:advice> <!-- 切面 --> <aop:config> <aop:advisor advice-ref="txadvice" pointcut="execution(* com.zwp.service.*.*(..))" /> </aop:config> </beans>
至此,spring和mybatis框架的整合就完成了。
4、测试:
(1)创建测试用表:
(2)利用mybatis-generator自动创建实体类、mybatis映射文件以及dao接口。
(3)建立service和实现类:
//userservice接口类: @service public interface userservice { public user getuserbyid(int userid); }
//userservice的实现类 @service public class userserviceimpl implements userservice { //注入usermapper接口 @autowired private usermapper usermapper; @override public user getuserbyid(int userid) { user user = usermapper.selectbyprimarykey(userid); return user; } }
(3)建立usercontroller类:
//user类的handler //需要在类上面加@controller注解,这样才能被自动扫描到 @controller @requestmapping("/user") public class usercontroller { @autowired private userservice userservice; private static logger log=loggerfactory.getlogger(usercontroller.class); @requestmapping(value="/getuserbyid/{userid}",method=requestmethod.get) public @responsebody user getuserbyid(@pathvariable integer userid){ return userservice.getuserbyid(userid); } @requestmapping(value="/login",method=requestmethod.get) public string login(httpservletrequest request,model model){ string username = request.getparameter("username"); string password = request.getparameter("password"); system.out.println("username:"+username+";password:"+password); user user=null; if (username.equals("zwp") && password.equals("123456")) { user = new user(); user.setage(11); user.setid(1); user.setpassword("123456"); user.setusername("zwp"); log.debug(user.tostring()); } model.addattribute("user", user); return "index"; } }
(4)部署项目,输入地址:http://localhost:8080/ssm/user/getuserbyid/2,出现下面响应结果,则表示整合成功了。
至此,maven+spring+springmvc+mybatis的整合就完成了。
附:项目结构图:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。