本人在學習Maven之餘,爲了深刻了解Maven的用法,決定建立一個SSM整合實例。項目是本身實際搭建,真實可用。html
SSM(Spring+SpringMVC+Mybatis)前端
Spring是一種輕量級框架,這是衆所周知的,開發者只須要把一些經常使用的如日誌,事務管理在配置文件中申明,能大大下降代碼的耦合,減小代碼侵入。他的核心是 IOC(控制反轉)和AOP(面向切面編程),具體你們想了解深刻能夠上網查閱,這裏再也不多講。java
SpringMVC顧名思義就是運用Spring框架使用MVC思想實現,他的核心就是前端控制器(DispatcherServlet),它的工做原理是:mysql
一、客戶端發出一個http請求給web服務器,web服務器對http請求進行解析,若是匹配DispatcherServlet的請求映射路徑(在web.xml中指定),web容器將請求轉交給web
DispatcherServlet.spring
二、DipatcherServlet接收到這個請求以後將根據請求的信息(包括URL、Http方法、請求報文頭和請求參數Cookie等)以及HandlerMapping的配置找處處理請求的處理 器(Handler)。sql
3-四、DispatcherServlet根據HandlerMapping找到對應的Handler,將處理權交給Handler(Handler將具體的處理進行封裝),再由具體的HandlerAdapter對Handler進行 具體的調用。數據庫
五、Handler對數據處理完成之後將返回一個ModelAndView()對象給DispatcherServlet。express
六、Handler返回的ModelAndView()只是一個邏輯視圖並非一個正式的視圖,DispatcherSevlet經過ViewResolver將邏輯視圖轉化爲真正的視圖View。apache
七、Dispatcher經過model解析出ModelAndView()中的參數進行解析最終展示出完整的view並返回給客戶端。
Mybatis是支持定製化 SQL、存儲過程以及高級映射的優秀的持久層框架。MyBatis 避免了幾乎全部的 JDBC 代碼和手動設置參數以及獲取結果集。MyBatis 能夠對 配置和原生Map使用簡單的 XML 或註解,將接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java對象)映射成數據庫中的記錄。
這裏是MySQL數據庫,數據庫表建立以下圖:
CREATE TABLE tb_user( id int(11) NOT NULL AUTO_INCREMENT, user_name varchar(40) NOT NULL, password varchar(40) NOT NULL, age int(4) NOT NULL, PRIMARY KEY(id)) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
完整項目整合以下圖所示:
1.建立Maven的Web項目(這個在上一篇文章已經講解了,這裏就再也不多講)
2.配置pom.xml,代碼以下:
<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>cn.temp</groupId> <artifactId>maven-web-demo02</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>maven-web-demo02 Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <srping.version>4.0.2.RELEASE</srping.version> <mybatis.version>3.2.8</mybatis.version> <slf4j.version>1.7.12</slf4j.version> <log4j.version>1.2.17</log4j.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!-- java ee包 --> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> <scope>provided</scope> </dependency> <!-- spring框架包 start --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${srping.version}</version> </dependency> <!-- spring框架包 end --> <!-- mybatis框架包 start --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!-- mybatis框架包 end --> <!-- 數據庫驅動 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> </dependency> <!-- 導入dbcp的jar包,用來在applicationContext.xml中配置數據庫 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <!-- jstl標籤類 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log END --> <!-- Json --> <!-- 格式化對象,方便輸出日誌 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.6</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <!-- 上傳組件包 start --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.10</version> </dependency> <!-- 上傳組件包 end --> </dependencies> <build> <finalName>maven-web-demo02</finalName> </build> </project>
3.建立jdbc.properties文件
driver=com.mysql.jdbc.Driver url=jdbc:mysql://127.0.0.1:3306/orcl username=root password=123qweasd initialSize=0 maxActive=20 maxIdle=20 minIdle=1 maxWait=60000
4.建立日誌屬性文件
#\u5B9A\u4E49LOG\u8F93\u51FA\u7EA7\u522B log4j.rootLogger=INFO,Console,File #\u5B9A\u4E49\u65E5\u5FD7\u8F93\u51FA\u76EE\u7684\u5730\u4E3A\u63A7\u5236\u53F0 log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.Target=System.out #\u53EF\u4EE5\u7075\u6D3B\u5730\u6307\u5B9A\u65E5\u5FD7\u8F93\u51FA\u683C\u5F0F\uFF0C\u4E0B\u9762\u4E00\u884C\u662F\u6307\u5B9A\u5177\u4F53\u7684\u683C\u5F0F log4j.appender.Console.layout = org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n #\u6587\u4EF6\u5927\u5C0F\u5230\u8FBE\u6307\u5B9A\u5C3A\u5BF8\u7684\u65F6\u5019\u4EA7\u751F\u4E00\u4E2A\u65B0\u7684\u6587\u4EF6 log4j.appender.File = org.apache.log4j.RollingFileAppender #\u6307\u5B9A\u8F93\u51FA\u76EE\u5F55 log4j.appender.File.File = logs/ssm.log #\u5B9A\u4E49\u6587\u4EF6\u6700\u5927\u5927\u5C0F log4j.appender.File.MaxFileSize = 10MB # \u8F93\u51FA\u6240\u4EE5\u65E5\u5FD7\uFF0C\u5982\u679C\u6362\u6210DEBUG\u8868\u793A\u8F93\u51FADEBUG\u4EE5\u4E0A\u7EA7\u522B\u65E5\u5FD7 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.接下來建立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" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> <!-- 自動掃描 --> <context:component-scan base-package="com.sgcc.user" > <!-- 不掃描@Controller註解的類--> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 引入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties" /> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> <!-- 初始化鏈接大小 --> <property name="initialSize" value="${initialSize}"></property> <!-- 鏈接池最大數量 --> <property name="maxActive" value="${maxActive}"></property> <!-- 鏈接池最大空閒 --> <property name="maxIdle" value="${maxIdle}"></property> <!-- 鏈接池最小空閒 --> <property name="minIdle" value="${minIdle}"></property> <!-- 獲取鏈接最大等待時間 --> <property name="maxWait" value="${maxWait}"></property> </bean> <!-- spring和MyBatis整合,不須要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自動掃描mapping.xml文件 --> <property name="mapperLocations" value="classpath:com/sgcc/user/mapping/*.xml"></property> </bean> <!-- DAO接口所在包名,Spring會自動查找其下的類 動態代理實現 不用寫dao的實現類--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.sgcc.user.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
6.建立SpringMVC文件,以下代碼
<?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-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 自動掃描該包 @controller註解的類--> <context:component-scan base-package="com.sgcc.user.controller"/> <!-- 靜態資源處理 --> <mvc:default-servlet-handler/> <!--自動註冊 RequestMappingHandlerMapping、RequestMappingHandlerAdapter 等bean --> <mvc:annotation-driven></mvc:annotation-driven> <!-- 定義跳轉的文件的先後綴 ,視圖模式配置--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
7.接下來就是各個業務文件了,以下圖所示:
8.建立UserController文件,以下圖所示:
package com.sgcc.user.controller;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.sgcc.user.pojo.User;
import com.sgcc.user.service.UserService;
@Controller
public class UserController {
/**
* 使用@Autowired也能夠,@Autowired默認按類型裝配
* @Resource 默認按名稱裝配,當找不到與名稱匹配的bean纔會按類型裝配。
*/
@Resource
private UserService userService;
/**
* 測試查詢
*
* @param id
* @param model
* @return
*/
@RequestMapping("/showUser")
public String testtoshowUser(@RequestParam(value = "id") Integer id, Model model) {
System.out.println("id:" + id);
User user = userService.getUserById(id);
model.addAttribute("user", user);
return "showUser";
}
/**
* 測試添加數據
*
* @param id
* @param model
* @return
*/
@RequestMapping("/insertUser")
public String testinsertUser() {
User user = new User();
user.setUserName("李清照");
user.setPassword("3232322");
user.setAge(22);
int count = userService.insert(user);
System.out.println("插入" + count + "條數據成功");
return "showUser";
}
}
9.建立UserDao
package com.sgcc.user.dao; import com.sgcc.user.pojo.User; public interface UserDao { int deleteByPrimaryKey(Integer id); int insert(User record); int insertSelective(User record); User selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); }
10.建立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" > <!-- namespace的值就是dao接口的完整路徑,就這個demo而言namespace 就是userDao.java的完整路徑--> <mapper namespace="com.sgcc.user.dao.UserDao"> <resultMap id="BaseResultMap" type="com.sgcc.user.pojo.User"> <id column="id" property="id" jdbcType="INTEGER" /> <result column="user_name" property="userName" jdbcType="VARCHAR" /> <result column="password" property="password" jdbcType="VARCHAR" /> <result column="age" property="age" jdbcType="INTEGER" /> </resultMap> <sql id="Base_Column_List"> id, user_name, password, age </sql> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer"> select <include refid="Base_Column_List" /> from tb_user where id = #{id,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> delete from tb_user where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="com.sgcc.user.pojo.User"> insert into tb_user (id, user_name, password, age) values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}) </insert> <insert id="insertSelective" parameterType="com.sgcc.user.pojo.User"> insert into tb_user <trim prefix="(" suffix=")" suffixOverrides=","> <if test="id != null"> id, </if> <if test="userName != null"> user_name, </if> <if test="password != null"> password, </if> <if test="age != null"> age, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="id != null"> #{id,jdbcType=INTEGER}, </if> <if test="userName != null"> #{userName,jdbcType=VARCHAR}, </if> <if test="password != null"> #{password,jdbcType=VARCHAR}, </if> <if test="age != null"> #{age,jdbcType=INTEGER}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.sgcc.user.pojo.User"> update tb_user <set> <if test="userName != null"> user_name = #{userName,jdbcType=VARCHAR}, </if> <if test="password != null"> password = #{password,jdbcType=VARCHAR}, </if> <if test="age != null"> age = #{age,jdbcType=INTEGER}, </if> </set> where id = #{id,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.sgcc.user.pojo.User"> update tb_user set user_name = #{userName,jdbcType=VARCHAR}, password = #{password,jdbcType=VARCHAR}, age = #{age,jdbcType=INTEGER} where id = #{id,jdbcType=INTEGER} </update> </mapper>
12.建立User類
package com.sgcc.user.pojo; 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 == null ? null : userName.trim(); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password == null ? null : password.trim(); } 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 + "]"; } }
13.建立UserService接口
package com.sgcc.user.service; import com.sgcc.user.pojo.User; public interface UserService { //根據id查找 public User getUserById(Integer userid); //添加一條數據 public int insert(User user); }
14.建立UserServiceImpl實現類
package com.sgcc.user.service; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.sgcc.user.dao.UserDao; import com.sgcc.user.pojo.User; @Transactional @Service("userService") public class UserServiceImpl implements UserService { /** * 由於沒有在spring的文件中顯式的聲明userService實現類,直接經過getBean獲得 userService 會找不到 * 須要顯式配置 @Service ("userService"),指定bean的名稱 * 至關與<bean id="userService" class="com.jxust.ssm.service.impl.UserServiceImpl"></bean> */ @Resource private UserDao userDao; public User getUserById(Integer userid) { return this.userDao.selectByPrimaryKey(userid); } @Override public int insert(User user) { return this.userDao.insert(user); } }
16.配置程序入口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" 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"> <display-name>maven-web-demo02</display-name> <!-- 編碼過濾器 --> <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> <!-- Spring監聽器 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mybatis.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--Spring MVC 配置servlet --> <servlet> <servlet-name>springDispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
18.建立前端頁面,index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <a href="showUser?id=2">ShowUser page</a><br> <a href="insertUser">insertUser </a> </body> </html>
19.建立showUser.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>測試</title> </head> <body> id:${user.id} <br> userName: ${user.userName} <br> password: ${user.password} <br> age: ${user.age} <br> </body> </html>
20啓動服務,以下圖所示: