1. 程式人生 > >(實用篇)一步步搭建Spring+SpringMVC+MyBatis(SSM)框架

(實用篇)一步步搭建Spring+SpringMVC+MyBatis(SSM)框架

一、前言

本篇內容是培訓作業的第一個任務,旨在搭建一個SSM框架,做一個HTML頁面,能查詢,能插入資料(新建使用者)、登陸。實現的功能最為基礎,但是要求所有程式碼均為手寫,不能使用Mybatis 自動生成mapping和dao。由於此框架是後面一系列任務的基礎,所以,還是有必要完整的記錄下所有的細節過程,一方面希望幫助有需要的同學,另一方面也做一個階段性的總結與回顧。

二、環境相關介紹

2.1 環境介紹

環境:jdk1.8 + Spring(4.3.10) + Mybatis(3.2.7) + apache-tomcat(8.0.52) + MySQL(5.1.21) + Oracle(11.2.0.3)

2.2 專案程式碼說明

此專案程式碼已經上傳到,由於後續任務的推進也會不定時更新。

三、搭建SSM框架

3.1 建立maven專案

3.2 完整專案結構

完整的專案結構如上圖所示,包括基本的框架部分、配置檔案部分、測試部分、前端部分等內容。

3.3 引入maven 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/maven-v4_0_0.xsd">
	  <modelVersion>4.0.0</modelVersion>
	  <groupId>com.lixj.work</groupId>
	  <artifactId>task_one</artifactId>
	  <version>0.0.1-SNAPSHOT</version>
	  <packaging>war</packaging>
	  
	<properties>  
        <!-- spring版本號 -->  
        <spring.version>4.3.10.RELEASE</spring.version>  
        <!-- mybatis版本號 -->  
        <mybatis.version>3.2.7</mybatis.version>  
        <!-- log4j日誌檔案管理包版本 -->  
        <slf4j.version>1.7.7</slf4j.version>  
        <log4j.version>1.2.17</log4j.version>  
    </properties> 
	
	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</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-core</artifactId>
			<version>${spring.version}</version> 
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>${mybatis.version}</version> 
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.1.1</version>
		</dependency>
		
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.21</version>
		</dependency>
		
		<dependency>
		  <groupId>com.oracle</groupId>
		  <artifactId>ojdbc6</artifactId>
		  <version>11.2.0.3</version>
		</dependency>
		
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>net.sf.json-lib</groupId>
			<artifactId>json-lib</artifactId>
			<version>2.4</version>
			<classifier>jdk15</classifier>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>0.2.9</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.7.1</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>1.9.11</version>
		</dependency>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.2.2</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.0.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.2</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.1.26</version>
		</dependency>

		<dependency> 
			<groupId> org.aspectj</groupId > 
			<artifactId> aspectjweaver</artifactId > 
			<version> 1.8.7</version > 
		</dependency> 

	    <dependency>
	            <groupId>jdk.tools</groupId>
	            <artifactId>jdk.tools</artifactId>
	            <version>1.8</version>
	    </dependency>
	    
	    <dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
			<version>2.5.0</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.5.0</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.5.0</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.jr</groupId>
			<artifactId>jackson-jr-all</artifactId>
			<version>2.5.0</version>
		</dependency>
	    <!-- https://mvnrepository.com/artifact/org.jgroups/jgroups -->
		<dependency>
		    <groupId>org.jgroups</groupId>
		    <artifactId>jgroups</artifactId>
		    <version>4.0.12.Final</version>
		</dependency>
		
		<dependency>
			<groupId>com.thetransactioncompany</groupId>
			<artifactId>jsonrpc2-client</artifactId>
			<version>1.15</version>
		</dependency>
	</dependencies>

	<build>
		<finalName>task_one</finalName>
		<plugins>
			<plugin>
				<groupId>org.mybatis.generator</groupId>
				<artifactId>mybatis-generator-maven-plugin</artifactId>
				<version>1.3.2</version>
				<configuration>
					<verbose>true</verbose>
					<overwrite>true</overwrite>
				</configuration>
			</plugin>
			<plugin>  
	            <groupId>org.apache.maven.plugins</groupId>  
	            <artifactId>maven-compiler-plugin</artifactId>  
	            <version>2.3.2</version>  
	            <configuration>  
	                <source>1.8</source> 
	                <target>1.8</target>
	            </configuration>  
	        </plugin>  
		</plugins>
	</build>

