所需基本jar包分類
1.spring相關:core、bean、context、expression、commons-logging
2.web相關:web、webMVC
3.切面及異常:aop、tx
4.mysql相關:druid、mysql-connector
5.mybatis相關:mybatis、mybatis-spring
6.servlet相關:servlet-api
7.文件相關:fileupload、commons-io
8.log4j相關:log4j、common-logging
9.json相關:jackson-core、databind
10.swagger:swagger-springmvc
11.redis:jredis、spring-data-redis
以下是整合ssm框架的最小系統,各位在根據本身的需求配置各自的功能。
###整合ssm框架前置條件
1.下載安裝jdk
2.下載安裝maven
3.下載Tomcat
4.下載STS(eclipse)
備註:如上安裝配置自行百度,也能夠查閱我以前的博客。
###整合ssm框架步驟
####1.新建一個maven工程,工程目錄以下
####2.在src/main/java文件下建立分層包
分層指的是mvc,controller負責處理請求;service負責業務層;serviceImpl負責與數據庫鏈接;mapper存放的是mybatis的xx.mapper和xx.xml文件;bean下存放實體類。
####3.在src/main/resources文件下建立配置文件
db.properties指的是數據庫配置信息;log4j.properties指的是打印輸出信息;spring-config指的是spring的配置信息;spring-mvc指的是mvc的配置信息;spring-mybatis指的是mybatis的配置信息。
####4.在pom.xml文件添加所需jar包java
<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.test</groupId> <artifactId>ssm</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>ssm Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>4.2.0.RELEASE</spring.version> <jackson-core.version>2.6.1</jackson-core.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <!-- spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</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-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.6</version> </dependency> <!-- alibaba --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.15</version> </dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.36</version> </dependency> <!-- slf4j --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.10</version> </dependency> <!-- mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.3</version> </dependency> </dependencies> <build> <finalName>ssm</finalName> <defaultGoal>compile</defaultGoal> </build> </project>
備註:若是網速較慢的話,這個過程可能會有點長,能夠一個個的下載,或者是配置maven的鏡像站(筆者在家裏的網速特慢,沒有配置成功過;筆者在公司的網速還不錯,下載jar包均在5s之內。其實不須要配置鏡像站,maven自己下載的速度已經很快了),下載完成後,maven jar包列表以下,顯示是按照pom.xml配置的順序顯示的
####5.db.properties配置信息mysql
driverClassName=com.mysql.jdbc.Driver jdbc_url=jdbc:mysql://192.168.2.11:3306/test?useUnicode=true&characterEncoding=UTF-8 jdbc_username=root jdbc_password=123456
####6.log4j.properties配置信息web
log4j.rootLogger=DEBUG, stdout, D, E #log4j.logger.test=info #log4j.logger.org.apache.jasper = DEBUG #log4j.logger.org.apache.catalina.startup.TldConfig = DEBUG #log4j.logger.org.apache.catalina.session.ManagerBase = DEBUG log4j.logger.com.readygo.app.mapper=DEBUG log4j.logger.java.sql.Connection = DEBUG log4j.logger.java.sql.Statement = DEBUG log4j.logger.java.sql.PreparedStatement = DEBUG log4j.logger.java.sql.ResultSet = DEBUG 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} [ %t:%r ] - [ %p ] %m%n log4j.appender.D = org.apache.log4j.DailyRollingFileAppender log4j.appender.D.File = ${app.root}/WEB-INF/logs/debug.log log4j.appender.D.DatePattern = "."yyyy-MM log4j.appender.D.Append = true log4j.appender.D.Threshold = DEBUG log4j.appender.D.layout = org.apache.log4j.PatternLayout log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n log4j.appender.E = org.apache.log4j.DailyRollingFileAppender log4j.appender.E.File = ${app.root}/WEB-INF/logs/error.log log4j.appender.E.Append = true log4j.appender.E.DatePattern = "."yyyy-MM log4j.appender.E.Threshold = ERROR log4j.appender.E.layout = org.apache.log4j.PatternLayout log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
####7.spring配置文件,很簡潔吧redis
<?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"> <!-- 導入springMVC 與 springMybatis --> <import resource="spring-mvc.xml"/> <import resource="spring-mybatis.xml"/> </beans>
####8.springMVC配置信息,也很簡潔吧spring
<?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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd 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-4.2.xsd"> <!-- 掃描包 --> <context:component-scan base-package="com.test.spring"></context:component-scan> </beans>
####9.springMybatis配置信息sql
<?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: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-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd"> <!-- 讀取配置文件 --> <context:property-placeholder location="classpath:db.properties"/> <!-- 配置數據源 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName" value="${driverClassName}"></property> <property name="url" value="${jdbc_url}"></property> <property name="username" value="${jdbc_username}"></property> <property name="password" value="${jdbc_password}"></property> </bean> <!-- spring整合mybatis --> <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="mapperLocations" value="classpath:com/test/spring/mapper/*.xml" /> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.test.spring.mapper" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean" /> </bean> <!-- 配置事務管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 使事務註解生效 --> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
####10.建立數據庫和表
不須要鏈接數據庫的,這一步能夠省略。這裏須要安裝mysql數據庫、按照數據庫客戶端,我裝的是navicat。我建的數據庫、表以下,簡單點,就只建立了一個T_user表,字段如右邊查詢信息
####11.工程運行起來
這個時候是一個空的工程,可是能夠運行起來了哈。若是各位的運行起來報錯的話,請查找相關緣由。這一步經過了,才能開始業務部分。
####12.建立controller
在文件src/main/java下面的com.test.spring.controller下建立UserController類數據庫
package com.test.spring.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.test.spring.service.UserService; @RestController public class UserController { @Autowired private UserService userService; @RequestMapping(value="/userList",method= RequestMethod.GET) public void getUserList() { userService.getUserList(); } }
####13.建立UserServiceexpress
package com.test.spring.service; public interface UserService { public void getUserList(); }
####14.建立UserServiceImplapache
package com.test.spring.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.test.spring.bean.User; import com.test.spring.mapper.UserMapper; import com.test.spring.service.UserService; @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public void getUserList() { List<User> listUser = userMapper.getUserList(); System.out.println(listUser); } }
####15.建立UserMapper.java、UserMapper.xml與User(它是bean)
建立這些,能夠使用mybatis的自動建立代碼工具,請參考個人博客,有很詳細的介紹。
UserMapper.java以下json
package com.test.spring.mapper; import java.util.List; import com.test.spring.bean.User; public interface UserMapper { int deleteByPrimaryKey(Integer id); int insert(User record); int insertSelective(User record); User selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); List<User> getUserList(); }
UserMapper.xml以下
<?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="com.test.spring.mapper.UserMapper" > <resultMap id="BaseResultMap" type="com.test.spring.bean.User" > <id column="id" property="id" jdbcType="INTEGER" /> <result column="name" property="name" jdbcType="VARCHAR" /> </resultMap> <sql id="Base_Column_List" > id, name </sql> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" > select <include refid="Base_Column_List" /> from t_user where id = #{id,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" > delete from t_user where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="com.test.spring.bean.User" > insert into t_user (id, name) values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}) </insert> <insert id="insertSelective" parameterType="com.test.spring.bean.User" > insert into t_user <trim prefix="(" suffix=")" suffixOverrides="," > <if test="id != null" > id, </if> <if test="name != null" > name, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides="," > <if test="id != null" > #{id,jdbcType=INTEGER}, </if> <if test="name != null" > #{name,jdbcType=VARCHAR}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.test.spring.bean.User" > update t_user <set > <if test="name != null" > name = #{name,jdbcType=VARCHAR}, </if> </set> where id = #{id,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.test.spring.bean.User" > update t_user set name = #{name,jdbcType=VARCHAR} where id = #{id,jdbcType=INTEGER} </update> <select id="getUserList" resultType="com.test.spring.bean.User"> SELECT tu.id AS id, tu.`name` AS `name` FROM t_user tu </select> </mapper>
User類
public class User { private Integer id; private String name; }
####16.web.xml配置
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <!-- 編碼過濾器 --> <filter> <filter-name>encodingFilter</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>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 工程映射 --> <servlet> <servlet-name>ssm</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>ssm</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> <!-- log4j start --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>10000</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <!-- log4h end --> </web-app>
####17.測試
2016-09-06 14:24:15 [ http-nio-8080-exec-2:25440 ] - [ DEBUG ] Creating a new SqlSession 2016-09-06 14:24:15 [ http-nio-8080-exec-2:25453 ] - [ DEBUG ] SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@50093e1a] was not registered for synchronization because synchronization is not active 2016-09-06 14:24:15 [ http-nio-8080-exec-2:25480 ] - [ DEBUG ] Fetching JDBC Connection from DataSource 2016-09-06 14:24:15 [ http-nio-8080-exec-2:25905 ] - [ DEBUG ] JDBC Connection [com.mysql.jdbc.JDBC4Connection@7fd00c6e] will not be managed by Spring 2016-09-06 14:24:15 [ http-nio-8080-exec-2:25926 ] - [ DEBUG ] ==> Preparing: SELECT tu.id AS id, tu.`name` AS `name` FROM t_user tu 2016-09-06 14:24:15 [ http-nio-8080-exec-2:26001 ] - [ DEBUG ] ==> Parameters: 2016-09-06 14:24:15 [ http-nio-8080-exec-2:26052 ] - [ DEBUG ] <== Total: 3 2016-09-06 14:24:15 [ http-nio-8080-exec-2:26053 ] - [ DEBUG ] Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@50093e1a] 2016-09-06 14:24:15 [ http-nio-8080-exec-2:26053 ] - [ DEBUG ] Returning JDBC Connection to DataSource [User [id=1000, name=張三], User [id=1001, name=李四], User [id=1002, name=王五]]
備註: 1.[User [id=1000, name=張三], User [id=1001, name=李四], User [id=1002, name=王五]] 這行纔是代碼中 System.out.println(listUser) 打印結果,之因此截出這麼多信息,是讓閱者從源頭理解。 2.截圖中信息從 查詢數據庫(即建立SqlSession)開始、創建數據庫鏈接、查詢數據(打印出SQL)、打印返回結果、關閉數據庫鏈接。