最近項(xiàng)目比較忙,然后又生病了,都沒時間寫博客了QAQ。這次我?guī)砹薙SM框架搭建的一個答題管理系統(tǒng),之前我用的tp框架構(gòu)建的答題管理系統(tǒng),這次我用SSM框架重構(gòu)了一下

1.前期準(zhǔn)備
SSM架構(gòu)的相關(guān)知識(Spring+Springmvc+mybatis)
IDEA/eclipse/myeclipse編譯器
layui文檔的bang助:layui開發(fā)使用文檔
默認(rèn)的maven配置
Navicat/mysql workbench等數(shù)據(jù)庫可視化管理工具
使用IDEA創(chuàng)建maven項(xiàng)目
2.架構(gòu)設(shè)計(jì)(mvc)

首先將resources包設(shè)置為Resource Root
將webapp包設(shè)置為Web項(xiàng)目目錄
指定Web目錄:

指定Spring配置文件目錄:

model層采用mybatis進(jìn)行持久化處理
mybatis generator插件進(jìn)行逆向工程,
以下說明幾個配置文件:
applicationContext:Springmvc配置文件
<?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:數(shù)據(jù)庫連接池配置文件
<?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}"/>
<!-- 最大空閑值.當(dāng)經(jīng)過一個高峰時間后,連接池可以慢慢將已經(jīng)用不到的連接慢慢釋放一部分,一直減少到maxIdle為止 -->
<property name="maxIdle" value="${db.maxIdle}"/>
<!-- 最小空閑值.當(dāng)空閑的連接數(shù)少于閥值時,連接池就會預(yù)申請去一些連接,以免洪峰來時來不及申請 -->
<property name="minIdle" value="${db.minIdle}"/>
<!-- 最大建立連接等待時間。如果超過此時間將接到異常。設(shè)為-1表示無限制 -->
<property name="maxWait" value="${db.maxWait}"/>
<!--#給出一條簡單的sql語句進(jìn)行驗(yàn)證 -->
<!--<property name="validationQuery" value="select getdate()" />-->
<property name="defaultAutoCommit" value="${db.defaultAutoCommit}"/>
<!-- 回收被遺棄的(一般是忘了釋放的)數(shù)據(jù)庫連接到連接池中 -->
<!--<property name="removeAbandoned" value="true" />-->
<!-- 數(shù)據(jù)庫連接過多長時間不用將被視為被遺棄而收回連接池中 -->
<!--<property name="removeAbandonedTimeout" value="120" />-->
<!-- #連接的超時時間,默認(rèn)為半小時。 -->
<property name="minEvictableIdleTimeMillis" value="${db.minEvictableIdleTimeMillis}"/>
<!--# 失效檢查線程運(yùn)行時間間隔,要小于MySQL默認(rèn)-->
<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進(jìn)行聲明式事務(wù)管理需要聲明下面這行 -->
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
<!-- 事務(wù)管理 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
<!--提交失敗是否回滾-->
<property name="rollbackOnCommitFailure" value="true"/>
</bean>
</beans>
datasource.properties:數(shù)據(jù)庫配置文件
# 配置下載的驅(qū)動包的位置
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://數(shù)據(jù)庫IP:數(shù)據(jù)庫 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設(shè)置數(shù)據(jù)庫連接-->
<!--2.javaModelGenerator設(shè)置類的生成位置-->
<!--3.sqlMapGenerator設(shè)置生成xml的位置-->
<!--4.javaClientGenerator設(shè)置生成dao層接口的位置-->
<!--5.table設(shè)置要進(jìn)行逆向工程的表名以及要生成的實(shí)體類的名稱-->
<properties resource="datasource.properties"></properties>
<!--指定特定數(shù)據(jù)庫的jdbc驅(qū)動jar包的位置-->
<classPathEntry location="${db.driverLocation}"/>
<context id="default" targetRuntime="MyBatis3">
<!-- optional,旨在創(chuàng)建class時,對注釋進(jìn)行控制 -->
<commentGenerator>
<property name="suppressDate" value="true"/>
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--jdbc的數(shù)據(jù)庫連接 -->
<jdbcConnection
driverClass="${db.driverClassName}"
connectionURL="${db.url}"
userId="${db.username}"
password="${db.password}">
</jdbcConnection>
<!-- 非必需,類型處理器,在數(shù)據(jù)庫類型和java類型之間的轉(zhuǎn)換控制-->
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- Model模型生成器,用來生成含有主鍵key的類,記錄類 以及查詢Example類
targetPackage 指定生成的model生成所在的包名
targetProject 指定在該項(xiàng)目下所在的路徑
-->
<javaModelGenerator targetPackage="com.sl.example.pojo" targetProject="./src/main/java">
<!-- 是否允許子包,即targetPackage.schemaName.tableName -->
<property name="enableSubPackages" value="false"/>
<!-- 是否對model添加 構(gòu)造函數(shù) -->
<property name="constructorBased" value="true"/>
<!-- 是否對類CHAR類型的列的數(shù)據(jù)進(jìn)行trim操作 -->
<property name="trimStrings" value="true"/>
<!-- 建立的Model對象是否不可改變 即生成的Model對象不會有 setter方法,只有構(gòu)造方法 -->
<property name="immutable" value="false"/>
</javaModelGenerator>
<!--mapper映射文件生成所在的目錄 為每一個數(shù)據(jù)庫的表生成對應(yīng)的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 和相應(yīng)的Mapper對象
type="XMLMAPPER",生成SQLMap XML文件和獨(dú)立的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: 數(shù)據(jù)庫表名
domainObjectName: 生成的類名
enableCountByExample: 是否可以通過對象查數(shù)量
enableUpdateByExample: 是否可以通過對象進(jìn)行更新
-->
<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包下對應(yīng)控制器
dao包下是逆向生成的DAO數(shù)據(jù)層
pojo包下是逆向生成的實(shí)體類
service是我們寫的業(yè)務(wù)層
util是我們的工具類

