使用maven整合SSM框架详细步骤
(文章所使用框架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.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsdhttp://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;}@Overridepublic 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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsdhttp://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.xsdhttp://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 configurationPUBLIC "-//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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsdhttp://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.xsdhttp://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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsdhttp://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.xsdhttp://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接口@Autowiredprivate UserMapper userMapper;@Overridepublic User getUserById(int userId) {User user = userMapper.selectByPrimaryKey(userId);return user;} }(3)建立UserController類:
//User類的Handler //需要在類上面加@Controller注解,這樣才能被自動掃描到 @Controller @RequestMapping("/user") public class UserController {@Autowiredprivate 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的整合就完成了。
附:項目結構圖:
?
?
總結
以上是生活随笔為你收集整理的使用maven整合SSM框架详细步骤的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SpringMVC框架--学习笔记(下)
- 下一篇: springmvc整合swagger 与