Spirng+SpringMVC+Maven+Mybatis+MySQL專案搭建

小寶鴿發表於2015-12-22

這篇文章主要講解使用eclipse對Spirng+SpringMVC+Maven+Mybatis+MySQL專案搭建過程,包括裡面步驟和裡面的配置檔案如何配置等等都會詳細說明。

如果還沒有搭建好環境(主要是Maven+MySQL的配置)的猿友可以參考博主以前的一篇文章:
http://blog.csdn.net/u013142781/article/details/50300233

接下來馬上進入專案搭建過程:

1、建立表,並插入資料:

CREATE TABLE `t_user` (
  `USER_ID` int(11) NOT NULL AUTO_INCREMENT,
  `USER_NAME` char(30) NOT NULL,
  `USER_PASSWORD` char(10) NOT NULL,
  PRIMARY KEY (`USER_ID`),
  KEY `IDX_NAME` (`USER_NAME`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD) VALUES (1, 'luoguohui', '123456');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD) VALUES (2, 'zhangsan', '123456');

2、Maven工程建立

這裡寫圖片描述

3、選擇快速框架

這裡寫圖片描述

4、輸出專案名,包(Packaging,如果只是普通的專案,選jar就好了,如果是web專案就選war,這裡是web專案,所以選擇war)

這裡寫圖片描述

5、建立好的目錄如下:

這裡寫圖片描述

6、新增包的依賴,編輯pom.xml檔案新增如下依賴:

<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.luo</groupId>
  <artifactId>first_maven_project</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

  <properties>
        <!-- spring版本號 -->
        <spring.version>3.2.8.RELEASE</spring.version>
        <!-- log4j日誌檔案管理包版本 -->
        <slf4j.version>1.6.6</slf4j.version>
        <log4j.version>1.2.12</log4j.version>
        <!-- junit版本號 -->
        <junit.version>4.10</junit.version>
        <!-- mybatis版本號 -->
        <mybatis.version>3.2.1</mybatis.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-webmvc</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>

        <!--單元測試依賴 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>

        <!-- 日誌檔案管理包 -->
        <!-- log 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>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <!-- log end -->

        <!--spring單元測試依賴 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </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>

        <!-- mysql驅動包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.29</version>
        </dependency>
    </dependencies>

</project>

7、配置檔案:

這裡寫圖片描述

7.1、mybatis包下新增mybatis-config.xml檔案(mybatis配置檔案):

<?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>    
</configuration>

7.2、properties包下新增jdbc.properties檔案(資料來源配置檔案):

jdbc_driverClassName=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/luo
jdbc_username=root
jdbc_password=root

7.3、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.luo.dao.UserDao">
<!--設定domain類和資料庫中表的欄位一一對應,注意資料庫欄位和domain類中的欄位名稱不致,此處一定要!-->
    <resultMap id="BaseResultMap" type="com.luo.domain.User">
        <id column="USER_ID" property="userId" jdbcType="INTEGER" />
        <result column="USER_NAME" property="userName" jdbcType="CHAR" />
        <result column="USER_PASSWORD" property="userPassword" jdbcType="CHAR" />
    </resultMap>
    <!-- 查詢單條記錄 -->
    <select id="selectUserById" parameterType="int" resultMap="BaseResultMap">
        SELECT * FROM t_user WHERE USER_ID = #{userId}
    </select>
</mapper>

