SSM框架——Spring+SpringMVC+Mybatis的搭建教程

=================================================html

人工智能教程。零基礎!通俗易懂!風趣幽默!你們能夠看看是否對本身有幫助!


點擊查看高清無碼教程java

=================================================mysql

一:概述
SSM框架在項目開發中常用到,相比於SSH框架,它在僅幾年的開發中運用的更加普遍。git

  • Spring做爲一個輕量級的框架,有不少的拓展功能,最主要的咱們通常項目使用的就是IOC和AOP。
  • SpringMVC是Spring實現的一個Web層,至關於Struts的框架,可是比Struts更加靈活和強大!
  • Mybatis是 一個持久層的框架,在使用上相比Hibernate更加靈活,能夠控制sql的編寫,使用 XML或註解進行相關的配置!

根據上面的描述,學習SSM框架就很是的重要了!github

二:搭建一個SSM的過程web

  1. 使用Maven管理項目
    使用Maven在Eclipse中建立一個webapp的項目 ,具體的建立過程不作演示,若有不會建立的[建立項目]
    也可使用Maven命令進行建立,在Dos窗口進入指定的目錄,執行下面命令:
mvn archetype:create -DgroupId=org.ssm.dufy -DartifactId=ssm-demo -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

使用命令要注意,系統安裝了Maven,並配置好了環境變量![Maven的安裝和環境變量配置]spring

  1. 導入項目(命名建立),添加依賴
    導入項目是IDE中,或者直接在IDE建立,通常默認有【src/main/java】,手動建立【src/test/resources】、【src/test/java】文件夾。sql

    以下項目結構:數據庫

    而後直接配置 pom.xml文件中的包依賴!express

<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>org.dufy</groupId>
  <artifactId>ssm</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>ssmDemo</name>
  <url>http://maven.apache.org</url>
  <properties>
    <spring.version>4.0.5.RELEASE</spring.version>
    <mybatis.version>3.2.1</mybatis.version>
    <slf4j.version>1.6.6</slf4j.version>
    <log4j.version>1.2.12</log4j.version>
    <mysql.version>5.1.35</mysql.version>
    
    
  </properties>
  <dependencies>
  <!-- 添加Spring依賴 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</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-context-support</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</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.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <!--spring單元測試依賴 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>
 
  <!-- spring webmvc相關jar -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
  
  <!-- mysql驅動包 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${mysql.version}</version>
    </dependency>
    
    <!-- alibaba data source 相關jar包-->
     <dependency>
         <groupId>com.alibaba</groupId>
         <artifactId>druid</artifactId>
         <version>0.2.23</version>
     </dependency>
     
     <!-- alibaba fastjson 格式化對 -->  
        <dependency>  
            <groupId>com.alibaba</groupId>  
            <artifactId>fastjson</artifactId>  
            <version>1.1.41</version>  
        </dependency> 
    
     <!-- logback 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>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.1.2</version>
    </dependency>
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-core</artifactId>
        <version>1.1.2</version>
    </dependency>
    <dependency>
        <groupId>org.logback-extensions</groupId>
        <artifactId>logback-ext-spring</artifactId>
        <version>0.1.1</version>
    </dependency>
    
    <!--mybatis依賴 -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>${mybatis.version}</version>
    </dependency>

    <!-- mybatis/spring包 -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.2.0</version>
    </dependency>
  <!-- 添加servlet3.0核心包 -->
          <dependency>
              <groupId>javax.servlet</groupId>
              <artifactId>javax.servlet-api</artifactId>
              <version>3.0.1</version>
          </dependency>
          <dependency>
              <groupId>javax.servlet.jsp</groupId>
              <artifactId>javax.servlet.jsp-api</artifactId>
              <version>2.3.2-b01</version>
          </dependency>
          <!-- jstl -->
          <dependency>
              <groupId>javax.servlet</groupId>
              <artifactId>jstl</artifactId>
              <version>1.2</version>
          </dependency>
    <!--單元測試依賴 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>ssmDemo</finalName>
  </build>
</project>
  1. 建立數據庫和表,生成代碼
    建立數據庫我參考別人的博客數據庫設計,這塊沒有本身去書寫,直接添上代碼
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)

生成代碼請查看:

[Mybatis自動生成代碼]

生成的代碼導入圖片解釋:

  1. Spring 和 mybatis整合,鏈接數據庫,進行Junit測試
    將生成的代碼拷貝到項目中,而後進行Spring和Mybatis的整合,添加配置文件!

