今天開始就作一個我的博客實戰項目了,首先就項目環境的搭建,萬丈高樓平地起。這篇 博客主要講解基於maven的ssm項目整合。
整合步驟css
第一步:html
MyBatis和Spring整合,經過Spring管理mapper接口。java
使用mapper的掃描器自動掃描mapper接口在Spring中進行註冊。mysql
第二步:web
經過Spring管理Service接口。spring
使用配置方式將Service接口配置在Spring配置文件中。sql
實現事務控制。數據庫
第三步:apache
因爲SpringMVC是Spring的模塊,無需整合這兩個。編程
項目架構:
下面講解部分包/文件做用
mapper:存放mybatis的mapper文件夾
log4j.properties:log4j日誌屬性文件
mybatis-conf.xml:mybatis全局配置文件
spring-bean.xml:spring與mybatis整合配置文件
spring-mvc.xml:spring mvc配置文件
下面就開始咱們的項目整合吧
maven是一個優秀的項目對象管理器工具 我能夠經過在pom.xml中添加須要的jar包的依賴就能夠導入對應的jar包了,很是的方便。
下面就列出整合ssm所對應的依賴
<!-- 添加sevlet支持 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <!-- 添加jsp支持 --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> </dependency> <!-- 添加jstl支持 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <!-- 添加spring支持 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.3.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.3.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>4.3.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.3.0.RELEASE</version> </dependency> <!--spring test支持--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.0.RELEASE</version> </dependency> <!--spring mvc支持--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.0.RELEASE</version> </dependency> <!--spring 事務管理支持--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.3.0.RELEASE</version> </dependency> <!--spring jdbc操做支持--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.0.RELEASE</version> </dependency> <!--spring aop編程支持--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>4.3.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>4.3.0.RELEASE</version> </dependency> <!-- 添加mybatis支持 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.0</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <!-- jdbc驅動包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.30</version> </dependency> <!-- 添加阿里巴巴鏈接池Druid支持 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.16</version> </dependency> <!-- 添加log4j日誌 --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.21</version> </dependency> <!-- apache共公包 --> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <!-- 添加junit支持 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency>
這個文件主要配置mybatis全局配置文件
例如 別名 駝峯命名自動轉換等 在這裏我暫時只配置別名
<?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> <!-- 別名 --> <typeAliases> <package name="ssm.blog.entity"/> </typeAliases> </configuration>
整合主要步驟
開啓mybatis dao接口掃描
具體配置註解講的很清楚
<?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: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/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 開啓包掃描--> <context:component-scan base-package="ssm.blog"/> <!-- 配置druid數據源 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="username" value="root"/> <property name="password" value="root"/> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/db_blog"/> </bean> <!-- 配置mybatis的sqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 自動掃描mapper.xml文件--> <property name="mapperLocations" value="classpath:mapper/*.xml"/> <!-- 載入mybatis全局配置文件--> <property name="configLocation" value="classpath:mybatis-conf.xml"/> </bean> <!-- 配置mybatis dao接口掃描--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="ssm.blog.dao"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> </beans> <!-- 配置spring的聲明式事務,名字爲默認值 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 開啓事務控制的註解支持 --> <tx:annotation-driven transaction-manager="transactionManager"/>、、
如今mybatis與spring整合已經算完成了 接下來咱們測試一下
一、表結構
sql 文件
DROP DATABASE IF EXISTS db_blog; /*建立數據庫,並設置編碼*/ CREATE DATABASE db_blog DEFAULT CHARACTER SET utf8; USE db_blog; CREATE TABLE `t_blogger` ( `id` INT(11) NOT NULL AUTO_INCREMENT COMMENT '博主id', `username` VARCHAR(50) NOT NULL COMMENT '博主姓名', `password` VARCHAR(100) NOT NULL COMMENT '博主密碼', `profile` TEXT COMMENT '博主信息', `nickname` VARCHAR(50) DEFAULT NULL COMMENT '博主暱稱', `sign` VARCHAR(100) DEFAULT NULL COMMENT '博主簽名', `imagename` VARCHAR(100) DEFAULT NULL COMMENT '博主頭像路徑', PRIMARY KEY (`id`) ) ENGINE=INNODB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
二、實體類
package ssm.blog.entity; import org.springframework.stereotype.Component; import java.io.Serializable; /** * Created by xp on 2017/4/13. * @author xp * @Description 博主信息實體類 */ @Component //註冊bean 爲spring容器管理 public class Blogger implements Serializable { private Integer id; private String userName; //用戶名 private String password; //密碼 private String profile; //博主信息 private String nickName; //暱稱 private String sign; //博主簽名 private String imageName; //圖片路徑 public Blogger(String userName, String password, String profile, String nickName, String sign, String imageName) { this.userName = userName; this.password = password; this.profile = profile; this.nickName = nickName; this.sign = sign; this.imageName = imageName; } public Blogger() { } 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 String getProfile() { return profile; } public void setProfile(String profile) { this.profile = profile; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } public String getImageName() { return imageName; } public void setImageName(String imageName) { this.imageName = imageName; } @Override public String toString() { return "Blogger{" + "id=" + id + ", userName='" + userName + '\'' + ", password='" + password + '\'' + ", profile='" + profile + '\'' + ", nickName='" + nickName + '\'' + ", sign='" + sign + '\'' + ", imageName='" + imageName + '\'' + '}'; } }
三、dao接口以及mapper文件
dao接口
package ssm.blog.dao; import org.springframework.stereotype.Repository; import ssm.blog.entity.Blogger; /** * Created by xp on 2017/4/13. * 博主dao接口 */ @Repository //註冊爲持久層的bean public interface BloggerDao { /** * 查詢博主信息 * @return */ Blogger getBloggerData(); }
mapper
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="ssm.blog.dao.BloggerDao"> <!-- 返回結果映射 若是開啓駝峯命名轉換且命名規範該段代碼能夠不寫 由於配置別名 因此type屬性使用的是mybatis-conf中的別名 --> <resultMap type="Blogger" id="BloggerResult"> <id property="id" column="id"/> <result property="userName" column="username"/> <result property="password" column="password"/> <result property="profile" column="profile"/> <result property="nickName" column="nickname"/> <result property="sign" column="sign"/> <result property="imageName" column="imagename"/> </resultMap> <!-- 定義字段集合 --> <sql id="BloggerColumns"> id,username,password,profile,nickname,sign,imagename </sql> <!-- 接口中getBloggerData 具體實現--> <select id="getBloggerData" resultMap="BloggerResult"> select <include refid="BloggerColumns"/> from t_blogger where id = 1 </select> </mapper>
四、log4j.properties 文件
建立log4j.properties 打印日誌 查看執行sql語句
log4j.rootLogger=DEBUG, Console #Console log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.layout=org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n log4j.logger.java.sql.ResultSet=INFO log4j.logger.org.apache=INFO log4j.logger.java.sql.Connection=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG
五、建立測試類並測試
BloggerDaoTest
package ssm.blog.dao; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import ssm.blog.entity.Blogger; import javax.annotation.Resource; import static org.junit.Assert.*; /** * Created by xp on 2017/4/13. */ @RunWith(SpringJUnit4ClassRunner.class) //使用spring測試 @ContextConfiguration(locations = "classpath:spring-beans.xml") //設置spring配置文件路徑 public class BloggerDaoTest { @Resource //注入BloggerDao對象 private BloggerDao bloggerDao; @Test public void getBloggerData() throws Exception { Blogger blogger = bloggerDao.getBloggerData(); System.out.println(blogger); } }
打印結果
成功打印結果 說明spring與mybatis整合成功。
<?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: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/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 掃描全部ssm.blog.controller包下面的全部controller --> <context:component-scan base-package="ssm.blog.controller"/> <!-- 開啓註解配置--> <mvc:annotation-driven/> <!-- 靜態資源解析,包括js,css,img... --> <mvc:resources location="/static/" mapping="/static/**"/> <!-- 配置視圖解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--視圖前綴--> <property name="prefix" value="/"/> <!--視圖後綴--> <property name="suffix" value=".jsp"/> </bean> </beans>
註釋講的很清楚 我就再也不講了
<?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_3_0.xsd" id="WebApp_ID" version="3.0"> <!--spring配置文件路徑--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-beans.xml</param-value> </context-param> <!-- 配置spring監聽器--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--spring mvc核心servlet--> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 初始化參數配置 springnvc配置文件路徑--> <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>dispatcherServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> <!-- 編碼過濾器 --> <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> </web-app>
新建BloggerController
package ssm.blog.controller; import jdk.internal.org.objectweb.asm.tree.analysis.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; /** * Created by xp on 2017/4/13. * 博主控制器 */ @Controller //註冊爲控制器bean @RequestMapping(value = "/blog") //請求路徑 public class BloggerController { @ResponseBody //返回json數據 @RequestMapping(value="/hello") public String hello(){ return "hello"; } }
發佈項目到tomcat
打開瀏覽器輸入:http://localhost:8080/blog/hello
結果:
至此咱們ssm三大框架已經整合完畢,接下來就是我的博客實戰開發了