1. 程式人生 > >使用IDEA整合SSM框架

使用IDEA整合SSM框架

一、安裝環境和開發工具

在整合Spring,SpringMVCMyBatis 的過程中,很容易遇到一些小問題,因此記錄下整合過程。

首先是安裝環境和開發工具,如下:

  • Window 7
  • Jdk 1.8
  • MySql 8.0
  • Maven 3.5.4
  • Tomcat 8.5.34
  • IntelliJ IDEA 2018

二、整體專案結構

整個專案在Maven WebApp模板工程的基礎上構建,不同型別的檔案放置於不同的包或者路徑下,全部配置完成後的工程結構如下圖所示:

不同路徑下的檔案歸類說明如下表(classpath相當於resources資料夾):

包名/路徑名 作用
controller 存放控制器
mapper DAO層介面
pojo 實體類
service 業務類(介面+實現)
/com/cr/mapper 對應mapper下介面的xml檔案
/spring 與spring相關的配置檔案
/webapp/jsp 存放jsp檔案
/*.properties 資原始檔

三、配置步驟

1、新增Maven依賴

  • 新建一個Maven WebApp工程,在pom.xml新增依賴,主要包括spring、springmvc、 mybatis、mybatis-spring 、servlet 、mysql 等項的jar包。

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.cr</groupId>
  <artifactId>SSMTest</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>SSMTest Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <spring.version>5.0.8.RELEASE</spring.version>
    <jackson.version>2.9.3</jackson.version>
  </properties>

  <dependencies>
    <!--新增Spring MVC的依賴-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!--新增Servlet的依賴-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
    <!--JSTL用於在控制器中將模型繫結到JSP中-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <!--新增spring的依賴-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</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-aspects</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-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!--利用它處理事務問題-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!--新增資料庫Mysql驅動-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <!--驅動版本號一定要裝正確 否則連不上 mysql 5.1.46 可以適用本機-->
      <version>5.1.46</version>
    </dependency>

    <!--新增Mybatis依賴-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.2.6</version>
    </dependency>

    <!--整合Mybatis與Spring的依賴-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>
    <!-- Mybatis分頁依賴 -->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.1.2</version>
    </dependency>
    <!-- 處理時間日期格式 -->
    <dependency>
      <groupId>joda-time</groupId>
      <artifactId>joda-time</artifactId>
      <version>2.9.9</version>
    </dependency>
    <!-- 用於MD5加密 -->
    <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
      <version>1.10</version>
    </dependency>

    <!--日誌-->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.12</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.12</version>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>


    <!--新增Json依賴-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>${jackson.version}</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>${jackson.version}</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>${jackson.version}</version>
    </dependency>
    <!--有時候不加可能會報錯-->
    <dependency>
      <groupId>net.sf.json-lib</groupId>
      <artifactId>json-lib</artifactId>
      <version>2.4</version>
      <classifier>jdk15</classifier>
    </dependency>

    <!-- 新新增處理json為java bean -->
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-core-asl</artifactId>
      <version>1.9.13</version>
    </dependency>
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-mapper-asl</artifactId>
      <version>1.9.13</version>
    </dependency>
    <!-- 檔案上傳 高版本可以使用Multipart解析器 就不用引入這個包了 -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>
    <!-- 資料來源的引入, 池化技術 -->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.2.1</version>
    </dependency>
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.2.2</version>
    </dependency>

  </dependencies>

  <build>
    <finalName>SSMTest</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.7.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.20.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

新增完成後的maven依賴如下:

2、配置web.xml

  • spring上下文檔案路徑配置

    <!--配置Spring IoC的配置檔案路徑 classpath相當於resources資料夾-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/applicationContext.xml</param-value>
    </context-param>

    這裡指定了上下文配置檔案為spring資料夾下的applicationContext.xml,稍後再配置這個檔案。

  • Log4j配置

    <context-param>
        <param-name>log4jRefreshInterval</param-name>
        <param-value>60000</param-value>
    </context-param>
  • ContextLoaderListener監聽器配置

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- 防止Spring記憶體溢位監聽器 -->
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>
  • DispatcherServlet前置控制器配置

    <servlet>
        <!--springmvc框架預設自動找到/WEB-INF/springmvc-servlet.xml作為配置檔案載入web工程中 這裡手動設定位置-->
        <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/springmvc-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>

    springmvc框架預設自動找到/WEB-INF/[servlet-name]-servlet.xml作為配置檔案載入web工程中 這裡手動設定位置為spring資料夾下的springmvc-servlet.xml,稍後再配置這個檔案。

  • Servlet攔截設定

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         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配置 -->
    <!-- ================================================= -->
    <!--配置Spring IoC的配置檔案路徑 classpath相當於resources資料夾-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/applicationContext.xml</param-value>
    </context-param>
    <!--Log4j配置-->
    <context-param>
        <param-name>log4jRefreshInterval</param-name>
        <param-value>60000</param-value>
    </context-param>
    <!--配置ContextLoaderListener初始化IOC容器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- 防止Spring記憶體溢位監聽器 -->
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>

    <!-- Spring mvc配置 -->
    <!-- ================================================= -->
    <!--DispatcherServlet前置控制器配置-->
    <servlet>
        <!--springmvc框架預設自動找到/WEB-INF/springmvc-servlet.xml作為配置檔案載入web工程中 這裡手動設定位置-->
        <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/springmvc-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>
    <!--攔截內容:servlet對映設定-->
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

3、applicationContext.xml配置

  • 在spring資料夾下建立applicationContext.xml

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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--引入spring和其他整合的配置檔案 比如spring-mybatis.xml等-->
    <import resource="classpath:spring/spring-*.xml"/>

</beans>
  • 這裡引入spring和其他整合的配置檔案 比如spring-mybatis.xml等,接下來在spring資料夾下新建一個spring-mybatis.xml檔案

4、spring-mybatis.xml配置

  • 配置自動掃描,需要掃描到控制層服務層,剛開始我這裡寫成了com.cr.mapper,結果導致控制器不能注入

    <context:component-scan base-package="com.cr" />
  • 新建資料庫資原始檔jdbc.properties,針對不同的資料庫需要修改配置 同時要注意匹配資料庫的版本號,比如我安裝的是MySQL 8.0,之前由於驅動版本弄錯了,所以總是連線資料庫失敗,後來改成5.1.46才解決了問題

    # 針對不同的資料庫需要修改配置 同時要注意匹配資料庫的版本號
    mysql.driver=com.mysql.jdbc.Driver
    mysql.url=jdbc:mysql://localhost:3306/mybatis
    mysql.username=root
    mysql.password=XXXX
    
    #定義初始連線數
    dbcp.initialSize=0
    #定義最大連線數
    dbcp.maxActive=20
    #定義最大空閒
    dbcp.maxIdle=20
    #定義最小空閒
    dbcp.minIdle=1
    #定義最長等待時間
    dbcp.maxWait=60000
  • 引入資料庫資原始檔

    <bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties" />
    </bean>
  • 配置資料庫MySQL

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${mysql.driver}" />
        <property name="url" value="${mysql.url}" />
        <property name="username" value="${mysql.username}" />
        <property name="password" value="${mysql.password}" />
    
    
        <property name="initialSize" value="${dbcp.initialSize}" />
        <property name="maxActive" value="${dbcp.maxActive}" />
        <property name="maxIdle" value="${dbcp.maxIdle}" />
        <property name="minIdle" value="${dbcp.minIdle}" />
        <property name="maxWait" value="${dbcp.maxWait}" />
    </bean>
  • 整合Spring和MyBatis,注意路徑的書寫方式是"/"不是"."

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 自動掃描mapping.xml檔案 注意路徑是"/"不是"."-->
        <property name="mapperLocations" value="classpath:com/cr/mapper/*.xml" />
        <property name="configuration">
            <!--可以將之前mybatis.cfg.xml的一些配置項轉移到這裡來-->
            <bean class="org.apache.ibatis.session.Configuration">
                <property name="mapUnderscoreToCamelCase" value="true" />
            </bean>
        </property>
    </bean>
  • 掃描持久層介面

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.cr.mapper" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>
  • 資料庫事務管理

    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

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"
       xmlns:tx="http://www.springframework.org/schema/cache"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/aop
                        http://www.springframework.org/schema/aop/spring-aop.xsd
                        http://www.springframework.org/schema/tx
                        http://www.springframework.org/schema/tx/spring-tx.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc.xsd
                        http://www.springframework.org/schema/cache
                        http://www.springframework.org/schema/cache/spring-cache.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 自動掃描包 包括了控制層和服務層 -->
    <context:component-scan base-package="com.cr" />
    <!-- 引入資料庫配置檔案 -->
    <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">
        <property name="driverClassName" value="${mysql.driver}" />
        <property name="url" value="${mysql.url}" />
        <property name="username" value="${mysql.username}" />
        <property name="password" value="${mysql.password}" />


        <property name="initialSize" value="${dbcp.initialSize}" />
        <property name="maxActive" value="${dbcp.maxActive}" />
        <property name="maxIdle" value="${dbcp.maxIdle}" />
        <property name="minIdle" value="${dbcp.minIdle}" />
        <property name="maxWait" value="${dbcp.maxWait}" />
    </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/cr/mapper/*.xml" />
        <property name="configuration">
            <!--可以將之前mybatis.cfg.xml的一些配置項轉移到這裡來-->
            <bean class="org.apache.ibatis.session.Configuration">
                <property name="mapUnderscoreToCamelCase" value="true" />
            </bean>
        </property>
    </bean>

    <!-- 掃描DAO持久層介面 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.cr.mapper" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>

    <!-- 資料庫事務管理 -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
</beans>

5、springmvc-servlet.xml配置

springmvc-servlet.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-4.1.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

    <!-- scan the package and the sub package -->
    <context:component-scan base-package="com.cr.controller"/>
    <!-- don't handle the static resource -->
    <mvc:default-servlet-handler />

    <!-- if you use annotation you must configure following setting -->
    <mvc:annotation-driven />

    <!-- configure the InternalResourceViewResolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          id="internalResourceViewResolver">
        <!--相當於尋找/jsp/xxx.jsp檔案-->
        <!-- 字首 -->
        <property name="prefix" value="/jsp/" />
        <!-- 字尾 -->
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

6、建立實體類

  • 在pojo包下新建一個實體User類,包含使用者名稱username 和 密碼password 欄位,alt + insert 生成 setter和getter方法

User.java

package com.cr.pojo;


public class User {
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

7、DAO層建立

  • 建立測試用表t_user,並新增兩條資料

  • 在mapper包下新建一個UserMapper介面,包含一個select查詢方法,可以查詢使用者是否存在,若不存在返回null

    UserMapper.java

    package com.cr.mapper;
    
    import com.cr.pojo.User;
    
    public interface UserMapper {
        User select(User user);
    }
  • 建立UserMapper和mybatis對映檔案 UserMapper.xml,路徑是resource/com/cr/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" >
    <mapper namespace="com.cr.mapper.UserMapper">
        <select id="select" parameterType="com.cr.pojo.User" resultType="com.cr.pojo.User">
            select * from t_user
            where username = #{username}
            and password = #{password}
        </select>
    </mapper>

8、服務層建立

  • 建立UserService介面,位於service包下

    UserService.java

    package com.cr.service;
    
    import com.cr.pojo.User;
    
    public interface UserService {
        /**
         * 根據user資訊檢查資料庫中是否存在該使用者
         */
        User get(User user);
    }
  • 在service包下建立impl子包,新增實現類UserServiceImpl

    UserServiceImpl.java

    package com.cr.service.impl;
    
    import com.cr.mapper.UserMapper;
    import com.cr.pojo.User;
    import com.cr.service.UserService;
    import org.springframework.stereotype.Service;
    
    import javax.annotation.Resource;
    // @Service用於業務層 功能等同於@component
    @Service("userService")
    public class UserServiceImpl implements UserService {
        @Resource
        private UserMapper userMapper;
    
        @Override
        public User get(User user) {
            // 通過Mapper的select方法查詢使用者
            return userMapper.select(user);
        }
    }

