1. 程式人生 > >SSM第一篇 最簡單的SSM框架搭建過程--SSM簡單整合

SSM第一篇 最簡單的SSM框架搭建過程--SSM簡單整合

         SSMSpringSpring MVCMybatis)是什麼我想也不用在贅述。

許多童鞋現在開始學習這個流行的框架來進行Java開發,想要尋找一個最簡單的SSM框架搭建方法,這裡我不說什麼廢話,直接上手開始搭建,程式碼部分都做了詳細的註釋,可以快速上手!

建立Java Web專案

這裡博主用到的開發工具是IntelliJ IDEA,專案建立可能和eclipse和myeclipse有所不同,按照自己的需要來建立就好,用什麼IDE就按照什麼步驟來建立。

以下是完整目錄結構,不論什麼IDE都可以是這種結構,具體內容看圖:

 

匯入jar包

因為我們不採用maven的方式配置jar包,所以需要我們手動匯入jar檔案。這一步就不再多說,以下會和原始碼一同給出。


配置檔案


      這裡我們分別將Spring 和 Mybatis的配置檔案放在兩個資料夾中,Spring的有applicationContext.xml和applicationContext-mvc.xml,Mybatis的有mybatis-config.xml。

Mybatis配置檔案

Mybatis的配置檔案就是mybatis-config.xml,主要是配置typeAlias,將實體類匹配成XXXMapper.xml中可以直接使用的型別,相當於一個別名,在XXXMapper.xml中就無需再寫完整的實體類全路徑,直接用alias的值來代替。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD SQL Map Config 3.0//EN"
                "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
<!--之後用於測試-->
        <typeAlias type="com.javafeng.entity.User" alias="User" />
    </typeAliases>
</configuration>

其中的XXXMapper.xml當然就是Mybatis動態實現所需要的Mapper檔案,Dao介面就可以不用再編寫實現類。這裡的Mapper和Dao中的介面是對應的,再接下來的測試中我們會給出具體的配置。

Spring配置檔案

applicationContext.xml

      在這個配置檔案中,我們主要配置資料來源,Spring的事務管理和Dao介面的掃描,以及對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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!--資料來源-連結資料庫的基本資訊,這裡直接寫,不放到*.properties資原始檔中-->
    <bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/javafeng" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean>
    <!-- 配置資料來源,載入配置,也就是dataSource -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <!--mybatis的配置檔案-->
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
        <!--掃描 XXXmapper.xml對映檔案,配置掃描的路徑-->
        <property name="mapperLocations" value="classpath:com/javafeng/mapping/*.xml"></property>
    </bean>
    <!-- DAO介面所在包名,Spring會自動查詢之中的類 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.javafeng.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

    <!--事務管理-->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入dataSource-->
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!--開啟事務註解掃描-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>
applicationContext-mvc.xml

      這個配置檔案中我們主要啟用Sping註解驅動,進行靜態資源的配置,註解掃描配置和檢視解析器配置.

<?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.xsd">

    <!-- 告知Spring,我們啟用註解驅動 -->
    <mvc:annotation-driven/>
    <!-- org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler,
    它會像一個檢查員,對進入DispatcherServlet的URL進行篩查,如果發現是靜態資源的請求,
    就將該請求轉由Web應用伺服器預設的Servlet處理,如果不是靜態資源的請求,才由DispatcherServlet繼續處理。 -->
    <mvc:default-servlet-handler/>
    <!-- 指定要掃描的包的位置 -->
    <context:component-scan base-package="com.javafeng" />
    <!-- 對靜態資原始檔的訪問,因為Spring MVC會攔截所有請求,導致jsp頁面中對js和CSS的引用也被攔截,配置後可以把對資源的請求交給專案的
    預設攔截器而不是Spring MVC-->
    <mvc:resources mapping="/static/**" location="/WEB-INF/static/" />

    <!-- 配置Spring MVC的檢視解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 有時我們需要訪問JSP頁面,可理解為在控制器controller的返回值加字首和字尾,變成一個可用的URL地址 -->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

web.xml

      我們在web.xml中載入Spring配置,並且將所有的請求都過濾給Spring MVC來處理,同時設定編碼過濾器解決編碼問題(最後一項可以不配置)。

      其中Spring MVC的請求過濾就是一個簡單的Servlet配置。