</project>

3.4 Spring與MyBatis的整合

所有需要的JAR包都引入以後,首先進行Spring與MyBatis的整合,然後再進行JUnit測試效果。

3.4.1 配置檔案相關內容

jdbc.properties

該檔案主要功能:資料庫連線資源相關。

#定義初始連線數
initialSize=0
#定義最大連線數
maxActive=20
#定義最大空閒
maxIdle=20
#定義最小空閒
minIdle=1
#定義最長等待時間
maxWait=60000

# MySQL資料庫連線配置
validationQuery=SELECT 1
jdbc_url=jdbc:mysql://localhost:3306/user?useUnicode=true&amp;characterEncoding=UTF-8
jdbc_username=root
jdbc_password=123456789
jdbc_driver=com.mysql.jdbc.Driver

# Oracle資料庫連線配置
#validationQuery=SELECT 1 FROM DUAL
#jdbc_url=jdbc:oracle:thin:@192.168.1.2:1521:orcl
#jdbc_username=scott
#jdbc_password=123456789
#jdbc_driver=oracle.jdbc.driver.OracleDriver

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

spring.xml

該檔案主要功能:引入配置屬性檔案、自動掃描。

<?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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">

	<!-- 引入資料庫配置屬性檔案 -->
	<context:property-placeholder location="classpath:jdbc.properties" />

	<!-- 自動掃描(自動注入) -->
	<context:component-scan base-package="com.service" />
</beans>

spring-mybatis.xml  

該檔案主要功能:整合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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="
http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
">

	<!-- 配置資料來源 -->
	<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
		<property name="driverClassName" value="${jdbc_driver}"/>
		<property name="url" value="${jdbc_url}" />
		<property name="username" value="${jdbc_username}" />
		<property name="password" value="${jdbc_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>
		

		<property name="validationQuery" value="${validationQuery}" />
		<property name="testOnBorrow" value="false" />
		<property name="testOnReturn" value="false" />
		<property name="testWhileIdle" value="true" />

		<!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閒連線,單位是毫秒 -->
		<property name="timeBetweenEvictionRunsMillis" value="60000" />
		<!-- 配置一個連線在池中最小生存的時間,單位是毫秒 -->
		<property name="minEvictableIdleTimeMillis" value="25200000" />

		<!-- 開啟removeAbandoned功能 -->
		<property name="removeAbandoned" value="true" />
		<!-- 1800秒,也就是30分鐘 -->
		<property name="removeAbandonedTimeout" value="1800" />
		<!-- 關閉abanded連線時輸出錯誤日誌 -->
		<property name="logAbandoned" value="true" />

		<!-- 監控資料庫 -->
		<property name="filters" value="mergeStat" />
	</bean>

	<!-- spring和MyBatis完美整合,不需要mybatis的配置對映檔案 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<!-- 自動掃描entity目錄, 省掉Configuration.xml裡的手工配置 -->
		<property name="mapperLocations" value="classpath:com/mapping/*.xml" />
	</bean>

	<!-- DAO介面所在包名,Spring會自動查詢其下的類。採用包掃描的方式配置 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.dao" />
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
	</bean>

	<!-- 配置事務管理器 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>

	<!-- 註解方式配置事物 -->
	<!-- <tx:annotation-driven transaction-manager="transactionManager" /> -->

	<!-- 攔截器方式配置事物 -->
	<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="add*" propagation="REQUIRED" />
			<tx:method name="append*" propagation="REQUIRED" />
			<tx:method name="insert*" propagation="REQUIRED" />
			<tx:method name="save*" propagation="REQUIRED" />
			<tx:method name="update*" propagation="REQUIRED" />
			<tx:method name="modify*" propagation="REQUIRED" />
			<tx:method name="edit*" propagation="REQUIRED" />
			<tx:method name="delete*" propagation="REQUIRED" />
			<tx:method name="remove*" propagation="REQUIRED" />
			<tx:method name="repair" propagation="REQUIRED" />
			<tx:method name="delAndRepair" propagation="REQUIRED" />
			<tx:method name="get*" propagation="SUPPORTS" />
			<tx:method name="find*" propagation="SUPPORTS" />
			<tx:method name="load*" propagation="SUPPORTS" />
			<tx:method name="search*" propagation="SUPPORTS" />
			<tx:method name="datagrid*" propagation="SUPPORTS" />
			<tx:method name="*" propagation="SUPPORTS" />
		</tx:attributes>
	</tx:advice>

	<aop:config>
		<aop:pointcut id="transactionPointcut" expression="execution(* sy.service..*Impl.*(..))" />
		<aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />
	</aop:config>

	<!-- 配置druid監控spring jdbc -->
	<bean id="druid-stat-interceptor" class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor">
	</bean>
	<bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut" scope="prototype">
		<property name="patterns">
			<list>
				<value>com.service.*</value>
				<value>com.serviceImpl.*</value>
			</list>
		</property>
	</bean>
	<aop:config>
		<aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut" />
	</aop:config>