最后的最后,我們數(shù)據(jù)庫設(shè)計(jì):
既然是答題管理系統(tǒng)。
一套題(即一個模板)(model表)對應(yīng)多個題目(qsn表)
一個題目(qsn表)對應(yīng)多個答案(detail表)
然后Navicat表設(shè)計(jì)如下:
model表:(t_gr_是前綴 rmkX是備用字段都不用管)

qsn表:(這里我沒有設(shè)置外鍵 實(shí)際上qsn表的model_id應(yīng)該設(shè)置外鍵)

detail表:(同上)

好了 說了那么多 終于做好所有的準(zhǔn)備了,可以正式進(jìn)入我們的開發(fā)了。
3.本章目標(biāo)
與thinkphp實(shí)現(xiàn)答題管理系統(tǒng)對應(yīng),我們依舊先實(shí)現(xiàn)model表(答題模板的增加功能模塊的實(shí)現(xiàn))
4.View層實(shí)現(xiàn)(Jquery+layui)
首先是添加模板的View層實(shí)現(xiàn)。

引用了layui的按鈕組樣式 id為btn-add的按鈕 即為添加模板按鈕

點(diǎn)擊添加模板 我們用Jquery設(shè)置其彈出了一個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: "添加模板"
});
});
如下

input框有三個,分別對應(yīng)數(shù)據(jù)庫的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">創(chuàng)建人名字</label>
<div class="layui-input-block">
<input type="text" name="create_name" required lay-verify="required" placeholder="請輸入創(chuàng)建人姓名" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">創(chuàng)建時間</label>
<div class="layui-input-block">
<input type="text" name="time" required lay-verify="required" placeholder="請輸入創(chuàng)建時間" 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>
然后,我們數(shù)據(jù)點(diǎn)擊立即添加按鈕,id為add。我們對其用Jquery進(jìn)行ajax請求。
//添加數(shù)據(jù)
$('#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對應(yīng)返回的狀態(tài)碼
layer.msg(data.msg, {
icon: 6
});
location.reload();
} else {
layer.msg(data.msg, {
icon: 5
});
}
}, "json");
}
});
提交的data,就是我們輸入框獲取的三個值,create_name,name,time。
提交到Controller層,如果返回的數(shù)據(jù)狀態(tài)碼為代表成功的1,則刷新整個頁面,否則,提示錯誤。
然后我們看看Controller層的代碼。
5.Controller層實(shí)現(xiàn)
首先我在util包下定義了一個Api類用來存放我們的工具類,主要用于返回給前端json數(shù)據(jù)
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;
}
}
返回的數(shù)據(jù)重載可選,三個為,code狀態(tài)碼,msg信息,data返回的數(shù)據(jù)。
兩個為,code狀態(tài)碼,msg信息。
然后對應(yīng)的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");//有注解,默認(rèn)轉(zhuǎn)換
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來創(chuàng)建一個相對唯一的模板ID,調(diào)用modelService層的InsertModel方法 傳入model對象,來添加模板
6.Service層實(shí)現(xiàn):
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.功能一覽
然后我們查看下我們的功能實(shí)現(xiàn)了沒

此外還有對應(yīng)的
SSM+maven實(shí)現(xiàn)答題管理系統(tǒng)二:模板刪除功能
SSM+maven實(shí)現(xiàn)答題管理系統(tǒng)三:題目及選項(xiàng)增刪功能
SSM+maven實(shí)現(xiàn)答題管理系統(tǒng)四:答題功能
SSM+maven實(shí)現(xiàn)答題管理系統(tǒng)五:統(tǒng)計(jì)功能
項(xiàng)目已經(jīng)部署上線:點(diǎn)我(訪客用戶名zhangsan 密碼123456)
好啦 還有兩小時就下班啦,我要去休息啦,喜歡就給顆小????還有star吧~