<?xml version="1.0" encoding="UTF-8"?>
<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">
    <!-- 載入Spring容器配置 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- Spring容器載入所有的配置檔案的路徑 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:spring/applicationContext.xml</param-value>
    </context-param>
    <!-- 配置SpringMVC核心控制器,將所有的請求(除了剛剛Spring MVC中的靜態資源請求)都交給Spring MVC -->
    <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/applicationContext-mvc.xml</param-value>
        </init-param>
        <!--用來標記是否在專案啟動時就加在此Servlet,0或正數表示容器在應用啟動時就載入這個Servlet,
        當是一個負數時或者沒有指定時,則指示容器在該servlet被選擇時才載入.正數值越小啟動優先值越高  -->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <!--為DispatcherServlet建立對映-->
    <servlet-mapping>
        <servlet-name>springMvc</servlet-name>
        <!-- 攔截所有請求,千萬注意是(/)而不是(/*) -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- 設定編碼過濾器 -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

到這裡我們的框架基本上就成形了,接下來可以進行簡單的測試。

測試

接下來就是應用例項,我會在文章結尾給出原始碼下載地址。

我們在資料庫新建如下表(我的資料庫名為javafeng,用的MySql):

CREATE TABLE `user` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `Name` varchar(255) DEFAULT NULL,
  `Age` int(11) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

這裡我們用逆向工程來生成實體類,Dao介面和對應的Mapper檔案,具體方法參考:

(版權歸原作者所有),逆向工程的工具同程式碼一併奉上。我在裡面分別添加了可以查詢表內全部資料的程式碼。

實體類User.java      

package com.javafeng.entity;

public class User {
    private Integer id;

    private String name;

    private Integer age;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

Mapper檔案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介面的全路徑-->
<mapper namespace="com.javafeng.dao.IUserDao" >
  <!--如下type的User就是mybatis-config.xml中配置的user-->
  <resultMap id="BaseResultMap" type="User" >
    <id column="ID" property="id" jdbcType="INTEGER" />
    <result column="Name" property="name" jdbcType="VARCHAR" />
    <result column="Age" property="age" jdbcType="INTEGER" />
  </resultMap>
<!--自己配置的查詢表所有資料的sql-->
  <select id="selectAllUser" resultType="User">
    select * FROM USER;
  </select>


  <sql id="Base_Column_List" >
    ID, Name, Age
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from user
    where ID = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from user
    where ID = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="User" >
    insert into user (ID, Name, Age
      )
    values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}
      )
  </insert>
  <insert id="insertSelective" parameterType="User" >
    insert into user
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        ID,
      </if>
      <if test="name != null" >
        Name,
      </if>
      <if test="age != null" >
        Age,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      </if>
      <if test="name != null" >
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="age != null" >
        #{age,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="User" >
    update user
    <set >
      <if test="name != null" >
        Name = #{name,jdbcType=VARCHAR},
      </if>
      <if test="age != null" >
        Age = #{age,jdbcType=INTEGER},
      </if>
    </set>
    where ID = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="User" >
    update user
    set Name = #{name,jdbcType=VARCHAR},
      Age = #{age,jdbcType=INTEGER}
    where ID = #{id,jdbcType=INTEGER}
  </update>
</mapper>

Dao層介面IUserDao.java,生成時為UserMapper.java,我這裡進行了重新命名,注意一定要記得同時修改Mapper檔案中的namespace:
package com.javafeng.dao;

import com.javafeng.entity.User;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("userDao")
public interface IUserDao {
    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
    //自己新增的,已匹配Mapper中的Sql
    List<User> selectAllUser();
}

       接下來是Service層介面UserService.java:

package com.javafeng.service;

import com.javafeng.entity.User;
import java.util.List;

public interface UserSercice {
    public List<User> getUser();
}

       Service介面實現類UserServiceImpl.java

package com.javafeng.service.impl;

import com.javafeng.dao.IUserDao;
import com.javafeng.entity.User;
import com.javafeng.service.UserSercice;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service("userService")
public class UserServiceImpl implements UserSercice{

    @Resource(name = "userDao")
    private IUserDao userDao;

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

       控制器UserController.java

package com.javafeng.controller;

import com.javafeng.entity.User;
import com.javafeng.service.UserSercice;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping(value = "/user")
public class UserController {
    @Resource(name = "userService")
    UserSercice userService;

    @RequestMapping(value = "/list")
    public ModelAndView list()
    {
        ModelAndView mv=new ModelAndView();
        List<User>  userList=userService.getUser();
        mv.addObject("userList",userList);
        mv.setViewName("/show");
        return mv;
    }

}

我們要做的就是把這個表的資料顯示在一個Jsp頁面上,所以在WEB-INF/jsp下新建一個show.jsp來顯示資料

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: 13926
  Date: 2017/7/18
  Time: 23:07
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<table border="1">
    <tr>
        <td>序號</td>
        <td>姓名</td>
        <td>年齡</td>
    </tr>
        <c:choose>
            <c:when test="${not empty userList}">
                <c:forEach items="${userList}" var="user" varStatus="vs">
                    <tr>
                        <td>${user.id}</td>
                        <td>${user.name}</td>
                        <td>${user.age}</td>
                    </tr>
                </c:forEach>
            </c:when>
            <c:otherwise>
               <tr>
                   <td colspan="2">無資料!</td>
               </tr>
            </c:otherwise>
        </c:choose>
</table>
</body>
</html>

我們在index.html中做如下更改來使專案啟動時自動訪問user/list路徑(其實就是懶得每次都輸這個地址,因為測試時大多數時候都不是一次就成)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <jsp:forward page="/user/list"/>
  </body>
</html>

       專案部署不用多講,直接釋出到Tomcat伺服器即可,因為已經才index.html做了修改,所以已不需要在位址列輸可惡的user/list路徑了,直接http://localhost:8080/SSMDemoByIdea

       這樣我們就能把User表的資料顯示在show.jsp了。


       到這裡我們的SSM框架搭建算是圓滿完成,要是你還在報錯中,恭喜,你可以接著繼續除錯了!

注意

0.     無論是註解的掃描還是配置檔案的掃描,路徑千萬要寫對,路徑千萬要寫對,路徑千萬要寫對

1.     再寫MapperDao介面時,一定要對應上,否則

Invalid bound statement (not found)
3.     Mapper在自動生成後,一定要按照自己專案的內容進行修改,比如namespace要和Dao介面對應,以及其中parameterType,resultType所對應的型別時你mybatis-config.xml中配置為alias值等等等等,總之千萬要注意!

檔案下載地址