</beans>

3.4.2 JUnit測試

3.4.2.1 建立測試用表:

注意!MySQL與Oracle中,設定主鍵方式不同,MySQL中直接指定欄位id AUTO_INCREMENT為自增主鍵,Oracle中則需要觸發器或自增序列設定自增主鍵。

CREATE TABLE `user` (
	`id` INT (11) NOT NULL AUTO_INCREMENT,
	`user_name` VARCHAR (40) NOT NULL,
	`user_password` VARCHAR (255) NOT NULL
	PRIMARY KEY (`id`)
) ENGINE = INNODB AUTO_INCREMENT = 1 DEFAULT CHARSET = utf8;
INSERT INTO `user` VALUES ('1', '張三', '11111');

3.4.3.2 建立實體類、MyBatis對映檔案以及DAO介面

此部分對應內容為如下,由於是手寫,沒有采用MyBatis Generator自動建立程式碼,所以mapping只測試了四個功能。

3.4.3.3 建立Service介面及其實現類

此部分對應內容為如下:

具體內容如下:

UserService.java

package com.service;  

import java.util.List;

import com.model.User;
  
public interface UserService {  
    public User getUserById(int id);
    
    public boolean regist(String username, String password);
    
    public boolean login(String username, String password);
    
    public List<User> selectAll();
}  

UserServiceImpl.java

package com.service.impl;
import java.util.List;

import javax.annotation.Resource;  
  
import org.springframework.stereotype.Service;

import com.dao.UserDao;
import com.model.User;
import com.service.UserService;
  
@Service("userService")  
public class UserServiceImpl implements UserService {  
    @Resource  
    private UserDao userDao;  
    
    public User getUserById(int id) {  
        // TODO Auto-generated method stub  
        return this.userDao.selectByPrimaryKey(id);  
    }

	@Override
	public boolean regist(String username, String password) {
		System.out.println("==========");
		System.out.println("userServiceImpl, regist: " + username + password);
		System.out.println("輸入的賬號:" + username + "輸入的密碼:" + password);
		if (username==""||password=="") {
			return false;
		}else {
			userDao.addUser(username, password);
			return true;
		}
	}

	@Override
	public boolean login(String username, String password) {
		System.out.println("==========");
		System.out.println("userServiceImpl, login: " + username + password);
		System.out.println("輸入的賬號:" + username + "輸入的密碼:" + password);
		User user = userDao.findUserByNameAndPwd(username, password);
		if (user != null) {
          if (user.getUser_name().equals(username) && user.getUser_password().equals(password)) {
        	  return true;
          }
      }
      return false;
	}

	@Override
	public List<User> selectAll() {
		return this.userDao.selectAllUser();
	}
}  

3.4.3.3 建立測試用例

此部分對應內容為如下:

測試類中採用註解的方式來引入配置檔案和類,然後再將service介面物件注入,就可以進行測試了。測試成功則表示Spring和Mybatis整合成功。輸出資訊使用的是Log4j列印到控制檯。

