1. 程式人生 > >使用maven搭建SSM專案(spring+springmvc+Mybatis)

使用maven搭建SSM專案(spring+springmvc+Mybatis)

本文介紹使用eclipse+maven搭建Spring+SpringMvc+Mybatis專案,以登陸為例:
1、建立maven專案
2、把maven專案變為動態網站
3、搭建spring+springmvc+Mybatis專案


1 建立maven專案

2 把maven專案變為動態網站

3 開始搭建spring+springmvc+Mybatis專案

3.1 配置maven依賴,在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.welljoint</groupId> <artifactId>testSSM2</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <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> <!-- 引入資料庫連線池 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId> <version>1.6</version> </dependency> </dependencies> </project>

3.2 請檢查maven依賴是否匯入到專案中了

(可以不用檢查,如何報錯了再來看)
- 請點選檢視:http://blog.csdn.net/tiandixuanwuliang/article/details/79250504#t4

3.3 在src/main/java中新建一個com.welljoint.entity的包;在這個包裡新建一個User.java的bean

package com.welljoint.entity;
/** 
 * @version  
 * @describe:使用者的bean
 */
public class User {
    private Integer id;
    private String userName;
    private String password;

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    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;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", userName=" + userName + ", password="
                + password + "]";
    }
}

3.4 在WEB-INF目錄下建立一個view資料夾;在該資料夾裡建立一個login.jsp,程式碼如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登陸</title>
</head>
<body>
    <form method="post">
        使用者名稱:<input type="text" name="userName"><br>
        密碼:<input type="text" name="password"><br>
        <input type="submit" value="登陸">
    </form>
</body>
</html>
  • 再在view資料夾下建立一個login_success.jsp的頁面,程式碼如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登陸成功</title>
</head>
<body>
    登陸成功
</body>
</html>

3.5 在src/main/java中新建一個com.welljoint.rest的包;在這個包裡新建一個LoginController.java作為控制器

package com.welljoint.rest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.welljoint.entity.User;

/** 
 * @version  
 * @describe:控制器
 */
@Controller  //註解為控制器
@RequestMapping(value="/login")    //截獲帶有/login的請求
public class LoginController {

    @RequestMapping(method=RequestMethod.GET)
    public String get(){  //用來返回一個頁面
        return "login";  //返回指向login.jsp頁面
    }

    @RequestMapping(method=RequestMethod.POST)
    public String post(User user){  //用來處理使用者的登陸請求
        return "login_success";
    }
}

3.6 在src/main/resources中新建一個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.0.xsd
                        http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
                        http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">  

    <!-- 對web包中的所有類進行掃描,以完成Bean建立和自動依賴注入的功能 -->
    <context:component-scan base-package="com.welljoint" />

    <!-- 啟用基於註解的配置 @RequestMapping, @ExceptionHandler,資料繫結 ,@NumberFormat ,  
    @DateTimeFormat ,@Controller ,@Valid ,@RequestBody ,@ResponseBody等  -->  
    <mvc:annotation-driven />  

    <!-- 檢視層配置 -->  
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <!--配置JSTL表示式-->  
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>  
        <!-- 字首 -->
        <property name="prefix" value="/WEB-INF/view/"/>  
        <!-- 字尾 -->
        <property name="suffix" value=".jsp"/>  
    </bean>  

    <!-- 配置靜態資源 -->
    <mvc:resources location="/res/" mapping="/res/**"/>  
</beans>  

3.7 配置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_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>testSSM2</display-name>

    <!-- 請求都交給DispatcherServlet處理 -->
    <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>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- 增加中文亂碼過濾器 -->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- 清除jsp空格 -->
    <jsp-config>
        <jsp-property-group>
            <url-pattern>*.jsp</url-pattern>
            <trim-directive-whitespaces>true</trim-directive-whitespaces>
        </jsp-property-group>
    </jsp-config>
</web-app>
  • 如果你是按照上述一步步做的話,已經可以執行看效果了,效果圖如下:
    這裡寫圖片描述
  • 任意輸入點選登陸後,如下圖:
    這裡寫圖片描述

3.8 寫service層:在src/main/java中新建一個com.welljoint.service的包;在這個包裡新建一個LoginService.java作為服務層的介面

