搭建ssm框架,咱們要分幾步進行,把每一個配置文件分開寫,這樣看上去一目瞭然,有利於後期的修改維護,對本身也能夠記請每一步的內容和步驟,方便記憶。css
一.spring-dao.xmlhtml
二.jdbc. propertiesjava
三.mybatis-config.xmlmysql
四.spring-service.xml程序員
五.spring-web.xmlweb
六. web.xmlspring
七.logback.xmlsql
詳細配置以下:數據庫
第一步:先在spring文件夾裏新建spring-dao.xml文件,由於spring的配置太多了,這裏咱們分三層
dao service web
1.讀入數據庫鏈接的相關參數
2.配置數據鏈接池
3.配置鏈接屬性,
4.配置c3p0,只配了幾個經常使用的
5.配置SqlSessionFactory對象(mybatis)
6.掃描dao層接口,動態實現dao接口
spring-dao.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
4 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">
5 <!-- 配置整合mybatis過程 -->
6 <!-- 1.配置數據庫相關參數properties的屬性:${url} -->
7 <context:property-placeholder location="classpath:jdbc.properties" />
8
9 <!-- 2.數據庫鏈接池 -->
10 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
11 <!-- 配置鏈接池屬性 -->
12 <property name="driverClass" value="${jdbc.driver}" />
13 <property name="jdbcUrl" value="${jdbc.url}" />
14 <property name="user" value="${jdbc.username}" />
15 <property name="password" value="${jdbc.password}" />
16
17 <!-- c3p0鏈接池的私有屬性 -->
18 <property name="maxPoolSize" value="30" />
19 <property name="minPoolSize" value="10" />
20 <!-- 關閉鏈接後不自動commit -->
21 <property name="autoCommitOnClose" value="false" />
22 <!-- 獲取鏈接超時時間 -->
23 <property name="checkoutTimeout" value="10000" />
24 <!-- 當獲取鏈接失敗重試次數 -->
25 <property name="acquireRetryAttempts" value="2" />
26 </bean>
27
28 <!-- 3.配置SqlSessionFactory對象 -->
29 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
30 <!-- 注入數據庫鏈接池 -->
31 <property name="dataSource" ref="dataSource" />
32 <!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
33 <property name="configLocation" value="classpath:mybatis-config.xml" />
34 <!-- 掃描entity包 使用別名 -->
35 <property name="typeAliasesPackage" value="com.soecode.lyf.entity" />
36 <!-- 掃描sql配置文件:mapper須要的xml文件 -->
37 <property name="mapperLocations" value="classpath:mapper/*.xml" />
38 </bean>
39
40 <!-- 4.配置掃描Dao接口包,動態實現Dao接口,注入到spring容器中 -->
41 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
42 <!-- 注入sqlSessionFactory -->
43 <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
44 <!-- 給出須要掃描Dao接口包 -->
45 <property name="basePackage" value="com.soecode.lyf.dao" />
46 </bean>
47 </beans>
jdbc. properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3307/ssm?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=
由於這裏用到mybatis,因此須要mybatis核心文件,在recourse文件夾裏新建mybatis-configx.xml
1.使用自增主鍵
2.使用列別名
3.開啓駝峯命名轉換create_time ->createTime
mybatis-config.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>
<!-- 配置全局屬性 -->
<settings>
<!-- 使用jdbc的getGeneratedKeys獲取數據庫自增主鍵值 -->
<setting name="useGeneratedKeys" value="true" />
<!-- 使用列別名替換列名 默認:true -->
<setting name="useColumnLabel" value="true" />
<!-- 開啓駝峯命名轉換:Table{create_time} -> Entity{createTime} -->
<setting name="mapUnderscoreToCamelCase" value="true" />
</settings>
</configuration>
第二步:剛弄好到層,接下來service層。在spring文件夾建立spring-service.xml
1.掃描service包全部的@Service註解
2.配置事務管理器,把事物交有spring來完成
3.配置基於註解的聲明事物,能夠直接在方法上@Transaction
spring-service.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"
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.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 掃描service包下全部使用註解的類型 -->
<context:component-scan base-package="com.soecode.lyf.service" />
<!-- 配置事務管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入數據庫鏈接池 -->
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 配置基於註解的聲明式事務 -->
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
第三步:配置web,在spring文件夾裏新建spring-web.xml
1.開啓SpringMVC註解模式,可使用@RequestMapping,@PathBariable,@ResponseBady等
2.對靜態資源的處理 ,如js,css,jsp等
3.配置警示牌、顯示ViewResolver,例如controller中某個方法返回一個string類型的「login」,實際上回返回「WEB-INF/login.jsp」
4.掃描web層的@Controller註解
spring-web.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"
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-3.0.xsd">
<!-- 配置SpringMVC -->
<!-- 1.開啓SpringMVC註解模式 -->
<!-- 簡化配置: (1)自動註冊DefaultAnootationHandlerMapping,AnotationMethodHandlerAdapter (2)提供一些列:數據綁定,數字和日期的format @NumberFormat, @DateTimeFormat, xml,json默認讀寫支持 -->
<mvc:annotation-driven />
<!-- 2.靜態資源默認servlet配置 (1)加入對靜態資源的處理:js,gif,png (2)容許使用"/"作總體映射 -->
<mvc:default-servlet-handler/>
<!-- 3.配置jsp 顯示ViewResolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 4.掃描web相關的bean -->
<context:component-scan base-package="com.soecode.lyf.web" />
</beans>
第四步:最後就是修改web.xml文件
web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1" metadata-complete="true">
<!-- 若是是用mvn命令生成的xml,須要修改servlet版本爲3.1 -->
<!-- 配置DispatcherServlet -->
<servlet>
<servlet-name>seckill-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置springMVC須要加載的配置文件 spring-dao.xml,spring-service.xml,spring-web.xml Mybatis - > spring -> springmvc -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-*.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>seckill-dispatcher</servlet-name>
<!-- 默認匹配全部的請求 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
咱們在項目中常常會使用到日誌,若以這裏還有配置日誌xml,在resources文件夾裏新建logback.xml
logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<!-- encoders are by default assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder -->
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="STDOUT" />
</root>
</configuration>
到目前爲止,咱們一共寫了7個配置文件
使用SSM(Spring、SpringMVC和Mybatis)已經有三個多月了,項目在技術上已經沒有什麼難點了,基於現有的技術就能夠實現想要的功能,固然確定有不少能夠改進的地方。以前沒有記錄SSM整合的過程,此次剛恰好基於本身的一個小項目從新搭建了一次,並且比項目搭建的要更好一些。之前解決問題的過程和方法並無及時記錄,之後在本身的小項目中遇到我再整理分享一下。此次,先說說三大框架整合過程。我的認爲使用框架並非很難,關鍵要理解其思想,這對於咱們提升編程水平頗有幫助。不過,若是用都不會,談思想就變成紙上談兵了!!!先技術,再思想。實踐出真知。(可經過圖片水印查看博客地址)apache
一、基本概念
1.一、Spring
Spring是一個開源框架,Spring是於2003 年興起的一個輕量級的Java 開發框架,由Rod Johnson 在其著做Expert One-On-One J2EE Development and Design中闡述的部分理念和原型衍生而來。它是爲了解決企業應用開發的複雜性而建立的。Spring使用基本的JavaBean來完成之前只可能由EJB完成的事情。然而,Spring的用途不只限於服務器端的開發。從簡單性、可測試性和鬆耦合的角度而言,任何Java應用均可以從Spring中受益。 簡單來講,Spring是一個輕量級的控制反轉(IoC)和麪向切面(AOP)的容器框架。
1.二、SpringMVC
Spring MVC屬於SpringFrameWork的後續產品,已經融合在Spring Web Flow裏面。Spring MVC 分離了控制器、模型對象、分派器以及處理程序對象的角色,這種分離讓它們更容易進行定製。
1.三、MyBatis
MyBatis 本是apache的一個開源項目iBatis, 2010年這個項目由apache software foundation 遷移到了google code,而且更名爲MyBatis 。MyBatis是一個基於Java的持久層框架。iBATIS提供的持久層框架包括SQL Maps和Data Access Objects(DAO)MyBatis 消除了幾乎全部的JDBC代碼和參數的手工設置以及結果集的檢索。MyBatis 使用簡單的 XML或註解用於配置和原始映射,將接口和 Java 的POJOs(Plain Old Java Objects,普通的 Java對象)映射成數據庫中的記錄。
二、開發環境搭建
若是須要,參看以前的博文:http://blog.csdn.net/zhshulin/article/details/30779873
三、Maven Web項目建立
若是須要,參看以前的博文:http://blog.csdn.net/zhshulin/article/details/37921705
四、SSM整合
下面主要介紹三大框架的整合,至於環境的搭建以及項目的建立,參看上面的博文。此次整合我分了2個配置文件,分別是spring-mybatis.xml,包含spring和mybatis的配置文件,還有個是spring-mvc的配置文件,此外有2個資源文件:jdbc.propertis和log4j.properties。完整目錄結構以下(最後附上源碼下載地址,不建議直接使用源碼,由於此教程已經有了所有代碼):
使用框架都是較新的版本:
Spring 4.0.2 RELEASE
Spring MVC 4.0.2 RELEASE
MyBatis 3.2.6
4.一、Maven引入須要的JAR包
爲了方便後面說的時候不須要引入JAR包,我這裏直接給出全部須要的JAR包,這都是基本的JAR包,每一個包的是幹什麼的都有註釋,就再也不多說了。
pom.xml
4.二、Spring與MyBatis的整合
全部須要的JAR包都引入之後,首先進行Spring與MyBatis的整合,而後再進行JUnit測試,先看一個項目結構圖:

4.2.一、創建JDBC屬性文件
jdbc.properties(文件編碼修改成utf-8)
- driver=com.mysql.jdbc.Driver
- url=jdbc:mysql://10.221.10.111:8080/db_zsl
- username=demao
- password=demao
- #定義初始鏈接數
- initialSize=0
- #定義最大鏈接數
- maxActive=20
- #定義最大空閒
- maxIdle=20
- #定義最小空閒
- minIdle=1
- #定義最長等待時間
- maxWait=60000
4.2.二、創建spring-mybatis.xml配置文件
這個文件就是用來完成spring和mybatis的整合的。這裏面也沒多少行配置,主要的就是自動掃描,自動注入,配置數據庫。註釋也很詳細,你們看看就明白了。
spring-mybatis.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: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-3.1.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.1.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
-
- <context:component-scan base-package="com.cn.hnust" />
-
- <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>
-
-
- <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
- <property name="dataSource" ref="dataSource" />
-
- <property name="mapperLocations" value="classpath:com/cn/hnust/mapping/*.xml"></property>
- </bean>
-
-
- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
- <property name="basePackage" value="com.cn.hnust.dao" />
- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
- </bean>
-
-
- <bean id="transactionManager"
- class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
- <property name="dataSource" ref="dataSource" />
- </bean>
-
- </beans>
4.2.三、Log4j的配置
爲了方便調試,通常都會使用日誌來輸出信息,Log4j是Apache的一個開放源代碼項目,經過使用Log4j,咱們能夠控制日誌信息輸送的目的地是控制檯、文件、GUI組件,甚至是套接口服務器、NT的事件記錄器、UNIX Syslog守護進程等;咱們也能夠控制每一條日誌的輸出格式;經過定義每一條日誌信息的級別,咱們可以更加細緻地控制日誌的生成過程。
Log4j的配置很簡單,並且也是通用的,下面給出一個基本的配置,換到其餘項目中也無需作多大的調整,若是想作調整或者想了解Log4j的各類配置,參看我轉載的一篇博文,很詳細:
http://blog.csdn.net/zhshulin/article/details/37937365
下面給出配置文件目錄:

