基礎SpringMVC+Spring+MyBatis框架搭建

前言

先嘮叨一下,這部分沒啥用,能夠跳過。
剛剛工做沒多久,公司的框架都不用本身搭,因此打算本身學習搭建一個框架練練手,因而查了不少SpringMVC+Spring+MyBatis搭建教程,說真的不結合五六個教程根本看不懂,有的教程搭着搭着忽然讓用自動生成工具弄,而後生成的代碼也看不到。我仍是更但願能把最最基礎的,一個核心的流程描述出來,有了根基再弄那些自動化的,省力的,或者本身的小技巧也不遲。
下面開始搭建框架,我寫的也很渣,但願能慢慢改進,大神勿噴。javascript

項目的建立

新建工程(Dynamic Web Project)選擇好本身的tomcat版本後finish便可。
工程的建立css

新建成功後的目錄結構:
圖片描述html

jar包的引入

所需jar包大合影:
jar包合影java

jar包我放在了百度網盤上網盤地址,密碼是:fso6,下載好以後放在lib包下。mysql

SpringMVC的環境搭建:

步驟選擇了先SpringMVC,而後加入Sping和MyBatis整合。SpringMVC能直接在瀏覽器上看到,增長點成就感,更能鼓勵本身。web

首先在WEB-INF下新建一個web.xml,代碼以下:spring

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

    <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:springmvc-servlet.xml</param-value>
        </init-param>
    </servlet>

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

並在src目錄下加入 springmvc-servlet.xml文件:sql

<?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">                    
 
    <!-- 掃描這個包下的類 -->
    <context:component-scan base-package="com.mytestpro"/>
 
    <!-- 防止靜態資源獲取不到 -->
    <mvc:default-servlet-handler />
 
    <!-- 若是須要使用註解,下面的配置必須有 -->
    <mvc:annotation-driven />
     
    <!-- 配置資源的前綴和後綴 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
            id="internalResourceViewResolver">
        <!-- 前綴 -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!-- 後綴 -->
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

關於classpath:默認是你項目下的WEB-INF/classes目錄。這個目錄不是說咱們eclipse中的目錄,而是打包放在tomcat下的目錄。兩個文件建立好以後clean一下tomcat應該就能在你發佈的目錄下看到springmvc-servlet.xml文件了。數據庫

而後建立Controller的java文件:apache

package com.mytestpro.demo.Controller;

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

@Controller
public class TestController {

    @RequestMapping("/test")
    public String test(){
        System.out.println("dsadas");
        //這裏return了test,SpringMVC會加上你配置的前綴後綴去找頁面
        return "test";
    }
    
}

咱們再加入一個test.jsp方便測試,由於以前配置的前綴是WEB-INF/jsp,因此咱們在WEB-INF下建一個jsp包,而後把test.jsp放進去(建議從頁面到數據庫整套環境使用UTF-8以減小亂碼的可能性)。

<%@ 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>Insert title here</title>
</head>
<body>
    this is my test JSP
</body>
</html>

此時,項目的代碼結構以下:
代碼目錄結構

而後其實這個時候就能跑了~放在tomcat下而後運行吧!
結果就是這樣了:
圖片描述

至此,SpringMVC的環境順利的建好了。

整合Spring+MyBatis

咱們所要搭建的完整的架構中,應該是Controller-Service-Dao-DB這個從上至下的順序,固然了因爲MyBatis的加入,咱們弱化了Dao層,而且沒有對Dao接口的實現,若是使用Hibernate那麼Dao接口對應的impl也是要有的。

數據表的建立:
這個SQL超簡單就不說明了。

CREATE TABLE test_user(
    id int not null primary key,
    name varchar(20),
        password varchar(100),
        phone VARCHAR(30)
);

而後在web.xml中加入關於Spring的配置。修改後的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"
    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">

    <!-- Spring -->
    <!-- 配置Spring配置文件路徑 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>  
            classpath:applicationContext.xml  
        </param-value>
    </context-param>
    <!-- 配置Spring上下文監聽器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- Spring -->

    <!-- 配置Spring字符編碼過濾器 -->
    <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>


    <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:springmvc-servlet.xml</param-value>
        </init-param>
    </servlet>

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