7.4、spring配置檔案application.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"
    xsi:schemaLocation="  
           http://www.springframework.org/schema/beans  
           http://www.springframework.org/schema/beans/spring-beans-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/context  
           http://www.springframework.org/schema/context/spring-context-3.0.xsd">

     <!-- 引入jdbc配置檔案 -->  
     <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
               <value>classpath:properties/*.properties</value>
                <!--要是有多個配置檔案,只需在這裡繼續新增即可 -->
            </list>
        </property>
    </bean>



    <!-- 配置資料來源 -->
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <!-- 不使用properties來配置 -->
        <!-- <property name="driverClassName" value="com.mysql.jdbc.Driver" /> 
            <property name="url" value="jdbc:mysql://localhost:3306/learning" /> 
            <property name="username" value="root" /> 
            <property name="password" value="christmas258@" /> -->
       <!-- 使用properties來配置 -->
        <property name="driverClassName">
            <value>${jdbc_driverClassName}</value>
        </property>
        <property name="url">
            <value>${jdbc_url}</value>
        </property>
        <property name="username">
            <value>${jdbc_username}</value>
        </property>
        <property name="password">
            <value>${jdbc_password}</value>
        </property>
    </bean>

    <!-- 自動掃描了所有的XxxxMapper.xml對應的mapper介面檔案,這樣就不用一個一個手動配置Mpper的對映了,只要Mapper介面類和Mapper對映檔案對應起來就可以了。 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage"
            value="com.luo.dao" />
    </bean>

    <!-- 配置Mybatis的檔案 ,mapperLocations配置**Mapper.xml檔案位置,configLocation配置mybatis-config檔案位置-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>  
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
        <!-- <property name="typeAliasesPackage" value="com.tiantian.ckeditor.model" 
            /> -->
    </bean>

    <!-- 自動掃描註解的bean -->
    <context:component-scan base-package="com.luo.service" />

</beans>

8、介面和類的配置:

這裡寫圖片描述

8.1、com.luo.domain下新增User.java檔案:

package com.luo.domain;

public class User {

    private Integer userId;  
    private String userName;  
    private String userPassword;  


    public Integer getUserId() {  
        return userId;  
    }  

    public void setUserId(Integer userId) {  
        this.userId = userId;  
    }  

    public String getUserName() {  
        return userName;  
    }  

    public void setUserName(String userName) {  
        this.userName = userName;  
    }  

    public String getUserPassword() {  
        return userPassword;  
    }  

    public void setUserPassword(String userPassword) {  
        this.userPassword = userPassword;  
    }  

}

8.2、com.luo.dao下新增UserDao.java檔案:

package com.luo.dao;

import com.luo.domain.User;

public interface UserDao {

    /**
     * @param userId
     * @return User
     */
    public User selectUserById(Integer userId);  

}

8.3、com.luo.service下新增UserService.java介面和UserServiceImpl實現類:

package com.luo.service;

import com.luo.domain.User;

public interface UserService {
    User selectUserById(Integer userId);  
}
package com.luo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.luo.dao.UserDao;
import com.luo.domain.User;

@Service  
public class UserServiceImpl implements UserService {

    @Autowired  
    private UserDao userDao;  

    public User selectUserById(Integer userId) {  
        return userDao.selectUserById(userId);  

    }  
}

9、單元測試

這裡寫圖片描述

9.1、com.luo.baseTest下新增SpringTestCase.java:

package com.luo.baseTest;

import org.junit.runner.RunWith;  
import org.springframework.test.context.ContextConfiguration;  
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;  
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  

//指定bean注入的配置檔案  
@ContextConfiguration(locations = { "classpath:application.xml" })  
//使用標準的JUnit @RunWith註釋來告訴JUnit使用Spring TestRunner  
@RunWith(SpringJUnit4ClassRunner.class)  
public class SpringTestCase extends AbstractJUnit4SpringContextTests {

}

9.2、com.luo.service新增UserServiceTest.java:

package com.luo.service;

import org.junit.Test;  
import org.springframework.beans.factory.annotation.Autowired;  
import com.luo.baseTest.SpringTestCase;  
import com.luo.domain.User;

public class UserServiceTest extends SpringTestCase {

    @Autowired  
    private UserService userService; 

    @Test  
    public void selectUserByIdTest(){  
        User user = userService.selectUserById(1);  
        System.out.println(user.getUserName() + ":" + user.getUserPassword());
    }  
}

9.3、執行單元測試,UserServiceTest右鍵Run As –>Junit Test,執行結果:

這裡寫圖片描述


下面加入springmvc,並轉換maven工程為web專案


10、轉換成web專案:

如果上面webapp為空的,說明這個專案還不是web專案:

這裡寫圖片描述

接下來開啟如下頁面。將紅框裡面的勾去掉,確定(OK):

這裡寫圖片描述

然後重新開啟剛剛那個頁面,把Dynamic web Module勾上,就會看到紅框的內容,點選:

這裡寫圖片描述

然後配置如下:

這裡寫圖片描述

那麼webapp下就會生成這些東西:

這裡寫圖片描述

11、配置springmvc

11.1、pom.xml檔案新增依賴,修改後配置如下:

<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.luo</groupId>
  <artifactId>first_maven_project</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

  <properties>
        <!-- spring版本號 -->
        <spring.version>3.2.8.RELEASE</spring.version>
        <!-- junit版本號 -->
        <junit.version>4.10</junit.version>
        <!-- mybatis版本號 -->
        <mybatis.version>3.2.1</mybatis.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-webmvc</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>

        <!--單元測試依賴 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>

        <!--spring單元測試依賴 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </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>

        <!-- mysql驅動包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.29</version>
        </dependency>

        <!-- javaee-api包 注意和專案使用的JDK版本對應 -->  
        <dependency>  
            <groupId>javax</groupId>  
            <artifactId>javaee-api</artifactId>  
            <version>6.0</version>  
            <scope>provided</scope>  
        </dependency>  

        <!-- javaee-web-api包 注意和專案使用的JDK版本對應 -->  
        <dependency>  
            <groupId>javax</groupId>  
            <artifactId>javaee-web-api</artifactId>  
            <version>6.0</version>  
            <scope>provided</scope>  
        </dependency>  

    </dependencies>

</project>

其實也就增加了下面兩個

<!-- javaee-api包 注意和專案使用的JDK版本對應 -->
<dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>6.0</version>
    <scope>provided</scope>
</dependency>

<!-- javaee-web-api包 注意和專案使用的JDK版本對應 -->
<dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-web-api</artifactId>
    <version>6.0</version>
    <scope>provided</scope>
</dependency>

11.2、在src/main/resource中新增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">

   <mvc:annotation-driven /> 
   <!-- 掃描controller(controller層注入) -->
   <context:component-scan base-package="com.luo.controller"/>  

   <!-- 對模型檢視新增前字尾 -->
   <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
      p:prefix="/WEB-INF/view/" p:suffix=".jsp"/>
</beans>

11.3、配置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" 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_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>Archetype Created Web Application</display-name>
   <!-- 起始歡迎介面 -->
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <!-- 讀取spring配置檔案 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:application.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>

    <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:springmvc/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>

    <!-- 錯誤跳轉頁面 -->
    <error-page>
        <!-- 路徑不正確 -->
        <error-code>404</error-code>
        <location>/WEB-INF/errorpage/404.jsp</location>
    </error-page>
    <error-page>
        <!-- 沒有訪問許可權,訪問被禁止 -->
        <error-code>405</error-code>
        <location>/WEB-INF/errorpage/405.jsp</location>
    </error-page>
    <error-page>
        <!-- 內部錯誤 -->
        <error-code>500</error-code>
        <location>/WEB-INF/errorpage/500.jsp</location>
    </error-page>
</web-app>

11.4、新增index.jsp,在src/main/webapp/WEB-INF下新建一個資料夾view,新增一個index.jsp,內容如下:

這裡寫圖片描述

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<body>
<h2>Hello World!</h2>
使用者名稱: ${user.userName}<br>
 密碼:${user.userPassword}<br>
</body>
</html>

11.5、寫controller

這裡寫圖片描述

在src/main/java下新建一個包com.luo.controller.然後新建一個類UserController.java,其內容如下

package com.luo.controller;

import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.luo.domain.User;
import com.luo.service.UserService;

@Controller  
public class UserController {  

    @Resource  
    private UserService userService;  

    @RequestMapping("/")    
    public ModelAndView getIndex(){      
        ModelAndView mav = new ModelAndView("index");   
        User user = userService.selectUserById(1);  
        mav.addObject("user", user);   
        return mav;    
    }    
}  

11.6 執行!!!!完成!

這裡寫圖片描述

12、原始碼下載

http://download.csdn.net/detail/u013142781/9376381

13、可能會遇到的錯

之前有個兄弟按照我的配置,但是發現pom.xml檔案報如下錯誤:

Cannot detect Web Project version. Please specify version of Web Project through <version> configuration property of war plugin. E.g.: <plugin> <artifactId>maven-war-plugin</artifactId> <configuration> <version>3.0<ersion> </configuration> </plugin>

解決方案是,如下的三個地方jdk版本需要保持一致:

1、專案右鍵->屬性->Java Compiler:

這裡寫圖片描述

2、專案右鍵->屬性->Project Facets:

這裡寫圖片描述

3、如果pom.xml配置瞭如下的外掛的話:

<build>
 <plugins>
    <plugin>
      <artifactId>maven-compiler-plugin</artifactId>
      <configuration>
        <source>1.7</source>
        <target>1.7</target>
      </configuration>
    </plugin>
    <plugin>
      <artifactId>maven-war-plugin</artifactId>
      <version>2.4</version>
      <configuration>
        <version>3.0</version>
      </configuration>
    </plugin>
  </plugins>
  <finalName>webserver</finalName>
</build>

這裡也要跟上面兩個保持一致:

這裡寫圖片描述

相關文章