SSM+maven實現答題管理系統(一)

最近項目比較忙,而後又生病了,都沒時間寫博客了QAQ。此次我帶來了SSM框架搭建的一個答題管理系統,以前我用的tp框架構建的答題管理系統,此次我用SSM框架重構了一下image.pngphp

1.前期準備

SSM架構的相關知識(Spring+Springmvc+mybatis)IDEA/eclipse/myeclipse編譯器layui文檔的bang助:layui開發使用文檔默認的maven配置Navicat/mysql workbench等數據庫可視化管理工具前端

使用IDEA建立maven項目java

2.架構設計(mvc)

image.png

首先將resources包設置爲Resource Root將webapp包設置爲Web項目目錄mysql

指定Web目錄:image.pnggit

指定Spring配置文件目錄:image.pnggithub

model層採用mybatis進行持久化處理mybatis generator插件進行逆向工程,如下說明幾個配置文件:applicationContext:Springmvc配置文件web

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

    <!--掃描包下的註解-->
    <context:component-scan base-package="com.sl.example" annotation-config="true"/>

    <!--<context:annotation-config/>-->
    <aop:aspectj-autoproxy/>


    <import resource="applicationContext-datasource.xml"/>


</beans>
複製代碼

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

    <context:component-scan base-package="com.sl.example" annotation-config="true"/>

    <bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="order" value="2"/>
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
        <property name="locations">
            <list>
                <value>classpath:datasource.properties</value>
            </list>
        </property>
        <property name="fileEncoding" value="utf-8"/>
    </bean>



    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${db.driverClassName}"/>
        <property name="url" value="${db.url}"/>
        <property name="username" value="${db.username}"/>
        <property name="password" value="${db.password}"/>
        <!-- 鏈接池啓動時的初始值 -->
        <property name="initialSize" value="${db.initialSize}"/>
        <!-- 鏈接池的最大值 -->
        <property name="maxActive" value="${db.maxActive}"/>
        <!-- 最大空閒值.當通過一個高峯時間後,鏈接池能夠慢慢將已經用不到的鏈接慢慢釋放一部分,一直減小到maxIdle爲止 -->
        <property name="maxIdle" value="${db.maxIdle}"/>
        <!-- 最小空閒值.當空閒的鏈接數少於閥值時,鏈接池就會預申請去一些鏈接,以避免洪峯來時來不及申請 -->
        <property name="minIdle" value="${db.minIdle}"/>
        <!-- 最大創建鏈接等待時間。若是超過此時間將接到異常。設爲-1表示無限制 -->
        <property name="maxWait" value="${db.maxWait}"/>
        <!--#給出一條簡單的sql語句進行驗證 -->
        <!--<property name="validationQuery" value="select getdate()" />-->
        <property name="defaultAutoCommit" value="${db.defaultAutoCommit}"/>
        <!-- 回收被遺棄的(通常是忘了釋放的)數據庫鏈接到鏈接池中 -->
        <!--<property name="removeAbandoned" value="true" />-->
        <!-- 數據庫鏈接過多長時間不用將被視爲被遺棄而收回鏈接池中 -->
        <!--<property name="removeAbandonedTimeout" value="120" />-->
        <!-- #鏈接的超時時間,默認爲半小時。 -->
        <property name="minEvictableIdleTimeMillis" value="${db.minEvictableIdleTimeMillis}"/>

        <!--# 失效檢查線程運行時間間隔,要小於MySQL默認-->
        <property name="timeBetweenEvictionRunsMillis" value="40000"/>
        <!--# 檢查鏈接是否有效-->
        <property name="testWhileIdle" value="true"/>
        <!--# 檢查鏈接有效性的SQL語句-->
        <property name="validationQuery" value="SELECT 1 FROM dual"/>
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath*:mappers/*Mapper.xml"></property>

        <!-- 分頁插件 -->
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageHelper">
                    <property name="properties">
                        <value>
                            dialect=mysql
                        </value>
                    </property>
                </bean>
            </array>
        </property>

    </bean>

    <bean name="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.sl.example.dao"/>
    </bean>

    <!-- 使用@Transactional進行聲明式事務管理須要聲明下面這行 -->
    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
    <!-- 事務管理 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
        <!--提交失敗是否回滾-->
        <property name="rollbackOnCommitFailure" value="true"/>
    </bean>


</beans>
複製代碼

datasource.properties:數據庫配置文件ajax

# 配置下載的驅動包的位置
db.driverLocation = C:/java/mysql-connector-java-5.1.41.jar

# db.driverClassName = oracle.jdbc.driver.OracleDriver

db.driverClassName = com.mysql.jdbc.Driver

# db.url=jdbc:mysql://數據庫IP:數據庫 Port/database?characterEncoding=utf-8
db.url = jdbc:mysql://xxxx:3306/tp5?characterEncoding=utf-8
db.username =XXX
db.password =XXXXX

db.initialSize = 20
db.maxActive = 50
db.maxIdle = 20
db.minIdle = 10
db.maxWait = 10
db.defaultAutoCommit = true
db.minEvictableIdleTimeMillis = 3600000複製代碼

generatorConfig.xml:mybatis generator逆向工程時的配置文件算法

<?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>
    <!--1.jdbcConnection設置數據庫鏈接-->
    <!--2.javaModelGenerator設置類的生成位置-->
    <!--3.sqlMapGenerator設置生成xml的位置-->
    <!--4.javaClientGenerator設置生成dao層接口的位置-->
    <!--5.table設置要進行逆向工程的表名以及要生成的實體類的名稱-->


    <properties resource="datasource.properties"></properties>

    <!--指定特定數據庫的jdbc驅動jar包的位置-->
    <classPathEntry location="${db.driverLocation}"/>

    <context id="default" targetRuntime="MyBatis3">

        <!-- optional,旨在建立class時,對註釋進行控制 -->
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!--jdbc的數據庫鏈接 -->
        <jdbcConnection
                driverClass="${db.driverClassName}"
                connectionURL="${db.url}"
                userId="${db.username}"
                password="${db.password}">
        </jdbcConnection>


        <!-- 非必需,類型處理器,在數據庫類型和java類型之間的轉換控制-->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>


        <!-- Model模型生成器,用來生成含有主鍵key的類,記錄類 以及查詢Example類
            targetPackage     指定生成的model生成所在的包名
            targetProject     指定在該項目下所在的路徑
        -->
        <javaModelGenerator targetPackage="com.sl.example.pojo" targetProject="./src/main/java">
            <!-- 是否容許子包,即targetPackage.schemaName.tableName -->
            <property name="enableSubPackages" value="false"/>
            <!-- 是否對model添加 構造函數 -->
            <property name="constructorBased" value="true"/>
            <!-- 是否對類CHAR類型的列的數據進行trim操做 -->
            <property name="trimStrings" value="true"/>
            <!-- 創建的Model對象是否不可改變  即生成的Model對象不會有 setter方法,只有構造方法 -->
            <property name="immutable" value="false"/>
        </javaModelGenerator>

        <!--mapper映射文件生成所在的目錄 爲每個數據庫的表生成對應的SqlMap文件 -->
        <sqlMapGenerator targetPackage="mappers" targetProject="./src/main/resources">
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>

        <!-- 客戶端代碼,生成易於使用的針對Model對象和XML配置文件 的代碼
                type="ANNOTATEDMAPPER",生成Java Model 和基於註解的Mapper對象
                type="MIXEDMAPPER",生成基於註解的Java Model 和相應的Mapper對象
                type="XMLMAPPER",生成SQLMap XML文件和獨立的Mapper接口
        -->

        <!-- targetPackage:mapper接口dao生成的位置 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.sl.example.dao" targetProject="./src/main/java">
            <!-- enableSubPackages:是否讓schema做爲包的後綴 -->
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>

        <!-- tablenName: 數據庫表名
                domainObjectName: 生成的類名
                enableCountByExample: 是否能夠經過對象查數量
                enableUpdateByExample: 是否能夠經過對象進行更新
        -->
        <table tableName="t_gr_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>

        <table tableName="t_gr_qsn_model" domainObjectName="Model" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
        </table>
        <table tableName="t_gr_qsn" domainObjectName="Qsn" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
        </table>
        <table tableName="t_gr_qsn_detail" domainObjectName="Detail" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
        </table>
        <table tableName="t_gr_psg_qsn_r" domainObjectName="Choose" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
        </table>
    </context>
</generatorConfiguration>
複製代碼

而後controller包下對應控制器dao包下是逆向生成的DAO數據層pojo包下是逆向生成的實體類service是咱們寫的業務層util是咱們的工具類

image.png

最後的最後,咱們數據庫設計:

既然是答題管理系統。

一套題(即一個模板)(model表)對應多個題目(qsn表)

一個題目(qsn表)對應多個答案(detail表)

而後Navicat表設計以下:model表:(tgr是前綴 rmkX是備用字段都不用管)image.png

qsn表:(這裏我沒有設置外鍵 實際上qsn表的model_id應該設置外鍵)image.png

detail表:(同上)image.png

好了 說了那麼多 終於作好全部的準備了,能夠正式進入咱們的開發了。

3.本章目標

與thinkphp實現答題管理系統對應,咱們依舊先實現model表(答題模板的增長功能模塊的實現)

4.View層實現(Jquery+layui)

首先是添加模板的View層實現。

image.png

引用了layui的按鈕組樣式 id爲btn-add的按鈕 即爲添加模板按鈕image.png

點擊添加模板 咱們用Jquery設置其彈出了一個layui的彈出層 id爲set-add-put

//彈出添加窗口
            $('#btn-add').click(function() {
                layer.open({
                    type: 1,
                    skin: 'layui-layer-rim', //加上邊框
                    area: ['660px', '350px'], //寬高
                    content: $('#set-add-put'),
                    title: "添加模板"
                });
            });複製代碼

以下

image.png

input框有三個,分別對應數據庫的create_name,time,name。

<!--添加彈出層-->
    <div id="set-add-put" style="display:none; width:550px; padding:20px;">
        <form class="layui-form">
            <div class="layui-form-item">
                <label class="layui-form-label">建立人名字</label>
                <div class="layui-input-block">
                    <input type="text" name="create_name" required lay-verify="required" placeholder="請輸入建立人姓名" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">建立時間</label>
                <div class="layui-input-block">
                    <input type="text" name="time" required lay-verify="required" placeholder="請輸入建立時間" autocomplete="off" class="layui-input" id="time">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">模板名稱</label>
                <div class="layui-input-block">
                    <input type="text" name="name" required lay-verify="required" placeholder="請輸入模板名稱" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button type="button" class="layui-btn" lay-submit lay-filter="formDemo" id="add">當即添加</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </div>複製代碼

而後,咱們數據點擊當即添加按鈕,id爲add。咱們對其用Jquery進行ajax請求。

//添加數據
            $('#add').click(function() {
                var create_name = $('input[name="create_name"]').val(); //獲取值
                var name = $('input[name="name"]').val();
                var time = $('input[name="time"]').val();
                if (create_name !== '') {
                    //打開正在加載中彈出層
                    layer.msg('加載中', {
                        icon: 16,
                        shade: 0.01,
                        time: '9999999'
                    });
                    var url = "survey/add_model";//這裏的url是相較與tp5的路由不一樣的地方
                    var data = {
                        create_name: create_name,
                        name: name,
                        time: time
                    }
                    $.post(url, data, function(data) { //使用ajax提交
                        layer.closeAll();
                        if (data.code == 1) { //這裏的code對應返回的狀態碼
                            layer.msg(data.msg, {
                                icon: 6
                            });
                            location.reload();
                        } else {
                            layer.msg(data.msg, {
                                icon: 5
                            });
                        }
                    }, "json");
                }
            });複製代碼

提交的data,就是咱們輸入框獲取的三個值,create_name,name,time。提交到Controller層,若是返回的數據狀態碼爲表明成功的1,則刷新整個頁面,不然,提示錯誤。

而後咱們看看Controller層的代碼。

5.Controller層實現

首先我在util包下定義了一個Api類用來存放咱們的工具類,主要用於返回給前端json數據

package com.sl.example.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

//code=1 success 2 fail 3 warning
public class Api {
    public Map<String,Object> returnJson(int code,String msg){
        Map map=new HashMap();
        map.put("code",code);
        map.put("msg",msg);
        return map;
    }

    public Map<String,Object> returnJson(int code, String msg, List<Map> data){
        Map map=new HashMap();
        map.put("code",code);
        map.put("msg",msg);
        map.put("data",data);
        return map;
    }

    public Map<String,Object> returnJson(int code, String msg, Map data){
        Map map=new HashMap();
        map.put("code",code);
        map.put("msg",msg);
        map.put("data",data);
        return map;
    }
}
複製代碼

返回的數據重載可選,三個爲,code狀態碼,msg信息,data返回的數據。兩個爲,code狀態碼,msg信息。

而後對應的controller層代碼

//增長model
    @RequestMapping(value="Index/survey/add_model")
    @ResponseBody
    public Map<String,Object> addModel(HttpServletRequest req) throws IOException{
        String name = req.getParameter("name");
        String createName=req.getParameter("createName");
        String strtime=req.getParameter("time");//有註解,默認轉換
        if (createName==null){
            return api.returnJson(3,"warning");
        }
        UUID uuid=UUID.randomUUID();
        String modelId=uuid.toString();
        Model model=new Model();
        Date time=string2Date.DateChange(strtime);
        model.setCreateName(createName);
        model.setName(name);
        model.setTime(time);
        model.setModelId(modelId);
        int is_add=modelService.InsertModel(model);
        if (is_add!=0){
            return api.returnJson(1,"添加成功");
        }else{
            return api.returnJson(2,"添加失敗");
        }
    }複製代碼

這裏使用了UUID來建立一個相對惟一的模板ID,調用modelService層的InsertModel方法 傳入model對象,來添加模板

6.Service層實現:

ModelService.java

package com.sl.example.service;


import com.sl.example.pojo.Model;

import java.util.List;

public interface ModelService {
    public List<Model> findAllModel();

    public int deleteModelById(String modelId);

    public int deleteModelByIds(String[] arr);

    public int InsertModel(Model model);

    public Model selectModelById(String modelId);
}
複製代碼

ModelService.Impl:

package com.sl.example.service;


import com.sl.example.pojo.Model;

import java.util.List;

public interface ModelService {
    public List<Model> findAllModel();

    public int deleteModelById(String modelId);

    public int deleteModelByIds(String[] arr);

    public int InsertModel(Model model);

    public Model selectModelById(String modelId);
}
複製代碼

7.功能一覽

而後咱們查看下咱們的功能實現了沒

1.gif

此外還有對應的SSM+maven實現答題管理系統二:模板刪除功能

SSM+maven實現答題管理系統三:題目及選項增刪功能

SSM+maven實現答題管理系統四:答題功能

SSM+maven實現答題管理系統五:統計功能

項目已經部署上線:點我(訪客用戶名zhangsan 密碼123456)

好啦 還有兩小時就下班啦,我要去休息啦,喜歡就給顆小💗💗還有star吧~

項目僅供測試學習使用,拒絕任何形式的商業用途,轉侵刪。
項目源碼關注公衆號Code In Java,回覆"答題管理系統"便可獲取。除此以外,還有Java學習圖譜,數據結構與算法資料等各類資料均可以在後臺獲取。

關注公衆號:Code In Java資源,項目,面試題一網打盡但願與你成爲Java技術的同路人

相關文章
相關標籤/搜索