測試類如下:

package com.test;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.alibaba.fastjson.JSON;
import com.model.User;
import com.service.UserService;

/**   
 * @ClassName:  testweb   
 * @Description: TODO
 * @author: li_xj 
 * @date: 2018年9月16日 上午12:07:55   
 *     
 */
@RunWith(SpringJUnit4ClassRunner.class)       

@ContextConfiguration(locations = { "classpath:spring.xml", "classpath:spring-mybatis.xml" }) 

public class testweb {
	private static Logger logger = Logger.getLogger(testweb.class);
	
	@Resource
	private UserService userService;
	
	@Test(expected=java.lang.ArithmeticException.class)
	public void test1() {
		System.out.println("test1");
		User user = userService.getUserById(1);
		logger.info(JSON.toJSONString(user));
	}
}

測試結果:

至此,整合完成Spring和mybatis兩大框架。

3.5 整合SpringMVC

3.5.1 配置spring-mvc.xml

spring-mvc.xml

該檔案主要功能:自動掃描控制器,設定靜態資源,啟動註解功能,設定檢視解析器。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc" 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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.0.xsd 
http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

	<!-- 預設的註解對映的支援 -->
	<mvc:annotation-driven />

	<!-- 解決:No mapping found for HTTP request with URI的問題 -->
	<mvc:default-servlet-handler />

	<!-- 基於註解的Handler配置 自動掃描controller包下的所有類,使其認為spring mvc的控制器 -->
	<context:component-scan base-package="com.controller" />

	<!-- 靜態資源存在時候不進行對映,表示WEB-VENDER下的東西都是靜態資源 -->
	<mvc:resources mapping="/WEB-VENDER/**" location="/WEB-VENDER/" />

	<!-- 
		2,3. 啟動Spring MVC的註解功能,完成請求和註解POJO的對映 
		AnnotationMethodHandlerAdapter與RequestMappingHandlerAdapter 
		為 spring mvc 支援類註解和方法級別註解的兩個處理類
	-->
	<bean
		class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
				<ref bean="mappingJacksonHttpMessageConverter" /><!-- json轉換器 -->
			</list>
		</property>
	</bean>
	<bean
		class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
		<property name="messageConverters">
			<list>
				<ref bean="mappingJacksonHttpMessageConverter" />
			</list>
		</property>
	</bean>

	<!-- 4. 檢視解析器 對模型檢視名稱的解析,即在模型檢視名稱新增前後綴 解析jsp解析,預設使用jstl標籤,classpath下的得有jstl的包 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver"
		p:prefix="/WEB-INF/html/" p:suffix=".html" />

	<!-- 避免IE執行AJAX時,返回JSON出現下載檔案 -->
	<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
		<property name="supportedMediaTypes">
			<list>
				<bean class="org.springframework.http.MediaType">
					<constructor-arg index="0" value="text" />
					<constructor-arg index="1" value="plain" />
					<constructor-arg index="2" value="UTF-8" />
				</bean>
				<bean class="org.springframework.http.MediaType">
					<constructor-arg index="0" value="*" />
					<constructor-arg index="1" value="*" />
					<constructor-arg index="2" value="UTF-8" />
				</bean>
				<bean class="org.springframework.http.MediaType">
					<constructor-arg index="0" value="text" />
					<constructor-arg index="1" value="*" />
					<constructor-arg index="2" value="UTF-8" />
				</bean>
				<bean class="org.springframework.http.MediaType">
					<constructor-arg index="0" value="application" />
					<constructor-arg index="1" value="json" />
					<constructor-arg index="2" value="UTF-8" />
				</bean>
			</list>
		</property>
	</bean>

</beans>

3.5.2 配置web.xml