9、建立控制器

  • 在controller包下建立控制器UserController,根據表單的使用者名稱和密碼,在資料中匹配,如果存在該使用者,則跳轉到登入成功介面user.jsp,如果使用者不存在則返回null,重定向回登入介面,以便於重新登入。

UserController.java

package com.cr.controller;

import com.cr.pojo.User;
import com.cr.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
// spring-mybatis.xml和springmvc-servlet.xml都配置了掃描控制層
@Controller
public class UserController {
    // 注入UserService
    @Resource
    private UserService userService;

    @RequestMapping(value = "/login")
    public String login(User user) {
        ModelAndView mv = new ModelAndView();
        System.out.println("開始查詢---");
        user = userService.get(user);

        if (user != null) {
            System.out.println("查到的User: " + user.getUsername());
            mv.addObject("user", user);
            // 轉到user.jsp使用者介面
            return "user";
        } else {
            System.out.println("未查到此使用者");
            // 查不到使用者資訊,則重定向回登入介面
            System.out.println("重定向回登入介面---");
            return "login";
        }
    }
}

10、建立Jsp頁面

login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>login</title>
</head>
<body>
<h1>使用者登入介面</h1>
<h2>使用者資訊</h2>
<h3>Tom  123</h3>
<h3>Jack 456</h3>
<br>
<form id="form" action="/login" method="post">
    <table>
        <tr>
            <td>使用者名稱</td>
            <td><input id="username" name="username" value="" /></td>
        </tr>
        <tr>
            <td>密碼</td>
            <td><input id="password-always-checkbox" name="password" /></td>
        </tr>
        <tr>
            <td></td>
            <td align="right"><input type="submit" value="提交"></td>
        </tr>
    </table>