而後和springmvc-servlet.xml那個配置文件同樣,放在src下一個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: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.1.xsd    
                        http://www.springframework.org/schema/context    
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd    
                        http://www.springframework.org/schema/mvc    
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">  
    <!-- 自動掃描 -->  
    <context:component-scan base-package="com.mytestpro" />  
    <!-- 引入配置文件 -->  
    <bean id="propertyConfigurer"  
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
        <property name="location" value="classpath:jdbc.properties" />  
    </bean>  
  
      <!-- 這裏使用了dbcp的鏈接池,能夠看作是用來創建和數據庫的鏈接的,具體好處能夠自行百度 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  
        destroy-method="close">  
        <property name="driverClassName" value="${driver}" />  
        <property name="url" value="${url}" />  
        <property name="username" value="${username}" />  
        <property name="password" value="${password}" />  
        <!-- 初始化鏈接大小 -->  
        <property name="initialSize" value="${initialSize}"></property>  
        <!-- 鏈接池最大數量 -->  
        <property name="maxActive" value="${maxActive}"></property>  
        <!-- 鏈接池最大空閒 -->  
        <property name="maxIdle" value="${maxIdle}"></property>  
        <!-- 鏈接池最小空閒 -->  
        <property name="minIdle" value="${minIdle}"></property>  
        <!-- 獲取鏈接最大等待時間 -->  
        <property name="maxWait" value="${maxWait}"></property>  
    </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/mytestpro/demo/mapping/*.xml"></property>  
    </bean>
  
    <!-- DAO接口所在包,Spring會查找其下的類,用來和mapper.xml對應起來 -->  
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="com.mytestpro.demo.dao" />  
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>  
    </bean>
  
    <!-- 事務管理 -->  
    <bean id="transactionManager"  
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource" />  
    </bean>  
  
</beans>

其中使用到的jdbc.properties配置文件,須要在src上新建這個文件,主要爲了配置鏈接池的相關信息。內容以下:

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/fooler
username=root
password=
#\u5B9A\u4E49\u521D\u59CB\u8FDE\u63A5\u6570  
initialSize=0
#\u5B9A\u4E49\u6700\u5927\u8FDE\u63A5\u6570  
maxActive=20
#\u5B9A\u4E49\u6700\u5927\u7A7A\u95F2  
maxIdle=20
#\u5B9A\u4E49\u6700\u5C0F\u7A7A\u95F2  
minIdle=1
#\u5B9A\u4E49\u6700\u957F\u7B49\u5F85\u65F6\u95F4  
maxWait=60000

而後在建一系列的包,項目結構以下:
項目結構

而後創建TestUser實體,固然了,在Entity包下。

package com.mytestpro.demo.Entity;

public class TestUser {

    private Integer id;
    private String name;
    private String password;
    private String phone;
    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;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    
}

接下來就是mybatis的功能的建設了。因爲咱們在applicationcontext.xml文件裏配置了關於mybatis的映射文件存在包(com/mytestpro/demo/mapping/*.xml)和dao接口所在的包(com.mytestpro.demo.dao)。因此這裏咱們直接把xml文件和dao接口放到對應的包裏就行了。

TestUserMapper.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.mytestpro.demo.dao.TestUserDao">

    <select id="getUser" parameterType="com.mytestpro.demo.Entity.TestUser" resultType="com.mytestpro.demo.Entity.TestUser">
        select * from test_user where name = #{name} and password= #{password}
    </select> 
</mapper>

這裏須要說明的地方:
namespace:對應的dao接口的目錄及名字。
id:這個方法的名字,和dao接口的方法名字必定要同樣。
parameterType:傳入參數的類型。
resultType:返回結果的類型。

對應的dao接口:

package com.mytestpro.demo.dao;

import com.mytestpro.demo.Entity.TestUser;

public interface TestUserDao {
    TestUser getUser(TestUser user);
}

而後創建service接口以及實現類,這裏先提供一個按照用戶名密碼查找用戶的藉口好了。
接口及其實現類以下:
UserService:

package com.mytestpro.demo.service;

import com.mytestpro.demo.Entity.TestUser;

public interface UserService {

    TestUser getUser(TestUser user);
    
}

UserServiceImpl:

package com.mytestpro.demo.service.impl;

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

import com.mytestpro.demo.Entity.TestUser;
import com.mytestpro.demo.dao.TestUserDao;
import com.mytestpro.demo.service.UserService;
@Service
public class UserServiceImpl implements UserService{

    @Autowired
    TestUserDao testUserDao;
    
    @Override
    public TestUser getUser(TestUser user) {
        // TODO Auto-generated method stub
        return testUserDao.getUser(user);
    }

}

而且爲了便於測試,我在Controller層也作了變化,定義了兩個函數,一個用於展現登陸頁面,一個處理登錄的操做:

package com.mytestpro.demo.Controller;

import org.apache.ibatis.io.ResolverUtil.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mytestpro.demo.Entity.TestUser;
import com.mytestpro.demo.service.UserService;

@Controller
public class TestController {

    @Autowired
    UserService userService;
    
    @RequestMapping("/test")
    public String test(){
        System.out.println("dsadas");
        return "test";
    }
    
    @RequestMapping("/doLogin")
    public String doLogin(TestUser user){
        TestUser testUser = userService.getUser(user);
        if(testUser!=null){
            System.out.println(testUser.getPhone());
            return "success";
        }else{
            return "false";
        }
    }
}

對新的Controller的解釋:
test()函數直接讓頁面展現test.jsp,沒什麼好說的。
doLogin調用了service的getUser方法,檢測是否有這個用戶存在,若是有則進入success.jsp頁面,不然進入false.jsp頁面。
三個頁面的內容以下:
test.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>
    <% 
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
    %>
    <title>TestLogin</title>
    <link rel="stylesheet" type="text/css" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css">  
</head>
<body>
    <div class="container">
          <h2>Please input your name and password</h2>
          <form action="${basepath}doLogin">
          
              <div class="input-group">
                <span class="input-group-addon" >UserName</span>
                <input type="text" class="form-control" id="name" name="name">
            </div>
            <br>
            <div class="input-group">
                <span class="input-group-addon">Password</span>
                <input type="password" id="password" name="password" class="form-control" >
            </div>
            <br>    
            <div class="input-group">
                <button id="fat-btn" class="btn btn-success" type="submit">登陸</button>
            </div>
              
          </form>
          
    </div>
<script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
</body>
</html>

爲了美觀,這裏使用了bootstrap,form的action直接將表單提交到doLogin方法中(字段會自動封裝到TestUser實體中)。

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>Insert title here</title>
</head>
<body>
    登錄成功!
</body>
</html>

false.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>Insert title here</title>
</head>
<body>
    登錄失敗!
</body>
</html>

咱們數據庫中現有的數據:
數據庫數據

操做頁面,用戶名whr,密碼123456:
操做

登錄結果:
結果

最後的項目結構:

圖片描述

至此,一個最簡單的SpringMVC+Spring+MyBatis的框架搭建完成了。

代碼能夠在這裏下載到,密碼是:ubrr,這裏的代碼是我從workspace直接copy出來的。

最後的梳理

也不說那些專業的了,畢竟那些百度都能看到,說一下我對運行的直觀理解吧。
SpringMVC主要負責從頁面上到咱們程序中的流轉,頁面上的請求按照@RequestMapping的地址轉到對應的方法中,而後這個方法中咱們調用Service接口,Service的接口實現中,再調用Dao層的東西,這裏就是MyBatis了。Spring主要負責了bean的注入,說白了就是不用咱們本身new了,用一個註解好比@Autowired就能夠注入一個接口。而MyBatis呢,就是爲了方便使用數據庫,對數據庫進行操做的一個框架。

總結就這麼多吧。若是看到這裏但願你也是已經能搭建成功了。我也是新手,不熟練,文中若有不當還望各位指出,謝謝!

相關文章
相關標籤/搜索