該檔案主要功能:配置的spring-mvc的Servlet、對spring.xml與spring-mybatis.xml的引入。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:web="http://java.sun.com/xml/ns/javaee" 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-demo</display-name>
  <servlet>
    <description>spring mvc servlet</description>
    <servlet-name>springMvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <description>spring mvc 的配置檔案:spring-mvc.xml</description>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springMvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>/index.jsp</welcome-file>
    <welcome-file>/index.html</welcome-file>
    <welcome-file>/index.htm</welcome-file>
    <welcome-file>/default.html</welcome-file>
    <welcome-file>/default.htm</welcome-file>
    <welcome-file>/default.jsp</welcome-file>
  </welcome-file-list>
  <display-name>mybatis</display-name>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring.xml,classpath:spring-mybatis.xml</param-value>
  </context-param>
  <context-param>
    <param-name>spring.profiles.active</param-name>
    <param-value>dev</param-value>
  </context-param>
  <context-param>
    <param-name>spring.profiles.default</param-name>
    <param-value>dev</param-value>
  </context-param>
  <context-param>
    <param-name>spring.liveBeansView.mbeanDomain</param-name>
    <param-value>dev</param-value>
  </context-param>
  <filter>
    <description>字符集過濾器</description>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <description>字符集編碼</description>
      <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>
  <listener>
    <description>spring監聽器</description>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <listener>
    <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
  </listener>
  <session-config>
    <session-timeout>15</session-timeout>
  </session-config>
</web-app>

3.5.3 建立UserController類

UserController.java

package com.controller;

import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.model.User;
import com.service.UserService;

/**
 * 
 * @ClassName:  userController   
 * @Description: TODO
 * @author: li_xj 
 * @date: 2018年9月15日 下午4:20:53   
 *
 */
@Controller
@RequestMapping("/user")
public class UserController {

	private UserService userService;

	public UserService getUserService() {
		return userService;
	}

	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	//測試
	@RequestMapping(value="/showUser/{id}", method=RequestMethod.GET)
	public String showUser(@PathVariable int id, HttpServletRequest request) {
		System.out.println(id);
		User user = userService.getUserById(id);
		System.out.println(user);
		request.setAttribute("user", user);
		return "showUser";
	}
	
	//正常訪問new_user頁面
    @RequestMapping("/index")
    public String index(){
        return "index";
    }
    
  //正常訪問system_index頁面
    @RequestMapping("/system_index")
    public String system_index(){
        return "system_index";
    }
	
    //驗證regist
	@RequestMapping(value="/checkRegist", method=RequestMethod.POST, produces="text/html;charset=UTF-8;")
	@ResponseBody //只返回資料,不返回頁面
	public String checkRegist(HttpServletRequest request, @RequestBody String user) {
		System.out.println("==========");
		String[] strs=user.split("\"");	
		String username = strs[3];
		String password = strs[7];
		System.out.println("使用者註冊:" + username + password);
		
		boolean registType = userService.regist(username, password);
		JSONObject jsonObject = new JSONObject();
		if (registType) {
			jsonObject.put("message", "註冊成功!");
            return jsonObject.toJSONString();
		}else{ 
			jsonObject.put("message", "註冊失敗!");
            return jsonObject.toJSONString();
        }
	}
	
    //驗證login
	@RequestMapping(value="/checkLogin", method=RequestMethod.POST,  produces="text/html;charset=UTF-8;")
	@ResponseBody
	public String checkLogin(HttpServletRequest request, @RequestBody String user) {
		System.out.println("==========");
		String[] strs=user.split("\"");	
		String username = strs[3];
		String password = strs[7];
		System.out.println("使用者登入:" + username + password);
		
		boolean loginType = userService.login(username, password);
		System.out.println(loginType);
		JSONObject jsonObject = new JSONObject();
        if(loginType){
        	jsonObject.put("message", "true");
            return jsonObject.toJSONString();
        }else{ 
        	jsonObject.put("message", "fail");
            return jsonObject.toJSONString();
        }
	}
	
	// 查詢所有使用者
	@RequestMapping(value="/selectAllUser", method=RequestMethod.POST,  produces="text/html;charset=UTF-8;")
	@ResponseBody
	public String selectAllUser(HttpServletRequest request) {
		System.out.println("=====選擇所有使用者======");
		List<User> userList = userService.selectAll();
		JSONArray jsonArray = new JSONArray();
		for(User user:userList) {
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("id", user.getId());
			jsonObject.put("user_name", user.getUser_name());
			jsonObject.put("user_password", user.getUser_password());
			
			jsonArray.add(jsonObject);
		}
		System.out.println(jsonArray);
		return jsonArray.toJSONString();
	}
}