</form>

</body>
</html>

user.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>User</title>
</head>
<body>
<h1>使用者登入成功</h1>
<br>
歡迎您: ${user}
</body>
</html>

四、部署專案

1、Tomcat配置

2、啟動伺服器

  • 瀏覽器訪問http://localhost:8080/login

  • 填寫錯誤的使用者名稱或者密碼,瀏覽器將重新返回登入介面,控制檯顯示如下:

  • 填寫正確的使用者名稱Tom和密碼123,跳轉到登入成功介面user.jsp,顯示如下:

  • 以上說明SSM框架整合成功,專案地址:https://github.com/wychencr/SSM-Test

五、一些注意事項

  • MySQL的驅動要匹配本機安裝的版本

  • resources資料夾要被標記為Resource Root

  • xml配置檔案中的classpath相當於/resources

  • IDEA可能會提示上下文配置檔案沒有新增,只要開啟工程結構選項,把當前xml檔案新增到工程中即可

  • 注意各個xml配置檔案中掃描包的位置,如果有遺漏就會報錯

  • 注意各個jar包的版本問題,我原來使用最新的Mybatis 3.4.6就會出現報錯

    java.lang.IllegalAccessError: org.apache.commons.dbcp.DelegatingPreparedStatement.isClosed()

    修改版本為3.2.6後解決問題

歡迎訪問我的個人部落格: https://chenran.tk/