您好,登錄后才能下訂單哦!
(項(xiàng)目結(jié)構(gòu)圖參照文章末尾)
1、創(chuàng)建maven工程,在pom.xml文件中導(dǎo)入需要的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> <!-- 集中定義版本號(hào) --> <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> <!-- 因?yàn)楣俜降牟恢С謒ybatis逆向工程,在源碼上有修改,需要自己手動(dòng)編譯 --> <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> <!-- 時(shí)間操作組件 --> <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> <!-- 單元測(cè)試 --> <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> <!-- 分頁(yè)插件 --> <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相關(guān) --> <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相關(guān)配置文件 --> <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)編寫(xiě)springmvc.xml文件:
在文件中配置與springmvc框架相關(guān)的配置,比如: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"> <!-- 使用注解驅(qū)動(dòng):自動(dòng)配置處理器映射器與處理器適配器 --> <mvc:annotation-driven /> <!-- 注解方式:配置Handler,自動(dòng)掃描該包,使SpringMVC認(rèn)為包下用了@controller注解的類是控制器 --> <!-- 批量加載:組件掃描方式: --> <context:component-scan base-package="com.zwp.controller" /> <!-- 視圖解析器:解析jsp頁(yè)面,默認(rèn)使用jstl標(biāo)簽,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> <!-- 靜態(tài)資源處理,不攔截靜態(tài)資源,如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/**"/> <!-- 文件上傳相關(guān)配置 --> <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)編寫(xiě)Handler:
//User類的Handler //需要在類上面加@Controller注解,這樣才能被自動(dòng)掃描到 @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實(shí)體類 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)配置日志文件:
在項(xiàng)目根目錄下面創(chuàng)建log4j.properties日志文件,下面是日志文件的基本配置,可以滿足大多數(shù)項(xiàng)目的需求。
log4j.rootLogger=INFO,Console,File #定義日志輸出目的地為控制臺(tái) 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 #文件大小到達(dá)指定尺寸的時(shí)候產(chǎn)生一個(gè)新的文件 log4j.appender.File = org.apache.log4j.RollingFileAppender #指定輸出目錄 log4j.appender.File.File = logs/ssm.log #定義文件最大大小 log4j.appender.File.MaxFileSize = 10MB # 輸出所以日志,如果換成DEBUG表示輸出DEBUG以上級(jí)別日志 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)啟動(dòng)項(xiàng)目,進(jìn)行測(cè)試:
訪問(wèn)地址:http://localhost:8080/ssm/user/login?username=zwp&password=123456,如果出現(xiàn)下面頁(yè)面則代表映射成功。
至此,SpringMVC的配置就已經(jīng)成功。
3、Spring和Mybatis框架的整合:
整合思路:由Spring通過(guò)單例方式管理SqlSessionFactory;spring和mybatis整合生成代理對(duì)象,使用SqlSessionFactory創(chuàng)建SqlSession,持久層的mapper都需要有spring進(jìn)行管理。
(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.加載配置文件 --> <!-- 第一種加載多個(gè).properties文件的方法 --> <context:property-placeholder location="classpath:resource/*.properties"/> <!-- 2.配置數(shù)據(jù)庫(kù)連接池 --> <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創(chuàng)建并管理sqlsessionfactory,使用mybatis和spring整合包中的 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 配置數(shù)據(jù)源,數(shù)據(jù)庫(kù)連接池 --> <property name="dataSource" ref="dataSource" /> <!-- 加載mybatis的全局配置文件 --> <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" /> </bean> <!-- 4.mapper批量掃描:從mapper包中掃描出mapper,自動(dòng)創(chuàng)建代理對(duì)象并且在spring容器中注冊(cè) 需要遵循規(guī)范:mapper接口類名和mapper.xml映射文件名稱一致,且在同一目錄下, 自動(dòng)掃描出來(lái)的mapper的bean的id為類名(首字母小寫(xiě))--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.zwp.mapper" /> </bean> </beans>
創(chuàng)建并編寫(xiě)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"> <!-- 設(shè)置數(shù)據(jù)庫(kù)類型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六種數(shù)據(jù)庫(kù) --> <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"> <!-- 自動(dòng)掃描service層的接口與實(shí)現(xiàn)類 --> <context:component-scan base-package="com.zwp.service" /> </beans>
(3)配置事務(wù):(我的配置在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"> <!-- 事務(wù)管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 數(shù)據(jù)源 --> <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、測(cè)試:
(1)創(chuàng)建測(cè)試用表:
(2)利用MyBatis-Generator自動(dòng)創(chuàng)建實(shí)體類、Mybatis映射文件以及Dao接口。
(3)建立Service和實(shí)現(xiàn)類:
//UserService接口類: @Service public interface UserService { public User getUserById(int userId); }
//UserService的實(shí)現(xiàn)類 @Service public class UserServiceImpl implements UserService { //注入U(xiǎn)serMapper接口 @Autowired private UserMapper userMapper; @Override public User getUserById(int userId) { User user = userMapper.selectByPrimaryKey(userId); return user; } }
(3)建立UserController類:
//User類的Handler //需要在類上面加@Controller注解,這樣才能被自動(dòng)掃描到 @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)部署項(xiàng)目,輸入地址:http://localhost:8080/ssm/user/getUserById/2,出現(xiàn)下面響應(yīng)結(jié)果,則表示整合成功了。
至此,Maven+Spring+SpringMVC+Mybatis的整合就完成了。
附:項(xiàng)目結(jié)構(gòu)圖:
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。