package com.welljoint.service;

public interface LoginService {
    public int login(String userName,String password);
}
  • 再在com.welljoint.service包中新建一個LoginServiceImpl.java作為服務層介面的實現
package com.welljoint.service;

import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements LoginService{
    public int login(String userName,String password){
        return 1;
    }
}
  • 此時就可以把service層注入到controller層來發揮作用了,把LoginController.java修改為如下:
package com.welljoint.rest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.welljoint.entity.User;
import com.welljoint.service.LoginService;

/** 
 * @version  
 * @time 2018-3-8 下午4:17:37 
 * @describe:控制器
 */
@Controller  //註解為控制器
@RequestMapping(value="/login")    //截獲帶有/login的請求
public class LoginController {

    @Autowired
    LoginService loginService;  //注入service層

    @RequestMapping(method=RequestMethod.GET)
    public String get(){  //用來返回一個頁面
        return "login";  //返回指向login.jsp頁面
    }

    @RequestMapping(method=RequestMethod.POST)
    public String post(User user){  //用來處理使用者的登陸請求
        if (loginService.login(user.getUserName(), user.getPassword())==1) {
            return "login_success";  //登陸成功,跳轉到login_success.jsp頁面
        }
        return "login";
    }
}
  • 把專案執行起來,如果效果和之前的一樣,輸入任意值,點選登陸可以跳轉,則證明service層寫正確了,如下:
    這裡寫圖片描述

3.9寫dao層:在src/main/java中新建一個com.welljoint.dao的包;在這個包裡新建一個UserDao.java作為資料層的介面

package com.welljoint.dao;

import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import com.welljoint.entity.User;

/**
 * 
 * @author Administrator
 * dao層
 */
@Repository
public interface UserDao {
    User selectUser(@Param("userName")String userName,@Param("password")String password);
}
  • 此時就可以把dao層注入到service層來,把LoginServiceImpl.java修改為如下:
package com.welljoint.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.welljoint.dao.UserDao;

@Service
public class LoginServiceImpl implements LoginService{

    @Autowired
    UserDao userDao;

    @Override
    public int login(String userName,String password){
        User user = userDao.selectUser(userName,password);
        return user==null?0:1;
    }
}
  • 此時執行專案再用瀏覽器訪問時會報錯,因為我們的dao是沒有實現類的,在Mybatis中是通過配置檔案來配置的,錯誤資訊如下。但是有一個好訊息,我們的java程式碼已經都寫完了,剩下的事情:
    這裡寫圖片描述

3.10 把Mybatis加入到專案中,並且去資料庫查詢資料

  • 對於這一節,是難點,<敲黑板>,3.9節前做的是前奏,都沒有涉及到資料庫操作,關於3.10節,大家可以用Hibernate也可以用Mybatis,這一章我們講Mybatis,我的另一篇文章講Hibernate,也歡迎大家看。

  • (1)使用mysql,在本地建立一個名為ssm的資料庫(手動建立一個user表)

    • 資料字典如下
    id userName password
    integer varchar(10) varchar(10)
    ID 使用者名稱 密碼
    • 資料庫如下:
      這裡寫圖片描述
  • (2)在src/main/resources中建立名為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.welljoint.dao.UserDao" >

  <select id="selectUser" resultType="com.welljoint.entity.User" >
    SELECT 
        *
    FROM 
        user u
    WHERE 
        u.userName = #{userName} AND u.password = #{password}
  </select>

</mapper>
  • (3)在src/main/resources中建立spring.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:conf.properties"/>
    </bean>

    <!-- 2.掃描的包路徑,這裡不掃描被@Controller註解的類 --><!--使用<context:component-scan/> 可以不在配置<context:annotation-config/> -->
    <context:component-scan base-package="com.welljoint">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <import resource="classpath:spring-mybatis.xml" />

</beans>
  • (4)把spring.xml配置檔案,加入到web.xml中,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_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>testSSM2</display-name>

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

    <!-- 請求都交給DispatcherServlet處理 -->
    <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>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- 清除jsp空格 -->
    <jsp-config>
        <jsp-property-group>
            <url-pattern>*.jsp