MyBatis+SpringMVC 框架搭建小結

前言:最近再寫一款視頻播放器的後臺,踩了不少坑,在此總結。html

設計順序:

前提:搭建配置無缺的Spring-MyBatis項目前端

1.流程分析,數據庫設計(看似無用,真正作起來真的須要這個東西幫忙整理下思路)java

2.dao層,mapper層,pojo層(能夠自動生成),service層,impl層的編寫mysql

3.controll層的編寫git

流程圖:github

 

搭建Spring-Mybatis項目框架:(GitHub地址:https://github.com/XaiverHai/mybatis_spring)

項目結構:web

            


 

各個目錄層說明:由上往下(黑體的必備,其他的能夠自定)

controller     控制層,和前端相聯繫,主要負責從頁面獲取數據,傳遞數據到頁面。spring

dao       數據層,和數據庫聯繫,對數據庫進行增刪改查接口的書寫。sql

mapping    dao層的配置文件,這一層在mybatis裏面很重要,是對應dao層的數據庫實現層,數據庫邏輯都是寫在裏面,也能夠寫優化的數據庫代碼。數據庫

pojo      對應數據庫的對象,也是dao層直接操做的對象,能夠在這裏面添加返回Json的toString()方法。這樣返回的對象就能夠直接爲Json了。

service    中間層,也是服務層,用來寫dao層的接口,處理邏輯。

service.impl   服務實現層,實現接口邏輯的,裏面放的是實體類,判斷是否爲空等操做能夠在這裏面進行。

utils       通用公共層


 

src/main/resources目錄 文件說明:

jdbc.properties  數據庫配置文件,裏面配置着數據庫參數

log4j.properties    日誌配置文件,能夠在控制檯或者文件裏面輸出日誌文件,以便收取信息修正bug。

mybatis-properties  mybatis配置文件,配置相關的內容。

spring-dao    spring和mybatis的整合文件,這個文件將兩個的配置完美結合了,也是關鍵。

spring-mvc    這個就是servlet的配置文件了,前端能不能正常跑起來這個很重要。


 

WebContent目錄說明

WEB-INF  這裏面的文件前端沒法訪問的,因此直接在地址上面輸入這裏面的文件怎麼都是404,不配置的話只能後臺調用

web.xml    關鍵文件,須要在裏面配置DispatcherServerlet,配置過濾器以及監聽。

 

pom.xml    這個不是這個目錄裏面的是外層目錄,主要是maven的配置文件,拿着這個就不用苦逼的烤jar包了。

框架搭建(先搭建框架,再進行開發):

先建立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>MyBatisSpringMVC</groupId>
    <artifactId>MyBatisSpringMVC</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <url>http://maven.apache.org</url>
    <properties>
        <!-- spring版本號 -->
        <spring.version>4.0.2.RELEASE</spring.version>
        <!-- mybatis版本號 -->
        <mybatis.version>3.2.6</mybatis.version>
        <!-- log4j日誌文件管理包版本 -->
        <slf4j.version>1.7.7</slf4j.version>
        <log4j.version>1.2.17</log4j.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <!-- 表示開發的時候引入,發佈的時候不會加載此包 -->
            <scope>test</scope>
        </dependency>
        <!-- spring核心包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</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-webmvc</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-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</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.2</version>
        </dependency>
        <!-- 導入java ee jar 包 -->
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
        </dependency>
        <!-- 導入Mysql數據庫連接jar包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.30</version>
        </dependency>
        <!-- 導入dbcp的jar包,用來在applicationContext.xml中配置數據庫 -->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.2.2</version>
        </dependency>
        <!-- JSTL標籤類 -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- 日誌文件管理包 -->
        <!-- log start -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>


        <!-- 格式化對象,方便輸出日誌 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.1.41</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 -->
        <!-- 映入JSON -->
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>
        <!-- 上傳組件包 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.9</version>
        </dependency>


    </dependencies>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <warSourceDirectory>WebContent</warSourceDirectory>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
pom.xml

 

 再配置jdbc.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/vddb
username=root
password=1234
initialSize=0
maxActive=20
maxIdle=20
minIdle=1
maxWait=60000
jdbc.properties

 

配置mybatis-config.xml配置文件

<?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>
    <!-- 配置全局屬性 -->
    <settings>
        <!-- 使用jdbc的getGeneratedKeys獲取數據庫自增值 -->
        <setting name="useGeneratedKeys" value="true" />
        <!-- 使用列別名替換別名 -->
        <setting name="useColumnLabel" value="true" />
        <!-- 開啓駝峯命名規範 -->
        <setting name="mapUnderscoreToCamelCase" value="true" />
    </settings>
</configuration>
mybatis-config.xml

 

 

配置spring-dao.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.mybatis.spring.*" />
    <!-- 1.數據庫鏈接池 -->
    <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"
        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>

    <!-- 2.配置sqlsession對象,不須要mybatis的配置映射文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入數據庫鏈接池 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 配置MyBatis全局配置文件:mybatis-config.xml -->
        <property name="configLocation" value="classpath:mybatis-config.xml" />
        <!-- 掃描sql配置文件:mapper須要的xml文件 -->
        <property name="mapperLocations" value="classpath:com/mybatis/spring/mapping/*.xml" />
        <!-- 自動掃描數據庫實體pojo文件 -->
        <property name="typeAliasesPackage" value="com.mybatis.spring.pojo" />
    </bean>

    <!-- 4:DAO接口所在包名,Spring會自動查找其下的類 ,動態實現Dao接口注入到Spring容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 給出須要掃描的Dao接口包 -->
        <property name="basePackage" value="com.mybatis.spring.dao" />
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

    <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
</beans>
spring-dao

 

配置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.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">
    <!-- 引用註解 -->
    <mvc:annotation-driven />

    <mvc:default-servlet-handler />
    <!-- 自動掃描該包,使SpringMVC認爲包下用了@controller註解的類是控制器 -->
    <context:component-scan base-package="com.mybatis.spring.controller.*" />
    <!-- 靜態文件訪問路徑權限,意思就是下面的location目錄會跳過攔截直接訪問 -->
    <mvc:resources location="/WEB-INF/pages/" mapping="/pages/*" />
    <!--避免IE執行AJAX時,返回JSON出現下載文件 -->
    <bean id="mappingJacksonHttpMessageConverter"
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </bean>
    <!-- 啓動SpringMVC的註解功能,完成請求和註解POJO的映射 -->
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter" />    <!-- JSON轉換器 -->
            </list>
        </property>
    </bean>
    <!-- 定義跳轉的文件的先後綴 ,視圖模式配置 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 這裏的配置個人理解是自動給後面action的方法return的字符串加上前綴和後綴,變成一個 可用的url地址 -->
        <property name="prefix" value="/WEB-INF/pages/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!-- 配置文件上傳,若是沒有使用文件上傳能夠不用配置,固然若是不配,那麼配置文件中也沒必要引入上傳組件包 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 默認編碼 -->
        <property name="defaultEncoding" value="utf-8" />
        <!-- 文件大小最大值 -->
        <property name="maxUploadSize" value="10485760000" />
        <!-- 內存中的最大值 -->
        <property name="maxInMemorySize" value="40960" />
    </bean>

</beans>
spring-mvc.xml

 

配置log4j.properties日誌輸出文件

#定義LOG輸出級別  
log4j.rootLogger=INFO,Console,File
#定義日誌輸出目的地爲控制檯  
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#能夠靈活地指定日誌輸出格式,下面一行是指定具體的格式  
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d[%t]%-5p[%c] - %m%n
  
#文件大小到達指定尺寸的時候產生一個新的文件  
log4j.appender.File = org.apache.log4j.RollingFileAppender
#指定輸出目錄  
log4j.appender.File.File = E:Users/SpringMVC/MyBatisSpringMVC/logs/ssm.log
#定義文件最大大小  
log4j.appender.File.MaxFileSize = 10MB
# 輸出因此日誌,若是換成DEBUG表示輸出DEBUG以上級別日誌  
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n  
log4j.properties

 

而後再是配置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>MyBatis_Spring_MVC</display-name>
    <welcome-file-list>
        <welcome-file>register.jsp</welcome-file>
    </welcome-file-list>
    <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>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:config/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>
            org.springframework.web.context.ContextCleanupListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>spring-mvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-*.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring-mvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>
web.xml

 

 

直接複製粘貼過來,運氣好的話能夠直接跑,可是若是運氣很差,改都很差下手,所以,配置仍是須要熟悉,下面是當時碰見的幾個比較嚴重的bug,也是對這個框架不甚其解,總之,配置上面的事情須要瞭解,可是也不能花太多的時間,畢竟是造輪子的事情,更多的應該體如今代碼上面。

配置問題:

1.No mapping found for HTTP request with URI

這個也是不少網上出現的問題,確實很難解決,個人狀況出如今跳轉的時候。

解決辦法:這個是servlet裏面的配置有問題,在servlet裏面,添加了<mvc:default-servlet-handler />問題就解決了。

2.沒法找到***-servlet.xml文件

這個問題是在自定義servlet的時候出現,web.xml會默認掃描這個文件,可是默認的路徑是和他一個路徑。

解決辦法:在servlet裏面添加下面代碼便可

<init-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:spring-*.xml</param-value>
</init-param>

正式編碼:

設計邏輯數據庫:

在此以前,你須要知道你要實現的功能,須要對哪些數據進行操做,因此在編碼前,你須要設計好數據庫,整套流程有個明確的認識,這樣寫起來也比較有層次性。

在這裏我用到寫流程的軟件是 Processon(https://www.processon.com)

自動生成dao,mapper,pojo:

數據庫作完了就能夠往代碼裏面添加最簡單的增刪改查功能了,這裏有一個自動生成數據庫操做對象以及mapper文件的方法,大大提升了工做效率。

須要的是一個xml文件,兩個jar包,隨便放在哪一個文件夾,寫在項目裏面是用到的時候省得處處找。

1.配置generatorConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!-- 數據庫驅動 -->
    <classPathEntry location="mysql-connector-java-5.1.25-bin.jar" />
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true" />
            <!-- 是否去除自動生成的註釋 true:是 : false:否 -->
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
        <!--數據庫連接URL,用戶名、密碼 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
            connectionURL="jdbc:mysql://localhost:3306/vddb" userId="root"
            password="1234">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>
        <!-- 生成模型的包名和位置 -->
        <javaModelGenerator targetPackage="com.mybatis.spring.pojo"
            targetProject="src">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- 生成映射文件的包名和位置 -->
        <sqlMapGenerator targetPackage="com.mybatis.spring.mapping"
            targetProject="src">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>
        <!-- 生成DAO的包名和位置 -->
        <javaClientGenerator type="XMLMAPPER"
            targetPackage="com.mybatis.spring.dao" targetProject="src">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
        <!-- 要生成的表 tableName是數據庫中的表名或視圖名 domainObjectName是實體類名 -->
        <table tableName="registerinfo" domainObjectName="RegisterInfo"
            enableCountByExample="false" enableUpdateByExample="false"
            enableDeleteByExample="false" enableSelectByExample="false"
            selectByExampleQueryId="false"></table>
    </context>
</generatorConfiguration>
generatorConfig.xml

 

裏面須要配置的是數據庫的名稱以及帳號密碼,還有就是對應的表和輸出的對象名

2.win+R+cmd 而後轉到 xml所在文件夾,執行腳本

腳本爲:java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite

執行成功會有成功的提示,接下來就是去文件夾裏面找文件就行了。

具體參見 http://www.cnblogs.com/xuhai/p/8011957.html

package com.mybatis.spring.dao;

import com.mybatis.spring.pojo.Resources;

public interface ResourcesMapper {
    int deleteByPrimaryKey(String index);

    int insert(Resources record);

    int insertSelective(Resources record);

    Resources selectByPrimaryKey(String index);

    int updateByPrimaryKeySelective(Resources record);

    int updateByPrimaryKey(Resources record);
}
ResourcesMapper.java

 

<?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.mybatis.spring.dao.ResourcesMapper" >
  <resultMap id="BaseResultMap" type="com.mybatis.spring.pojo.Resources" >
    <id column="index" property="index" jdbcType="VARCHAR" />
    <result column="image" property="image" jdbcType="VARCHAR" />
    <result column="title" property="title" jdbcType="VARCHAR" />
    <result column="video" property="video" jdbcType="VARCHAR" />
    <result column="page_num" property="pageNum" jdbcType="VARCHAR" />
  </resultMap>
  <sql id="Base_Column_List" >
    index, image, title, video, page_num
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String" >
    select 
    <include refid="Base_Column_List" />
    from resources
    where index = #{index,jdbcType=VARCHAR}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.String" >
    delete from resources
    where index = #{index,jdbcType=VARCHAR}
  </delete>
  <insert id="insert" parameterType="com.mybatis.spring.pojo.Resources" >
    insert into resources (index, image, title, 
      video, page_num)
    values (#{index,jdbcType=VARCHAR}, #{image,jdbcType=VARCHAR}, #{title,jdbcType=VARCHAR}, 
      #{video,jdbcType=VARCHAR}, #{pageNum,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.mybatis.spring.pojo.Resources" >
    insert into resources
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="index != null" >
        index,
      </if>
      <if test="image != null" >
        image,
      </if>
      <if test="title != null" >
        title,
      </if>
      <if test="video != null" >
        video,
      </if>
      <if test="pageNum != null" >
        page_num,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="index != null" >
        #{index,jdbcType=VARCHAR},
      </if>
      <if test="image != null" >
        #{image,jdbcType=VARCHAR},
      </if>
      <if test="title != null" >
        #{title,jdbcType=VARCHAR},
      </if>
      <if test="video != null" >
        #{video,jdbcType=VARCHAR},
      </if>
      <if test="pageNum != null" >
        #{pageNum,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.mybatis.spring.pojo.Resources" >
    update resources
    <set >
      <if test="image != null" >
        image = #{image,jdbcType=VARCHAR},
      </if>
      <if test="title != null" >
        title = #{title,jdbcType=VARCHAR},
      </if>
      <if test="video != null" >
        video = #{video,jdbcType=VARCHAR},
      </if>
      <if test="pageNum != null" >
        page_num = #{pageNum,jdbcType=VARCHAR},
      </if>
    </set>
    where index = #{index,jdbcType=VARCHAR}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.mybatis.spring.pojo.Resources" >
    update resources
    set image = #{image,jdbcType=VARCHAR},
      title = #{title,jdbcType=VARCHAR},
      video = #{video,jdbcType=VARCHAR},
      page_num = #{pageNum,jdbcType=VARCHAR}
    where index = #{index,jdbcType=VARCHAR}
  </update>
</mapper>
ResourcesMapper.xml
package com.mybatis.spring.pojo;

public class Resources {
    private String index;

    private String image;

    private String title;

    private String video;

    private String pageNum;

    public String getIndex() {
        return index;
    }

    public void setIndex(String index) {
        this.index = index == null ? null : index.trim();
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image == null ? null : image.trim();
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title == null ? null : title.trim();
    }

    public String getVideo() {
        return video;
    }

    public void setVideo(String video) {
        this.video = video == null ? null : video.trim();
    }

    public String getPageNum() {
        return pageNum;
    }

    public void setPageNum(String pageNum) {
        this.pageNum = pageNum == null ? null : pageNum.trim();
    }

    @Override
    public String toString() {
        return "{\"index\":\"" + index + "\",\"image\":\"" + image + "\",\"title\":\"" + title + "\",\"video\":\""
                + video + "\",\"pageNum\":\"" + pageNum + "\"}";
    }

}
Resources.java

 

上面的代碼分別爲dao層,mapping層,pojo層。


 

Serivice,ServiceImpl層的編寫

這個時候須要對dao層進行service代碼的編寫,用於書寫代碼邏輯。

package com.mybatis.spring.service;

import com.mybatis.spring.pojo.Resources;

public interface IResourcesService {

    public int deleteByPrimaryKey(String index);

    public int insert(Resources record);

    public int insertSelective(Resources record);

    public Resources selectByPrimaryKey(String index);

    public int updateByPrimaryKeySelective(Resources record);

    public int updateByPrimaryKey(Resources record);
}
IResourcesService.java
package com.mybatis.spring.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mybatis.spring.dao.ResourcesMapper;
import com.mybatis.spring.pojo.Resources;
import com.mybatis.spring.service.IResourcesService;

@Service
public class ResourcesServiceImpl implements IResourcesService {
    @Autowired
    private ResourcesMapper resourcesMapper;

    @Override
    public int deleteByPrimaryKey(String index) {
        return resourcesMapper.deleteByPrimaryKey(index);
    }

    @Override
    public int insert(Resources record) {
        return resourcesMapper.insert(record);
    }

    @Override
    public int insertSelective(Resources record) {
        return resourcesMapper.insertSelective(record);
    }

    @Override
    public Resources selectByPrimaryKey(String index) {
        return resourcesMapper.selectByPrimaryKey(index);
    }

    @Override
    public int updateByPrimaryKeySelective(Resources record) {
        return resourcesMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(Resources record) {
        return resourcesMapper.updateByPrimaryKey(record);
    }

}
ResourcesServiceImpl.java

這裏面註解的用法:我對註解不是很明白因此得解釋一下,實現類須要添加Autowired是要自動添加dao層的pojo對象,所以能夠直接返回相應值(有錯誤請及時糾正),Service是後面Controller層使用的時候告訴那邊

這個加載的是dao層的服務,用來關聯先後關係。


 

Controller層的編寫

package com.mybatis.spring.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.mybatis.spring.pojo.LoginResult;
import com.mybatis.spring.pojo.Register;
import com.mybatis.spring.pojo.Resources;
import com.mybatis.spring.service.IResourcesService;

@Controller
@Configuration
@ComponentScan("com.mybatis.spring.controller")
// No need to include component-scan in xml
public class ResourcesController {
    @Autowired
    private IResourcesService iResourcesService;

    @RequestMapping(value = "/login.do", method = RequestMethod.POST)
    public String login(@RequestParam("unicode") String unicode, Model model) throws Exception {
        // 判斷unicode是否存在,不存在的resources爲null。
        Resources login_resources = iResourcesService.selectByPrimaryKey(unicode);
        Register register = new Register();
        LoginResult loginResult = new LoginResult();
        Resources resources = new Resources();
        List<Resources> resourcesList = new ArrayList<Resources>();
        if (null == login_resources.toString()) {
            // 說明沒有註冊登陸,Flag設置爲false
            register.setFlag("false");
            loginResult.setFlag("false");
            // 添加試看視頻,返回爲前三個
            for (int i = 1; i <= 3; i++) {
                resources = iResourcesService.selectByPrimaryKey(String.valueOf(i));
                resourcesList.add(resources);
            }
            loginResult.setResourcesList(resourcesList);
            model.addAttribute("result", loginResult);
            return "result";
        } else {
            // 登陸成功,返回登陸成功的數值
            register.setFlag("true");
            loginResult.setFlag("true");
            // 返回全部視頻的值
            for (int i = 1; i <= 12; i++) {
                resources = iResourcesService.selectByPrimaryKey(String.valueOf(i));
                resourcesList.add(resources);
            }
            loginResult.setResourcesList(resourcesList);
            model.addAttribute("result", loginResult);
            return "result";
        }
    }
}
ResourcesController.java

 

這段代碼編寫得比較失敗得,由於controller裏面最好不須要這麼多判斷邏輯,這些都應該丟給service層來處理就好,好在代碼邏輯並不複雜,因此就這樣將就了。

須要說明的地方:

@Controller  讓配置的掃描在此有效,而且告知servlet這個是控制層。

@Configuration
@ComponentScan("com.mybatis.spring.controller")   這兩個要一塊兒用,用來掃描包的,和spring-mvc.xml裏面配置的做用是同樣的

@RequestMapping(value = "/login.do", method = RequestMethod.POST,produces = { "application/json;charset=UTF-8")   映射的路徑,能夠和前端的jsp文件裏面的action相對應。後面的produces是確認返回代碼格式。

@RequestParam("unicode") String unicode   這個是能夠從前端獲取的文件,直接從前端獲取,不須要特地獲取,能夠直接使用。

return "result";    這裏面的return可不是返回一個字符串,他是本身去尋找result.jsp這個文件去了,model能夠把獲取的值傳遞到前端。

@ResponseBody   返回值,能夠在方法體裏面定義返回的格式,好比不想返回頁面,而是Json數值,那麼就須要這個註解

<%@ page import="java.sql.*" language="java"
    contentType="text/html; charset=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>
    <center>
        <form action="login" name="loginForm" method="post">
            <table>
                <tr>
                    <td>帳號:</td>
                    <td><input type="text" name="username"></td>
                </tr>
                <tr>
                    <td>密碼:</td>
                    <td><input type="password" name="password"></td>
                </tr>
                <tr>
                    <td colspan="1"><input type="submit" value="登陸"></td>
                    <td colspan="1"><a href="register.jsp">註冊</a></td>
                </tr>
            </table>
        </form>
    </center>
</body>
</html>
index.jsp

 


 

注:上面的代碼不是徹底對應

相關文章
相關標籤/搜索