3.5.4 新建前端部分

3.5.4.1 採用jsp

由於本文最終顯示互動的是HTML頁面,所以在配置時將檢視解析器設定為html,在測試整合springmvc結果時,可以採用jsp頁面測試,修改spring-mvc.xml檔案如下:

	<!-- 4. 檢視解析器 對模型檢視名稱的解析,即在模型檢視名稱新增前後綴 解析jsp解析,預設使用jstl標籤,classpath下的得有jstl的包 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver"
		p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />

結果如下:

至此,SSM三大框架的整合完成!!!

3.5.4.2 採用HTML

SSM三大框架的整合完成後,考慮的問題是實現簡單的登陸註冊功能。前端部分採用bootstrap設定樣式內容,顯示頁面為HTML頁面而非jsp頁面。jsp頁面可以採用如${user.userName}的方式,將後臺資料直接顯示在前端,而HTML頁面則需要Ajax非同步傳輸獲取結果。

此部分結構如圖:

主要邏輯:前端訪問index.html頁面後,輸入使用者名稱密碼,通過Ajax將輸入的資料傳送到後臺controller,controller中通過指定介面service中的方法,在實現類serviceImpl中,操作dao對應的mapping實現具體的SQL。

部分關鍵程式碼:

index.js

 $.ajax({
	        type: "post",
	        url: "/task_one/user/checkRegist",
	        dataType:'json',
	        contentType: "application/json;charset=utf-8",
	        data: JSON.stringify(user),
	        
	        success:function(result){
	        	alert(result.message);
	        	location.reload();
	        },
	        error: function (XMLHttpRequest, textStatus, errorThrown) {
	            console.log(XMLHttpRequest.status);
	            console.log(XMLHttpRequest.readyState);
	            console.log(textStatus);
	        }
	    });

UserController.java

    //驗證regist
	@RequestMapping(value="/checkRegist", method=RequestMethod.POST, produces="text/html;charset=UTF-8;")
	@ResponseBody //只返回資料,不返回頁面
	public String checkRegist(HttpServletRequest request, @RequestBody String user) {
		System.out.println("==========");
		String[] strs=user.split("\"");	
		String username = strs[3];
		String password = strs[7];
		System.out.println("使用者註冊:" + username + password);
		
		boolean registType = userService.regist(username, password);
		JSONObject jsonObject = new JSONObject();
		if (registType) {
			jsonObject.put("message", "註冊成功!");
            return jsonObject.toJSONString();
		}else{ 
			jsonObject.put("message", "註冊失敗!");
            return jsonObject.toJSONString();
        }
	}

UserService.java 介面中定義的方法:

public boolean regist(String username, String password);

UserServiceImpl.java 實現類中對應的實現方法:

	@Override
	public boolean regist(String username, String password) {
		System.out.println("==========");
		System.out.println("userServiceImpl, regist: " + username + password);
		System.out.println("輸入的賬號:" + username + "輸入的密碼:" + password);
		if (username==""||password=="") {
			return false;
		}else {
			userDao.addUser(username, password);
			return true;
		}
	}

UserDao.java 中定義的add方法:

 public void addUser(@Param("user_name")String username,@Param("user_password") String password);

