- pom.xml
<properties>
<spring.version>4.1.5.RELEASE</spring.version>
<mybatis.version>3.2.8</mybatis.version>
<mybatis-spring.version>1.2.2</mybatis-spring.version>
</properties>
<!-- spring配置 -->
<!-- springframe start -->
<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>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.5</version>
</dependency>
<!-- springframe end -->
<!-- mybatis 配置 -->
<!-- mybatis start -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring.version}</version>
</dependency>
<!-- 数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<!-- mysql配置 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.28</version>
</dependency>
2.jdbc.properties
都按照自己的配置写,下面是我的
#mysql
jdbc_driverClassName =com.mysql.jdbc.Driver
jdbc_url =jdbc:mysql://Ip:3306/demo
jdbc_username =root
jdbc_password =123456
maxActive = 200
initialSize = 1
maxWait = 50
maxIdle = 20
minIdle = 3
removeAbandoned = true
removeAbandonedTimeout = 180
connectionProperties =clientEncoding\=UTF-8
3.建立spring-mybaties.xml
把spring-mybaties.xml加到web.xml让它能被扫到
<servlet>
<servlet-name>dispatcherServlet</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>
spring-mybaties.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.2.xsd">
<!-- 扫描文件(自动将servicec层注入) -->
<!-- mybaties与spring结合 -->
<!-- 引入jdbc配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- 配置业务数据源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="driverClassName">
<value>${jdbc_driverClassName}</value>
</property>
<property name="url">
<value>${jdbc_url}</value>
</property>
<property name="username">
<value>${jdbc_username}</value>
</property>
<property name="password">
<value>${jdbc_password}</value>
</property>
<!-- 连接池最大使用连接数 -->
<property name="maxActive">
<value>${maxActive}</value>
</property>
<!-- 初始化连接大小 -->
<property name="initialSize">
<value>${initialSize}</value>
</property>
<!-- 获取连接最大等待时间 -->
<property name="maxWait">
<value>${maxWait}</value>
</property>
<!-- 连接池最大空闲 -->
<property name="maxIdle">
<value>${maxIdle}</value>
</property>
<!-- 连接池最小空闲 -->
<property name="minIdle">
<value>${minIdle}</value>
</property>
<!-- 自动清除无用连接 -->
<property name="removeAbandoned">
<value>${removeAbandoned}</value>
</property>
<!-- 清除无用连接的等待时间 -->
<property name="removeAbandonedTimeout">
<value>${removeAbandonedTimeout}</value>
</property>
<!-- 连接属性 -->
<property name="connectionProperties">
<value>${connectionProperties}</value>
</property>
</bean>
<!-- 扫描dao对应的mapper文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--打印日志 -->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<!-- 自动扫描entity目录, 省掉Configuration.xml里的手工配置 -->
<property name="mapperLocations">
<array>
<value>classpath*:com/demo/demo/mapping/*.xml</value>
</array>
</property>
<property name="plugins">
<array>
<ref bean="pageInterceptor" />
</array>
</property>
<property name="configurationProperties">
<props>
<prop key="dialect">mysql</prop>
</props>
</property>
</bean>
<!-- 扫描DAO接口所在包名,Spring会自动查找其下的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.myobject.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 其它 -->
<!-- 分页拦截 -->
<bean id="pageInterceptor" class="com.myobject.util.PageInterceptor"></bean>
<!-- 拦截器方式配置事物 -->
<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
<tx:method name="batchSave*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
<tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
<tx:method name="modify*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
<tx:method name="delete*" propagation="SUPPORTS" rollback-for="java.lang.Exception" />
<tx:method name="del*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
<tx:method name="remove*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
<tx:method name="change*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
<tx:method name="commit*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
<tx:method name="submit*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
<tx:method name="uploadFile*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
<tx:method name="send*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
<tx:method name="stop*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
<tx:method name="verify*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
<tx:method name="import*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
<tx:method name="handle*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="public*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="reportApply*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="withdrawal*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="get*" propagation="SUPPORTS" rollback-for="java.lang.Exception"/>
<tx:method name="find*" propagation="SUPPORTS" rollback-for="java.lang.Exception"/>
<tx:method name="count*" propagation="SUPPORTS" rollback-for="java.lang.Exception" />
<tx:method name="export*" propagation="SUPPORTS" rollback-for="java.lang.Exception" />
<tx:method name="is*" propagation="SUPPORTS" rollback-for="java.lang.Exception"/>
<tx:method name="statistics*" propagation="SUPPORTS" rollback-for="java.lang.Exception"/>
<!-- <tx:method name="*" propagation="SUPPORTS" rollback-for="java.lang.Exception" /> -->
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="transactionPointcut" expression="execution(* com.demo.*.*.service.impl.*Impl.*(..))" />
<aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />
</aop:config>
</beans>
4.为了方便调试还需要配置Log4j打印日志
加依赖到pom.xml
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.6</version>
</dependency>
添加配置文件log4j.properties
log4j.rootLogger=DEBUG,CONSOLE,ROLLING_FILE
#INFO,WARN,ERROR,ROLLING_FILE
###################
# Console Appender
###################
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.Threshold=INFO
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern= [%p] %d %c - %m%n
########################
# Rolling File
########################
log4j.appender.ROLLING_FILE=org.apache.log4j.RollingFileAppender
log4j.appender.ROLLING_FILE.Threshold=INFO
log4j.appender.ROLLING_FILE.File=logs\\shipData.log
log4j.appender.ROLLING_FILE.Append=true
log4j.appender.ROLLING_FILE.MaxFileSize=5000KB
log4j.appender.ROLLING_FILE.MaxBackupIndex=2
log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.ROLLING_FILE.layout.ConversionPattern=[%p] %d %c - %m%n
5.在pom.xml中映射接口
<servlet>
<servlet-name>dispatcherServlet</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>dispatcherServlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<!-- 扫描全包 -->
<context:component-scan base-package="com.myobject.*" />
<mvc:annotation-driven />
<!-- 读取配置文件,在代码里使用注解方式注入 -->
<bean id="config"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<array>
<value>classpath*:demo.properties</value>
</array>
</property>
</bean>
<!-- 加载国际化资源 -->
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="defaultEncoding" value="UTF-8" />
<property name="fallbackToSystemLocale" value="false" />
<!-- 不抛出NoSuchMessageException, 使用messageKey作为返回值 -->
<property name="useCodeAsDefaultMessage" value="true" />
<property name="basenames">
<list>
<value>classpath:/languages/common_msg</value>
<value>classpath:/languages/biz_msg</value>
<!-- <value>classpath:formbean/validation</value> -->
</list>
</property>
</bean>
<bean id="resourceManager" class="com.demo.log.caches.SpringBeanCaches">
<property name="messageSource">
<ref bean="messageSource" />
</property>
</bean>
</beans>
6.程序
js
var demo = (function ($) {
//TODO 变量保存
var status = 0;
//TODO 数据url
var urlPath = {
initUrl:"rest/demo/findByPage",
saveUrl:"rest/demo/save",
editUrl:"rest/demo/update",
delUrl:"rest/demo/delete",
seeUrl:"rest/demo/findById/"
};
//获取ajax数据
// var _init = function(){
// $.ajax({
// url :urlPath.initUrl,
// dataType :'json',
// type : "POST",
// async : false,
// success : function(result) {
// if (result["code"] === 200){
// localData = _dataConvert(result["Result"]);
// }else {
// Messager.alert({
// Msg: result["msg"],
// iconImg: "warning",
// isModal: false
// });
// }
// }
// });
// };
//TODO 初始化方法入口
var _init = function () {
//装入表格
$("#demoTable").jqGrid({
url:urlPath.initUrl,
mtype : "POST",
datatype : "JSON",
colModel : [ {
label : "Id",
name : "id",
key : true,
hidden : true
}, {
label : "接口名称",
name : "name",
sortable:true,
width:"100%",
align:"center"
},{
label : "访问路径",
name : "requestUrl",
sortable:true,
width:"200%",
align:"center"
},{
label : "输入字段",
name : "inputContent",
sortable:true,
width:"200%",
align:"center"
}, {
label : "输出结果",
name : "outputContent",
width:"200%",
sortable:true,
align:"center"
},{
label : "描述",
name : "description",
sortable:true,
width:"200%",
align:"center"
} ],
loadonce : false,
forceFit: true,
viewrecords : true,
//autowidth : true,
height : false,
rownumbers : true,
multiselect : true,
multiboxonly : true,
rowNum : 10, // 每页显示记录数
rowList : [10, 15, 20 ], // 用于改变显示行数的下拉列表框的元素数组
pager : "#infoPage"
});
$("#demoTable").jqGrid({autowidth:false}).setGridWidth($(window).width()-300);
};
var _reloadGrid = function(){
$("#demoTable").trigger("reloadGrid")
};
/*搜索*/
_search = function(){
$("#demoTable").jqGrid('setGridParam',
{postData : {
"name":$("#searchDataForm input[name='name']").val(),
// "outputContent":$("#searchDataForm input[name='outputContent']").val()
},
page : 1
}).trigger("reloadGrid");
},
// 新增
_add = function(titleName){
status = 0;
_clearForm();
toolMethod.showPanel("#demoAddDialog", titleName, false);
};
/*清空表单*/
_clearForm = function(){
$("#interfaceName").val("");
$("#requestUrl").html("");
$("#interfaceInputContent").html("");
$("#interfaceOutputContent").html("");
$("#description").html("");
},
/*确认提交*/
_submit = function(){
if(status == 0){
_saveEditSubmit(urlPath.saveUrl);
}else {
_saveEditSubmit(urlPath.editUrl);
}
},
//确定提交
_saveEditSubmit = function (url) {
$.ajax({
url: url,
dataType: 'json',
type: 'POST',
data:$("#demoForm").serialize(),
async: false,
success: function(json) {
if(json.code === 1) {
toolMethod.closePanel("#demoAddDialog", true);
$("#demoTable").jqGrid('setGridParam', {postData: {}, page: 1}).trigger("reloadGrid");
Messager.show({Msg:json["msg"], isModal: false});
}else {
Messager.alert({Msg :toolMethod.writeObj(json["data"]),iconImg : "error",isModal : false});
return false;
}
},
});
};
/*编辑*/
_edit = function(url,id){
status = 1;
var ids = $("#demoTable").jqGrid('getGridParam', 'selarrrow');
var rowid = $("#demoTable").jqGrid("getGridParam", "selrow");
var len = ids.length;
if (len <= 0) {
Messager.alert({Msg: prompt.noSelectedEdit});
return false;
} else if (len > 1) {
Messager.alert({Msg: prompt.moreSelectedEdit});
return false;
} else {
var info = _getDataById(urlPath.seeUrl,rowid);
if(info){
_clearForm();
toolMethod.setFormFieldEditHtml(info,$("#demoAddDialog"));
toolMethod.showPanel("#demoAddDialog", "编辑接口描述");
}else{
return false;
}
}
},
/*查看操作*/
_see = function(){
var ids = $("#demoTable").jqGrid('getGridParam', 'selarrrow');
var rowid = $("#demoTable").jqGrid("getGridParam", "selrow");
var len = ids.length;
if (len <= 0) {
Messager.alert({Msg: prompt.noSelectedLook});
return false;
} else if (len > 1) {
Messager.alert({Msg: prompt.moreSelectedLook});
return false;
} else {
var seeData = _getDataById(urlPath.seeUrl,rowid);
/*将获取的数据填充在查看弹框中*/
toolMethod.setFormFieldDivHtml(seeData,$("#demoSeeDialog"));
toolMethod.showPanel("#demoSeeDialog", "查看接口描述");
}
};
/*根据Id请求*/
_getDataById = function(url,id){
var receiveData = null;
$.ajax({
url :url+id,
dataType : "json",
type : "POST",
data : {
"id" : id
},
async : false,
success : function(json) {
if(json["code"] === 1){
receiveData = json["data"];
}else{
receiveData = null;
Messager.alert({Msg: json["msg"],iconImg: "warning",isModal: false});
}
}
});
return receiveData;
},
/*删除操作*/
_del = function(){
var ids = $("#demoTable").jqGrid('getGridParam', 'selarrrow');
var len = ids.length;
if (len <= 0) {
Messager.alert({Msg: prompt.noSelectedDelete});
return;
} else {
/*确定是否删除 确定按钮-----flag:true删除*/
Messager.confirm({Msg:'确认删除数据?', iconImg: 'question',btnOk:'删除', 'isModal': true}).on(function (flag) {
if (flag) {
$.ajax({
url: urlPath.delUrl + "/" + ids,
dataType: 'JSON',
type: "DELETE",
async: false,
success: function (data) {
if (data["code"] === 1) {
Messager.show({Msg: data["msg"], isModal: false});
$("#demoTable").jqGrid('setGridParam', {postData: {},page: 1}).trigger("reloadGrid");
} else {
Messager.alert({Msg: data["msg"], iconImg: "warning", isModal: false});
}
}
});
}
})
}
};
//返回共有方法,以及对外提供的方法
return {
init: _init,
reloadGrid: _reloadGrid,
add: _add,
edit: _edit,
clearForm: _clearForm,
see: _see,
del: _del,
submit: _submit,
search: _search
};
})(jQuery);
$(function () {
/*提交表单进行验证*/
$("#demoForm").html5Validate(function(){
demo.submit();
});
demo.init();
// setInterval(
// "dataManModule.init()",setting.updateTime);
// setInterval(
// "dataManModule.reloadGrid()",setting.updateTime);
// $(window).resize(function(){
// $(window).unbind("onresize");
// $("#demoTable").jqGrid({autowidth:false}).setGridWidth($(window).width()-300);
// $(window).bind("onresize", this);
// });
});
controller
/**
* 文件名:DemoController.java
*/
package com.myobject.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.myobject.formbean.demoForm;
import com.myobject.model.DemoEntity;
import com.myobject.service.IDemo;
import com.myobject.util.CommonConstant;
import com.demo.base.entity.Page;
import com.demo.base.exception.CustomException;
import com.demo.base.validation.Save;
import com.demo.log.ControlLogModel;
import com.demo.log.LoggingManager;
import com.demo.utils.common.SystemContants;
import com.demo.utils.response.ResultJQGrid;
import com.demo.utils.response.ResultMessage;
/**
* 〈一句话功能简述〉管理控制层
* 〈功能详细描述〉与前端的信息管理模块数据交互的类,信息管理模块后台逻辑处理的入口。
*/
@Scope(value = "prototype")
@Controller
@RequestMapping(value = "/demo")
public class DemoController extends ResultController
{
/** 日志记录器 */
private static final LoggingManager LOGGER =
LoggingManager.getLogger(DemoController.class);
/** 业务接口 */
@Resource(name = "demoService")
private IDemo demoService;
@RequestMapping(value = "/save", method = RequestMethod.POST)
@ResponseBody
public ResultMessage save(@Validated(value = Save.class) demoForm entity,
BindingResult bindingResult)
throws Exception {
// 记录程序进入方法调试日志
LOGGER.debug(SystemContants.DEBUG_START, entity);
// 验证字段的合法性,true为存在非法输入信息,FALSE验证通过
boolean isResult = addErorrs(bindingResult);
if (isResult) {
// 设置响应消息
sendData(getValidErorrs(), CommonConstant.FORMVALID_FAIL_OPTION);
// 记录操作失败信息(存入文件)
LOGGER.info(CommonConstant.FORMVALID_FAIL_OPTION, entity);
// 保存操作日志 记录操作失败(存入数据库)
controlLog(ControlLogModel.CONTROL_RESULT_FAIL,
CommonConstant.FORMVALID_FAIL_OPTION, "接口描述",
getValidErorrs()).setErrorMessage(CommonConstant.FORMVALID_FAIL_OPTION)
.recordLog();
}
else {
DemoEntity info = new DemoEntity();
copyProperties(entity, info);
// 从session中获取当前用户信息
// BizUserEntity user = getUser();
info.setCreateBy("root");
info.setUpdateBy("root");
DemoEntity result =
this.demoService.save(info);
// 记录操作成功信息
LOGGER.info(CommonConstant.SAVE_SUC_OPTION, result);
// 设置响应消息
sendCode(CommonConstant.SAVE_SUC_OPTION);
}
// 记录程序结束方法调试日志
LOGGER.debug(SystemContants.DEBUG_END, entity);
return sendMessage();
}
/**
* 〈一句话功能简述〉编辑〈功能详细描述〉
*/
@RequestMapping(value = "/update", method = RequestMethod.POST)
@ResponseBody
public ResultMessage update(
@Validated(value = Update.class) InterDesciptionForm entity,
BindingResult bindingResult)
throws Exception {
// 记录程序进入方法调试日志
LOGGER.debug(SystemContants.DEBUG_START, entity);
boolean isResult = addErorrs(bindingResult);
if (isResult) {
// 设置响应消息
sendData(getValidErorrs(), CommonConstant.FORMVALID_FAIL_OPTION);
// 记录操作失败信息(存入文件)
LOGGER.info(CommonConstant.FORMVALID_FAIL_OPTION, entity);
// 保存操作日志 记录操作失败(存入数据库)
controlLog(ControlLogModel.CONTROL_RESULT_FAIL,
CommonConstant.FORMVALID_FAIL_OPTION, "编辑接口描述",
getValidErorrs()).setErrorMessage(CommonConstant.FORMVALID_FAIL_OPTION)
.recordLog();
}
else {
InterfaceInfoEntity info = new InterfaceInfoEntity();
copyProperties(entity, info);
// 从session中获取当前用户信息
info.setCreateBy("root");
info.setUpdateBy("root");
InterfaceInfoEntity result = this.interfaceDescriptionService.update(info);
// 记录操作成功信息
LOGGER.info(CommonConstant.UPDATE_SUC_OPTION, result);
// 保存操作日志 记录操作成功
controlLog(ControlLogModel.CONTROL_RESULT_SUCCESS,
CommonConstant.UPDATE_SUC_OPTION, "编辑接口描述 ",
result).recordLog();
// 设置响应消息
sendCode(CommonConstant.UPDATE_SUC_OPTION);
}
// 记录程序结束方法调试日志
LOGGER.debug(SystemContants.DEBUG_END, entity);
return sendMessage();
}
/**
* 〈一句话功能简述〉查看〈功能详细描述〉
*/
@RequestMapping(value = "/findById/{id}", method = RequestMethod.POST)
@ResponseBody
public Object findById(@PathVariable String id)
throws Exception {
// 记录程序进入方法调试日志
LOGGER.debug(SystemContants.DEBUG_START, id);
// 从session中获取当前用户信息
Map<String, Object> params = new HashMap<String, Object>();
params.put("updateBy", "root");
params.put("deptId", "root");
params.put("id", id);
DemoEntity entity = this.demoService.findById(params);
// 设置响应消息
sendData(entity, CommonConstant.FIND_SUC_OPTION);
// 记录操作成功信息
LOGGER.info(CommonConstant.FIND_SUC_OPTION, id);
// 记录程序执行方法结束调试日志
LOGGER.debug(SystemContants.DEBUG_END);
// 发送响应消息
return sendMessage();
}
/**
* 〈一句话功能简述〉删除 〈功能详细描述〉
*/
@RequestMapping(value = "/delete/{ids}", method = RequestMethod.DELETE)
@ResponseBody
public ResultMessage deletes(@PathVariable String... ids)
throws Exception {
LOGGER.debug(SystemContants.DEBUG_START, ids);
Map<String, Object> map = new HashMap<String, Object>();
boolean result = this.demoService.deletes(ids);
// 记录操作成功信息
LOGGER.info(CommonConstant.DELETE_SUC_OPTION, result);
// 设置响应消息
sendCode(CommonConstant.DELETE_SUC_OPTION);
// 记录程序执行方法结束调试日志
LOGGER.debug(SystemContants.DEBUG_END);
// 发送响应消息
return sendMessage();
}
/**
* 〈一句话功能简述〉查询〈功能详细描述〉
*/
@RequestMapping(value = "/findByPage", method = RequestMethod.POST)
@ResponseBody
public ResultMessage findByPage(demoForm entity)
throws Exception {
// 记录程序进入方法调试日志
LOGGER.debug(SystemContants.DEBUG_START, entity);
Map<String, Object> params = entity.handlePageParas();
// Map<String, Object> params = new HashMap<String, Object>();
List<DemoEntity> list =
this.demoService.findByParams(params);
Page page = (Page) params.get("page");
setJQGrid(list,
page.getTotalCount(),
entity.getCurrentPage(),
entity.getPageSize(),
CommonConstant.FIND_SUC_OPTION);
// 记录操作成功信息
LOGGER.info(CommonConstant.FIND_SUC_OPTION, entity);
// 记录程序执行方法结束调试日志
LOGGER.debug(SystemContants.DEBUG_END);
// 发送响应消息
return (ResultJQGrid) sendMessage();
}
/**
* {@inheritDoc}
*
*/
@Override
protected LoggingManager logger() {
return LOGGER;
}
}
service接口
package com.myobject.service;
import java.util.List;
import java.util.Map;
import com.MyObject.demo.model.DemoEntity;
import com.MyObject.base.service.IBaseService;
/**
* 〈一句话功能简述〉系统接口描述业务接口
* 〈功能详细描述〉
*/
public interface IDemo extends IBaseService<DemoEntity> {
/**
* 〈一句话功能简述〉查询以及搜索当前部门接收的接口描述
*/
List<DemoEntity> findByParams(Map<String, Object> params)
throws Exception;
/**
* 〈一句话功能简述〉查看系统接口描述信息
*/
DemoEntity findById(Map<String, Object> params)
throws Exception;
/**
*
* 〈一句话功能简述〉批量删除接口描述信息
*/
boolean deletes(String... ids)
throws Exception;
}
service实现
package com.myobject.service.impl;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.MyObject.demo.dao.IDemoDao;
import com.MyObject.demo.model.DemoEntity;
import com.MyObject.demo.service.IDemo;
import com.MyObject.demo.util.CommonConstant;
import com.MyObject.base.dao.IBaseDao;
import com.MyObject.base.exception.CustomException;
import com.MyObject.base.service.impl.BaseServiceImpl;
import com.MyObject.log.LoggingManager;
import com.MyObject.utils.basetools.StringUtils;
import com.MyObject.utils.common.SystemContants;
/**
* 〈一句话功能简述〉业务实现接口 〈功能详细描述〉
*
* @author qxj
* @version [版本号, 2015年11月24日]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
@Service(value = "demoService")
public class DemoImpl extends BaseServiceImpl<DemoEntity> implements
IDemo {
/** 日志记录器 */
private static final LoggingManager LOGGER =
LoggingManager.getLogger(DemoImpl.class);
/** 数据接口 */
@Resource(name = "demoDao")
private IDemoDao DemoDao;
/**
* {@inheritDoc}
*
*/
@Override
public IBaseDao<DemoEntity> getBaseDao() {
return DemoDao;
}
/**
* 〈一句话功能简述〉 保存 〈功能详细描述〉
*/
public DemoEntity save(DemoEntity entity)
throws Exception {
entity.setId(StringUtils.createUUID());
entity.setCreateTime(new Date());
entity.setUpdateTime(new Date());
entity.setRemove(SystemContants.ON);
this.DemoDao.save(entity);
return entity;
}
/**
* {@inheritDoc}
*
*/
@Override
public InterfaceInfoEntity update(InterfaceInfoEntity entity)
throws Exception {
// 记录程序进入方法调试日志
LOGGER.debug(SystemContants.DEBUG_START, entity);
try {
this.InterfaceDesDao.update(entity);
LOGGER.info(CommonConstant.UPDATE_SUC_OPTION, entity);
}
catch (Exception e) {
transactionException(CommonConstant.SYS_EXCEPTION, e, entity);
}
// 记录程序进入方法调试日志
LOGGER.debug(SystemContants.DEBUG_END, entity);
return entity;
}
/**
* {@inheritDoc}
*
*/
@Override
public List<DemoEntity> findByParams(Map<String, Object> params)
throws Exception {
// 记录程序进入方法调试日志
LOGGER.debug(SystemContants.DEBUG_START, params);
List<DemoEntity> infoList = null;
try {
params.put("remove", SystemContants.ON);
infoList = this.DemoDao.findByParams(params);
// 记录操作成功信息
LOGGER.info(CommonConstant.FIND_SUC_OPTION, infoList);
}
catch (Exception e) {
transactionException(CommonConstant.SYS_EXCEPTION, e, params);
}
// 记录程序进入方法调试日志
LOGGER.debug(SystemContants.DEBUG_END, params);
return infoList;
}
/**
* {@inheritDoc}
*
*/
@Override
public DemoEntity findById(Map<String, Object> params)
throws Exception {
// 记录程序进入方法调试日志
LOGGER.debug(SystemContants.DEBUG_START, params);
params.put("remove", SystemContants.ON);
DemoEntity interInfo = null;
try {
interInfo = this.DemoDao.findById(params);
// 记录操作成功信息
LOGGER.info(CommonConstant.FIND_SUC_OPTION, interInfo);
}
catch (Exception e) {
transactionException(CommonConstant.SYS_EXCEPTION, e, params);
}
// 记录程序进入方法调试日志
LOGGER.debug(SystemContants.DEBUG_END, params);
return interInfo;
}
/**
* {@inheritDoc}
*
*/
@Override
public boolean deletes(String... ids)
throws Exception {
// 记录程序进入方法调试日志
LOGGER.debug(SystemContants.DEBUG_START, ids);
Map<String, Object> map = new HashMap<String, Object>();
map.put("remove", SystemContants.OFF);
map.put("ids", ids);
boolean istrue = false;
try {
istrue = this.DemoDao.deletes(map) > 0 ? true : false;
}
catch (Exception e) {
throw new CustomException(CommonConstant.SYS_EXCEPTION);
}
// 记录程序进入方法调试日志
LOGGER.debug(SystemContants.DEBUG_END, ids);
return istrue;
}
/**
* {@inheritDoc}
*
*/
@Override
protected LoggingManager logger() {
return LOGGER;
}
}
dao接口
/*
* 文件名:ISystemNoticeDao.java
*/
package com.myobject.dao;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.myobject.model.DemoEntity;
import com.demo.base.dao.IBaseDao;
/**
* 〈一句话功能简述〉状态数据处理层接口。
* 〈功能详细描述〉状态数据处理层接口,主要用于接收mapper.xml文件中数据操作方法返回的操作。
*/
@Repository(value = "demoDao")
public interface IDemoDaoextends IBaseDao<DemoEntity> {
int save(DemoEntity arg0) throws Exception;
DemoEntity findById(Map<String, Object> params)
throws Exception;
int deletes(Map<String, Object> ids)
throws Exception;
List<DemoEntity> findByParams(Map<String, Object> params) throws Exception;
}
mapper
<?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.MyObject.dao.IDemoDao">
<resultMap id="BaseResultMap" type="com.MyObject.model.DemoEntity">
<id column="id" jdbcType="VARCHAR" property="id" />
<result column="input_content" jdbcType="VARCHAR" property="inputContent" />
<result column="output_content" jdbcType="VARCHAR" property="outputContent" />
<result column="remove" jdbcType="CHAR" property="remove" />
<result column="create_by" jdbcType="VARCHAR" property="createBy" />
<result column="create_time" jdbcType="DATE" property="createTime" />
<result column="update_by" jdbcType="VARCHAR" property="updateBy" />
<result column="update_time" jdbcType="DATE" property="updateTime" />
</resultMap>
<sql id="Base_Column_List">
id, input_content, output_content, remove, create_by, create_time, update_by, update_time
</sql>
<insert id="save" parameterType="com.Myobject.model.DemoEntity">
insert into t_demo
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="inputContent != null">
input_content,
</if>
<if test="outputContent != null">
output_content,
</if>
<if test="remove != null">
remove,
</if>
<if test="createBy != null">
create_by,
</if>
<if test="createTime != null">
create_time,
</if>
<if test="updateBy != null">
update_by,
</if>
<if test="updateTime != null">
update_time,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=VARCHAR},
</if>
<if test="inputContent != null">
#{inputContent,jdbcType=VARCHAR},
</if>
<if test="outputContent != null">
#{outputContent,jdbcType=VARCHAR},
</if>
<if test="remove != null">
#{remove,jdbcType=CHAR},
</if>
<if test="createBy != null">
#{createBy,jdbcType=VARCHAR},
</if>
<if test="createTime != null">
#{createTime,jdbcType=DATE},
</if>
<if test="updateBy != null">
#{updateBy,jdbcType=VARCHAR},
</if>
<if test="updateTime != null">
#{updateTime,jdbcType=DATE},
</if>
</trim>
</insert>
<update id="update" parameterType="com.Myobject.model.DemoEntity">
update t_interface_info
<set>
<if test="name != null">
name = #{name,jdbcType=VARCHAR},
</if>
<if test="inputContent != null">
input_content = #{inputContent,jdbcType=VARCHAR},
</if>
<if test="outputContent != null">
output_content = #{outputContent,jdbcType=CHAR},
</if>
<if test="requestUrl != null">
request_url = #{requestUrl,jdbcType=VARCHAR},
</if>
<if test="description != null">
description = #{description,jdbcType=VARCHAR},
</if>
<if test="createBy != null">
create_by = #{createBy,jdbcType=VARCHAR},
</if>
<if test="createTime != null">
create_time = #{createTime,jdbcType=DATE},
</if>
<if test="updateBy != null">
update_by = #{updateBy,jdbcType=VARCHAR},
</if>
<if test="updateTime != null">
update_time = #{updateTime,jdbcType=DATE},
</if>
<if test="remove != null">
remove = #{remove,jdbcType=CHAR},
</if>
</set>
where id = #{id,jdbcType=VARCHAR}
</update>
<select id="findById" parameterType="java.lang.String" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from t_demo
<where>
id = #{id,jdbcType=VARCHAR}
</where>
</select>
<!-- 查询 -->
<select id="findByParams" resultMap="BaseResultMap"
parameterType="java.util.Map">
SELECT
<include refid="Base_Column_List" />
FROM t_demo
<where>
<if test="inputContent !=null and inputContent !=''">
AND input_content LIKE CONCAT(CONCAT('%',#{inputContent}),'%')
</if>
<if test="outputContent !=null and outputContent !=''">
AND output_content LIKE CONCAT(CONCAT('%',#{outputContent}),'%')
</if>
AND remove = #{remove,jdbcType=VARCHAR}
</where>
</select>
<!-- 逻辑删除某条记录 -->
<update id="deletes" parameterType="java.util.Map">
update
t_demo
<set>
update_by = #{updateBy,jdbcType=VARCHAR},
update_time = #{updateTime,jdbcType=TIMESTAMP},
remove = #{remove,jdbcType=CHAR}
</set>
WHERE id IN
<foreach item="item" index="index" collection="ids" open="("
separator="," close=")">
#{item}
</foreach>
</update>
</mapper>