主要有
applicationContent.xml :Spring的相關配置!
Spring-mhbatis.xml : Spring和Mybatis集成配置!
jdbc.properties : 數據庫信息配置!
logback.xml : 日誌輸出信息配置!(不作介紹,詳細信息查看源碼

主要介紹applicationContext.xml、Spring-mhbatis.xml、jdbc.properties。主要內容以下:

jdbc.properties

jdbc_driverClassName =com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf8
jdbc_username=root
jdbc_password=root

applicationContext.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
">
    <!-- 1.配置jdbc文件 -->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="locations" value="classpath:jdbc.properties"/>
    </bean>

    <!-- 2.掃描的包路徑,這裏不掃描被@Controller註解的類 --><!--使用<context:component-scan/> 能夠不在配置<context:annotation-config/> -->
    <context:component-scan base-package="org.ssm.dufy">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    
    <import resource="classpath:spring-mybatis.xml" />
    
</beans>

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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" 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.2.xsd
   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

<!-- 3.配置數據源 ,使用的alibba的數據庫-->
     <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <!-- 基本屬性 url、user、password -->        
        <property name="driverClassName" value="${jdbc_driverClassName}"/>
        <property name="url" value="${jdbc_url}"/>
        <property name="username" value="${jdbc_username}"/>
        <property name="password" value="${jdbc_password}"/>
      
        <!-- 配置初始化大小、最小、最大 -->
        <property name="initialSize" value="10"/>
        <property name="minIdle" value="10"/>
        <property name="maxActive" value="50"/>

        <!-- 配置獲取鏈接等待超時的時間 -->
        <property name="maxWait" value="60000"/>
        <!-- 配置間隔多久才進行一次檢測,檢測須要關閉的空閒鏈接,單位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />

        <!-- 配置一個鏈接在池中最小生存的時間,單位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000" />

        <property name="validationQuery" value="SELECT 'x'" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />

        <!-- 打開PSCache,而且指定每一個鏈接上PSCache的大小  若是用Oracle,則把poolPreparedStatements配置爲true,mysql能夠配置爲false。-->
        <property name="poolPreparedStatements" value="false" />
        <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />

        <!-- 配置監控統計攔截的filters -->
        <property name="filters" value="wall,stat" />
    </bean>
    

     
    <!-- spring和MyBatis完美整合,不須要mybatis的配置映射文件 -->  
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" />  
        <!-- 自動掃描mapping.xml文件 -->  
        <property name="mapperLocations" value="classpath:org/ssm/dufy/mapper/*.xml"></property>  
    </bean>   
    
    
     <!-- DAO接口所在包名,Spring會自動查找其下的類 ,自動掃描了全部的XxxxMapper.xml對應的mapper接口文件,只要Mapper接口類和Mapper映射文件對應起來就能夠了-->  
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="org.ssm.dufy.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> 

    <!--======= 事務配置 End =================== -->
    <!-- 配置基於註解的聲明式事務 -->
    <!-- enables scanning for @Transactional annotations -->
    <tx:annotation-driven transaction-manager="transactionManager" />

    
</beans>

測試代碼,兩種方式:

測試1:

package org.ssm.dufy.service;

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 org.ssm.dufy.entity.User;

/**
 * 配置spring和junit整合,junit啓動時加載springIOC容器 spring-test,junit
 */
@RunWith(SpringJUnit4ClassRunner.class)
// 告訴junit spring配置文件
@ContextConfiguration({ "classpath:applicationContext.xml"})
public class IUserServiceTest {

    @Autowired
    public IUserService userService;
    
    @Test
    public void getUserByIdTest(){
     
        User user = userService.getUserById(1);
        System.out.println(user.getUserName());
    }
    
}

測試2:

package org.ssm.dufy.service;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.ssm.dufy.entity.User;

public class IUserServiceTest2 {

    
    public static void main(String[] args) {
        ApplicationContext application = new ClassPathXmlApplicationContext("applicationContext.xml");
        IUserService uService = (IUserService) application.getBean("userService");
        User user = uService.getUserById(1);
        System.out.println(user.getUserName());
    }
}

5:整合SpringMVC,添加配置,建立jsp
SpringMVC須要的依賴在pom.xml中已經加上了,如今需在Web項目中的web.xml中添加啓動SpringMVC啓動配置和Spring整合SpringMVC的配置了。
新增以下兩個文件:

spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:p="http://www.springframework.org/schema/p"
  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-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
     
    <!-- 掃描controller(controller層注入) -->
   <context:component-scan base-package="org.ssm.dufy.web" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
   
     <mvc:annotation-driven />

      <!-- 內容協商管理器  -->
    <!--一、首先檢查路徑擴展名(如my.pdf);二、其次檢查Parameter(如my?format=pdf);三、檢查Accept Header-->
    <bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
        <!-- 擴展名至mimeType的映射,即 /user.json => application/json -->
        <property name="favorPathExtension" value="true"/>
        <!-- 用於開啓 /userinfo/123?format=json 的支持 -->
        <property name="favorParameter" value="true"/>
        <property name="parameterName" value="format"/>
        <!-- 是否忽略Accept Header -->
        <property name="ignoreAcceptHeader" value="false"/>

        <property name="mediaTypes"> <!--擴展名到MIME的映射;favorPathExtension, favorParameter是true時起做用  -->
            <value>
                json=application/json
                xml=application/xml
                html=text/html
            </value>
        </property>
        <!-- 默認的content type -->
        <property name="defaultContentType" value="text/html"/>
    </bean>


    <!-- 當在web.xml 中   DispatcherServlet使用 <url-pattern>/</url-pattern> 映射時,能映射靜態資源 -->
    <mvc:default-servlet-handler />  
    <!-- 靜態資源映射 -->
    <mvc:resources mapping="/static/**" location="/WEB-INF/static/"/>
   

   <!-- 對模型視圖添加先後綴 -->
     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
      p:prefix="/WEB-INF/jsp/" p:suffix=".jsp"/>
      

</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
  <display-name>SSM-DEMO</display-name>
  <!-- 讀取spring配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    
    <!-- 設計路徑變量值 
    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>springmvc.root</param-value>
    </context-param>
    -->

    <!-- Spring字符集過濾器 -->
    <filter>
        <filter-name>SpringEncodingFilter</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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>SpringEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- 添加日誌監聽器 -->
    <context-param>
        <param-name>logbackConfigLocation</param-name>
        <param-value>classpath:logback.xml</param-value>
    </context-param>
    <listener>
        <listener-class>ch.qos.logback.ext.spring.web.LogbackConfigListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- springMVC核心配置 -->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <!--spingMVC的配置路徑 -->
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <!-- 攔截設置 -->
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

新增index.jsp文件

<%@ page contentType="text/html; charset=utf-8"%>
<!doctype html>
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>

6.啓動web服務,測試
將上面的項目添加到Tomcat中,啓動,控制檯沒有報錯,並在地址欄訪問,http://localhost:8080/ssm。頁面顯示 Hello World! 項目配置ok!

7:編寫Controller,和對應得業務界面
新增UserController ,經過參數傳遞uid獲取用戶,若用戶存在,跳轉到showName.jsp ,若用戶不存在,則跳轉到error.jsp,並返回提示信息!

package org.ssm.dufy.web;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.ssm.dufy.entity.User;
import org.ssm.dufy.service.IUserService;

@Controller
public class UserController {

    @Autowired
    private IUserService userService;
    
    @RequestMapping(value="/showname",method=RequestMethod.GET)
    public String showUserName(@RequestParam("uid") int uid,HttpServletRequest request,Model model){
        System.out.println("showname");
        User user = userService.getUserById(uid);
        if(user != null){
            request.setAttribute("name", user.getUserName());
            model.addAttribute("mame", user.getUserName());
            return "showName";
        }
        request.setAttribute("error", "沒有找到該用戶!");
        return "error";
    }
}

Jsp內容以下:

showName.jsp

<%@ page contentType="text/html; charset=utf-8"%>
<!doctype html>
<html>
<head>
    <title>show name</title>
</head>
<body>
    <h1>Welcome</h1> ${name }<h1>訪問此頁面</h1>

</body>
</html>

error.jsp

<%@ page contentType="text/html; charset=utf-8"%>
<!doctype html>
<html>
<head>
    <title>error page</title>
</head>
<body>
    <h2> ${error } </h2>

</body>
</html>

三:遇到的問題

1:找不到UserService,報錯

多是包掃描路徑的問題,檢查一下Service是否在掃描的範圍內

2:jsp接收不到request.setAttribute("","");內容

查資料說是由於 JSP的版本問題,能夠在Jsp 上面添加 <%@ page isELIgnored="false" %>
或者修改web.xml ,添加version版本!

<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    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" metadata-complete="true">

四:心得總結
或許這些都是站在別人的基礎的搭建的,可是看一篇SSM的搭建文章可能很快,看完以爲本身懂了,可是我建議必定要本身去搭建一次,看一遍,和動手作一遍徹底是兩個概念!

五:參考文章

SSM框架——詳細整合教程(Spring+SpringMVC+MyBatis)

Mybatis3.x與Spring4.x整合

附:
項目源代碼
https://github.com/dufyun/learn-tech-collection/tree/master/ssm
----------
歡迎訪問個人csdn博客,咱們一同成長!

"無論作什麼,只要堅持下去就會看到不同!在路上,不卑不亢!"
http://blog.csdn.net/u010648555

相關文章
相關標籤/搜索