log4j.properties
- #定義LOG輸出級別
- 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
4.2.四、JUnit測試
通過以上步驟(到4.2.2,log4j不配也沒影響),咱們已經完成了Spring和mybatis的整合,這樣咱們就能夠編寫一段測試代碼來試試是否成功了。
4.2.4.一、建立測試用表
既然咱們須要測試,那麼咱們就須要創建在數據庫中創建一個測試表,這個表建的很簡單,SQL語句爲:
- DROP TABLE IF EXISTS `user_t`;
-
- CREATE TABLE `user_t` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `user_name` varchar(40) NOT NULL,
- `password` varchar(255) NOT NULL,
- `age` int(4) NOT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-
- /*Data for the table `user_t` */
-
- insert into `user_t`(`id`,`user_name`,`password`,`age`) values (1,'測試','sfasgfaf',24);
4.2.4.二、利用MyBatis Generator自動建立代碼
參考博文:http://blog.csdn.net/zhshulin/article/details/23912615
這個可根據表自動建立實體類、MyBatis映射文件以及DAO接口,固然,我習慣將生成的接口名改成IUserDao,而不是直接用它生成的UserMapper。若是不想麻煩就能夠不改。完成後將文件複製到工程中。如圖:
4.2.4.三、創建Service接口和實現類
目錄結構:

下面給出具體的內容:
IUserService.jave
- package com.cn.hnust.service;
-
- import com.cn.hnust.pojo.User;
-
- public interface IUserService {
- public User getUserById(int userId);
- }
UserServiceImpl.java
- package com.cn.hnust.service.impl;
-
- import javax.annotation.Resource;
-
- import org.springframework.stereotype.Service;
-
- import com.cn.hnust.dao.IUserDao;
- import com.cn.hnust.pojo.User;
- import com.cn.hnust.service.IUserService;
-
- @Service("userService")
- public class UserServiceImpl implements IUserService {
- @Resource
- private IUserDao userDao;
- @Override
- public User getUserById(int userId) {
-
- return this.userDao.selectByPrimaryKey(userId);
- }
-
- }
4.2.4.四、創建測試類
測試類在src/test/java中創建,下面測試類中註釋掉的部分是不使用Spring時,通常狀況下的一種測試方法;若是使用了Spring那麼就可使用註解的方式來引入配置文件和類,而後再將service接口對象注入,就能夠進行測試了。
若是測試成功,表示Spring和Mybatis已經整合成功了。輸出信息使用的是Log4j打印到控制檯。
- package org.zsl.testmybatis;
-
- import javax.annotation.Resource;
-
- import org.apache.log4j.Logger;
- import org.junit.Before;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- import org.springframework.test.context.ContextConfiguration;
- import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-
- import com.alibaba.fastjson.JSON;
- import com.cn.hnust.pojo.User;
- import com.cn.hnust.service.IUserService;
-
- @RunWith(SpringJUnit4ClassRunner.class)
- @ContextConfiguration(locations = {"classpath:spring-mybatis.xml"})
-
- public class TestMyBatis {
- private static Logger logger = Logger.getLogger(TestMyBatis.class);
-
- @Resource
- private IUserService userService = null;
-
-
-
-
-
-
-
- @Test
- public void test1() {
- User user = userService.getUserById(1);
-
-
- logger.info(JSON.toJSONString(user));
- }
- }
測試結果:

至此,完成Spring和mybatis這兩大框架的整合,下面在繼續進行SpringMVC的整合。
4.三、整合SpringMVC
上面已經完成了2大框架的整合,SpringMVC的配置文件單獨放,而後在web.xml中配置整合。
4.3.一、配置spring-mvc.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: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-3.1.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.1.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
-
- <context:component-scan base-package="com.cn.hnust.controller" />
-
- <bean id="mappingJacksonHttpMessageConverter"
- class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
- <property name="supportedMediaTypes">
- <list>
- <value>text/html;charset=UTF-8</value>
- </list>
- </property>
- </bean>
-
- <bean
- class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
- <property name="messageConverters">
- <list>
- <ref bean="mappingJacksonHttpMessageConverter" />
- </list>
- </property>
- </bean>
-
- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
-
- <property name="prefix" value="/WEB-INF/jsp/" />
- <property name="suffix" value=".jsp" />
- </bean>
-
-
- <bean id="multipartResolver"
- class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
-
- <property name="defaultEncoding" value="utf-8" />
-
- <property name="maxUploadSize" value="10485760000" />
-
- <property name="maxInMemorySize" value="40960" />
- </bean>
-
- </beans>
4.3.二、配置web.xml文件
這裏面對spring-mybatis.xml的引入以及配置的spring-mvc的Servlet就是爲了完成SSM整合,以前2框架整合不須要在此處進行任何配置。配置同樣有詳細註釋,很少解釋了。
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"
- version="3.0">
- <display-name>Archetype Created Web Application</display-name>
-
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:spring-mybatis.xml</param-value>
- </context-param>
-
- <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>
-
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
-
- <listener>
- <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
- </listener>
-
-
- <servlet>
- <servlet-name>SpringMVC</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <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>SpringMVC</servlet-name>
-
- <url-pattern>/</url-pattern>
- </servlet-mapping>
- <welcome-file-list>
- <welcome-file>/index.jsp</welcome-file>
- </welcome-file-list>
-
- </web-app>
4.3.三、測試
至此已經完成了SSM三大框架的整合了,接下來測試一下,若是成功了,那麼恭喜你,若是失敗了,繼續調試吧,做爲程序員就是不停的與BUG作鬥爭!
4.3.3.一、新建jsp頁面

showUser.jsp 此頁面僅輸出一下用戶名,完成一個完整的簡單流程。
- <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>測試</title>
- </head>
-
- <body>
- ${user.userName}
- </body>
- </html>
4.3.3.二、創建UserController類
UserController.java 控制器
- package com.cn.hnust.controller;
-
- import javax.annotation.Resource;
- import javax.servlet.http.HttpServletRequest;
-
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.Model;
- import org.springframework.web.bind.annotation.RequestMapping;
-
- import com.cn.hnust.pojo.User;
- import com.cn.hnust.service.IUserService;
-
- @Controller
- @RequestMapping("/user")
- public class UserController {
- @Resource
- private IUserService userService;
-
- @RequestMapping("/showUser")
- public String toIndex(HttpServletRequest request,Model model){
- int userId = Integer.parseInt(request.getParameter("id"));
- User user = this.userService.getUserById(userId);
- model.addAttribute("user", user);
- return "showUser";
- }
- }
4.3.3.三、部署項目
輸入地址:localhost:8080/項目名稱/user/showUser?id=1
至此,SSM三大框架的整合就完成了,在此基礎上可再添加其餘功能。
參考地址:https://www.cnblogs.com/jay36/p/7762448.html
參考地址2:https://www.cnblogs.com/zHpx/p/7476539.html