最終UserMapper.xml 中對映的實現SQL:

  <insert id="addUser">
        <!-- MySQL -->
		insert into USER(user_name, user_password) values(#{user_name,jdbcType=VARCHAR}, #{user_password,jdbcType=VARCHAR})

        <!-- Oracle -->
		insert into USER(id, user_name, user_password) values(userinfo_id.nextval, #{user_name,jdbcType=VARCHAR}, #{user_password,jdbcType=VARCHAR})
  </insert>

3.6 結果展示

最終的登陸頁面:

使用者名稱或密碼錯誤提示:

註冊成功提示:

登陸成功提示:

登陸成功後自動跳轉到系統首頁,查詢所有使用者資訊:

此時資料庫內容如下:

至此,所有內容整合構建完畢!!!

四、總結

本人菜鳥一個,水平一般,能力有限。雖然之前接觸過並搭建過SSM框架,但是藉助MyBatis Generator等工具,對於底層的實現過程以及對映過程不是很清晰,在自己手動寫了一遍之後,深有感觸,本文只是實現了最基本的框架以及最基本的註冊登陸,在實際操作過程中,肯定存在很多值得優化的地方。在框架的整合與功能實現的整個過程中,總結的錯誤及內容點多達37個,附於錯誤集錦。對於spring的內容還需要更深一層次的理解與感悟,日後有時間在繼續優化、重構程式碼。

與君共勉!

五、錯誤集錦

1. Eclipse 修改maven 倉儲Repository位置 https://blog.csdn.net/anialy/article/details/21876099

2. maven映象修改 https://blog.csdn.net/only_wan/article/details/52975698

3. maven 轉  maven web https://blog.csdn.net/zouxucong/article/details/56009537

4. ..\target\m2e-wtp\web-resources\META-INF\MANIFEST.MF (系統找不到指定的路徑)解決辦法 https://blog.csdn.net/liliang_11676/article/details/79272348

5. Maven專案pom.xml檔案報錯“web.xml is missing and <failOnMissingWebXml> is set to   true” http://blog.51cto.com/wuyongzhiyi/1927436

6. navicat 連線Oracle資料庫 OCI更新 https://www.cnblogs.com/taojietx/p/6627934.html https://blog.csdn.net/suyu_yuan/article/details/51321761

7. 使用maven新增、管理oracle驅動包 https://blog.csdn.net/dwfyzf/article/details/78983066

8. Oracle 對錶的基本操作 https://blog.csdn.net/qq_33369215/article/details/52775308

9. get,set快捷鍵 右鍵--source--Generate Getters and Setters

10. 模板各模組註釋快捷鍵 alt+shift+J

11. Oracle 實現主鍵自增 https://zhidao.baidu.com/question/358461319.html

CREATE sequence userinfo_seq START WITH 1  INCREMENT BY 1;

12. oracle 時間格式 to_date('2018-09-15 16:36:00', 'yyyy-mm-dd hh24:mi:ss')

13. No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

14. spring報錯Error creating bean with name... spring-mvc 掃描包 spring-mybatis 掃描service與serviceImpl spring 新增資料庫配置檔案與掃描service https://blog.csdn.net/grit_icpc/article/details/58141424 https://blog.csdn.net/zhanghe687/article/details/71214166

15. 配置jdbc.properties檔案 https://blog.csdn.net/u012562943/article/details/52489447 https://www.cnblogs.com/zhangchengzhangtuo/p/5614305.html

16. Spring連線mysql資料庫錯誤:Cannot load JDBC driver class '${driver}' 沒有引入jdbc.properties配置檔案,系統無法識別

17. jdk.tools-1.8.jar jdk.tools-1.8.jar 在jdk的中找到 不需要額外下載 https://blog.csdn.net/fruitzerg/article/details/78339518

18. eclipse解決專案validate卡住的問題 https://blog.csdn.net/u011747152/article/details/79071388 https://blog.csdn.net/ksdb0468473/article/details/52249028

19. Not found org.springframework.http.converter.json.MappingJacksonHttpMessageConverter 新增jar包 <dependency>     <groupId>com.fasterxml.jackson.core</groupId>     <artifactId>jackson-annotations</artifactId>     <version>2.5.0</version> </dependency> <dependency>     <groupId>com.fasterxml.jackson.core</groupId>     <artifactId>jackson-core</artifactId>     <version>2.5.0</version> </dependency> <dependency>     <groupId>com.fasterxml.jackson.core</groupId>     <artifactId>jackson-databind</artifactId>     <version>2.5.0</version> </dependency> <dependency>     <groupId>com.fasterxml.jackson.jr</groupId>     <artifactId>jackson-jr-all</artifactId>     <version>2.5.0</version> </dependency> https://blog.csdn.net/hongweigg/article/details/46919235

20. 測試環境中,新增內容: @ContextConfiguration(locations = { "classpath:spring.xml", "classpath:spring-mybatis.xml" })  引入jdbc.properties檔案

21. impl 與 service放一起,掃描時一起掃描

22. 表單內容自動提交null 在controller中新加正常訪問內容:     //正常訪問login頁面     @RequestMapping("/regist")     public String regist(){         return "regist";     } 驗證的內容寫在另一個方法中:     @RequestMapping(value="/checkRegist", method=RequestMethod.GET)     public String checkRegist(User user,  HttpServletRequest request) throws UnsupportedEncodingException {

https://blog.csdn.net/s740556472/article/details/71247285

23. ajax response亂碼  在@RequestMapping裡的併發配置produces={"application/json;","text/html;charset=UTF-8;"} https://www.cnblogs.com/zique/p/6171862.html

24. annotation @RequestBody is disallowed for this location I am stupid. The proper annotation is @ResponseBody, not @RequestBody. http://forum.spring.io/forum/spring-projects/roo/111922-annotation-requestbody-is-disallowed-for-this-location

25. JQuery的ajax往後臺傳值情況 https://blog.csdn.net/binghuazheng/article/details/78380338

26. ajax後臺資料返回前端:     0.URL問題:這個URL是指向的controller中的mapping地址,為: 專案名 + controller的mapping + function的mapping     1. 設定function為 @ResponseBody ,設定成只返回資料,指向頁面     2.返回的資料顯示亂碼:在controller中的mapping中,新增:@RequestMapping(produces="text/html;charset=UTF-8;")     3.前端的ajax中,指定資料格式為json,在後臺返回時,要新建jsonobjet物件,封裝資料,再傳到前端ajax時可以正常解析;否則在狀態正常時,也會出現解析格式錯誤;      27. js前端驗證輸入是否為空 https://zhidao.baidu.com/question/535920141.html

28. ORA-00928 missing SELECT keyword http://ruowu.iteye.com/blog/648677

29. Oracle 連結資料庫:ORA-00904: invalid identifier     非法識別符號,說明sql寫的列名可能識別不到。網上有說不能加引號,否則識別不到。     但是在此mapping 的xml檔案中,每個用到的欄位都需要加雙引號才能正確識別。     select      "id", "user_name", "user_password"     from "userinfo"     where "id" = #{id,jdbcType=INTEGER}

30. html檔案引用靜態資源:css,js,img <link rel="stylesheet" href="/task/WEB-VENDER/css/signin.css" > 設定spring-mvc.xml:     <!-- 靜態資源存在時候不進行對映,表示WEB-VENDER下的東西都是靜態資源 -->     <mvc:resources mapping="/WEB-VENDER/**" location="/WEB-VENDER/" /> 然後直接引用 /task/...路徑即可。

31. TooManyResultsException異常 https://blog.csdn.net/liu_005/article/details/50822544

32. Mapper method 'com.dao.UserDao.addUser' has an unsupported return type: class com.model.User addUser()方法為void型別 https://blog.csdn.net/qq_32917699/article/details/77743453 https://www.cnblogs.com/dushan/p/5175779.html

33. 後臺 list 轉換成json格式:先構造json物件,再存入資料中。     JSONArray jsonArray = new JSONArray();     for(User user:userList) {         JSONObject jsonObject = new JSONObject();         jsonObject.put("id", user.getId());         jsonObject.put("user_name", user.getUser_name());         jsonObject.put("user_password", user.getUser_password());                  jsonArray.add(jsonObject);     }

34. js如何把伺服器裡面的json資料渲染輸出到html頁面 https://segmentfault.com/q/1010000012895596 迴圈拼接,其他框架

35. 前端json字串解析出json物件 https://www.cnblogs.com/songyunxinQQ529616136/p/6259559.html https://www.cnblogs.com/redfire/p/7702108.html

36. html 換行 <br>

37. sql排序:order by "" desc(降序)/asc(升序)

六、參考連結

https://segmentfault.com/q/1010000012895596 

https://blog.csdn.net/binghuazheng/article/details/78380338

https://www.cnblogs.com/zhangchengzhangtuo/p/5614305.html