1、前端列表初始化。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<link rel="stylesheet" href="ace_base/css/jquery-ui.css" />
<link rel="stylesheet" href="ace_base/css/ui.jqgrid.css" />
<link rel="stylesheet" href="ace_base/css/datepicker.css" />
<link rel="stylesheet" href="ace_base/css/bootstrap-multiselect.css" />
<link rel="stylesheet" href="ace_base/css/chosen.css" />
</HEAD>
<BODY>
<div class="container-fluid">
<div class="col-md-12">
<div class="col-md-3">
<label>姓名</label>
<input role="textbox" type="text" class="FormElement ui-widget-content ui-corner-all" id="name_sel" />
</div>
<div class="col-md-3">
<label>姓别</label>
<select id="sex_sel" class="form-control">
<option value=""></option>
<option value="0">男</option>
<option value="1">女</option>
</select>
</div>
<div class="col-md-3" style="text-align:right;">
<button class="btn btn-primary btn-sm" id="search" type="button" style="padding-bottom: 6px; border-bottom-width: 1px; padding-top: 5px; border-top-width: 1px;">查询</button>
<button class="btn btn-primary btn-sm" id="search_all" type="button" style="padding-bottom: 6px; border-bottom-width: 1px; padding-top: 5px; border-top-width: 1px;">重置</button>
</div>
</div>
</div>
<!-- /筛选 -->
<table id="grid-table"></table>
<div id="grid-pager"></div>
<!--列表-->
<script src="ace_base/js/jqGrid/jquery.jqGrid.src.js"></script>
<script src="ace_base/js/jqGrid/i18n/grid.locale-cn.js"></script>
<!--/列表-->
<!--dialog -->
<script src="ace_base/js/jquery-ui.js"></script>
<!--/dialog -->
<!--时间-->
<script src="ace_base/js/date-time/bootstrap-datepicker.js" charset="gb2312"></script>
<!--/时间-->
<script type="text/javascript" src="ace_base/js/chosen.jquery.js"></script>
<script type="text/javascript">
//定义表格id
var grid_selector = "#grid-table";
var pager_selector = "#grid-pager";
jQuery(function($) {
//设置适应界面
$(window).on('resize.jqGrid', function() {
ss = pageSize();
$(grid_selector).jqGrid('setGridWidth', $(".page-content").width()); // 设置jQgrid的宽度
$(grid_selector).jqGrid('setGridHeight', ss.WinH - 300); // 设置jQgrid的高度
function pageSize() { // 获取浏览器的宽高
var winW, winH;
if (window.innerHeight) {// all except IE
winW = window.innerWidth;
winH = window.innerHeight;
} else if (document.documentElement
&& document.documentElement.clientHeight) {// IE 6 Strict
// Mode
winW = document.documentElement.clientWidth;
winH = document.documentElement.clientHeight;
} else if (document.body) { // other
winW = document.body.clientWidth;
winH = document.body.clientHeight;
} // for small pages with total size less then the viewport
return {
WinW : winW,
WinH : winH
};
// 弹出框样式初始化
$.widget("ui.dialog", $.extend({}, $.ui.dialog.prototype, {
_title : function(title) {
var $title = this.options.title || ' '
if (("title_html" in this.options)
&& this.options.title_html == true)
title.html($title);
else
title.text($title);
}
}));
//列表jqGrid初始化
jQuery(grid_selector).jqGrid({
subGrid : false, //此处设置为true时可以打开子项,子项用不到已删除
url:"",//获取数据的地址
//rownumbers: true,
datatype: "json",
mtype:"POST",
hidegrid : false,//收缩列表按钮
prmNames : {
page : "pageNumInput",
rows : "pageSize"
},// 重新定义分页信息
height : 385, //表格高度
colNames : [ '姓名', '性别 ','出生日期','id'],
colModel : [
{
name : 'name',
index : 'name',
width : 150
},
{
name : 'sex',
index : 'sex',
width : 80,
formatter : function(cellValue,options,rowObject){
var item = "";
if(cellValue == '0'){
item = "男";
}else if(cellValue == '1'){
item = "女";
}
return item;
}
},{
name : 'date',
index : 'date',
width : 90
},{ name : 'id',
index : 'id',
hidden: ture,
}
],viewrecords : true,rowNum : 20,//初始页数rowList : [ 20, 50, 100,200 ],//扩展页数pager : pager_selector,altRows : true,multiselect : true,multiboxonly : true,emptyrecords:"无数据",loadComplete : function(data) {var table = this;setTimeout(function()
{styleCheckbox(table);updateActionIcons(table);updatePagerIcons(table);enableTooltips(table);}, 0);if(data.status=="success"){$("#alert_success").show();setTimeout(function(){$("#alert_success").hide();},1000);}},jsonReader: { //jsonReader来跟服务器端返回的数据做对应root:
"dataRows", //包含实际数据的数组page: "currPage", //当前页total: "totalPage",//总页数records:"totalCount", //查询出的记录数id:"id",repeatitems : false },editurl : "",//nothing is savedcaption : "个人信息列表"});var navButtons = jQuery(grid_selector).jqGrid('navGrid',pager_selector,{
//navbar optionsedit : false,editicon : 'ace-icon fa fa-pencil blue',add : false,addicon : 'ace-icon fa fa-plus-circle purple',del : false,delicon : 'ace-icon fa fa-trash-o red',search : false,searchicon
: 'ace-icon fa fa-search orange',refresh : false,refreshicon : 'ace-icon fa fa-refresh green',view : false,viewicon : 'ace-icon fa fa-search-plus grey',},{//edit record form//closeAfterEdit: true,//width: 700,recreateForm : true,beforeShowForm : function(e)
{var form = $(e[0]);form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')style_edit_form(form);}},{//new record form//width: 700,closeAfterAdd : true,recreateForm : true,viewPagerButtons : false,beforeShowForm
: function(e) {var form = $(e[0]);form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')style_edit_form(form);}});$(window).triggerHandler('resize.jqGrid');//trigger window resize to make the grid get the correct
size//switch element when editing inlinefunction aceSwitch(cellvalue, options, cell) {setTimeout(function() {$(cell).find('input[type=checkbox]').addClass('ace ace-switch ace-switch-5').after('<span class="lbl"></span>');}, 0);}//enable datepickerfunction
pickDate(cellvalue, options, cell) {setTimeout(function() {$(cell).find('input[type=text]').datepicker({format : 'yyyy-mm-dd',autoclose : true});}, 0);}function style_edit_form(form) {//enable datepicker on "sdate" field and switches for "stock" fieldform.find('input[name=sdate]').datepicker({format
: 'yyyy-mm-dd',autoclose : true})form.find('input[name=stock]').addClass('ace ace-switch ace-switch-5').after('<span class="lbl"></span>');//don't wrap inside a label element, the checkbox value won't be submitted (POST'ed)//.addClass('ace ace-switch ace-switch-5').wrap('<label
class="inline" />').after('<span class="lbl"></span>');//update buttons classesvar buttons = form.next().find('.EditButton .fm-button');buttons.addClass('btn btn-sm').find('[class*="-icon"]').hide();//ui-icon, s-iconbuttons.eq(0).addClass('btn-primary').prepend('<i
class="ace-icon fa fa-check"></i>');buttons.eq(1).prepend('<i class="ace-icon fa fa-times"></i>')buttons = form.next().find('.navButton a');buttons.find('.ui-icon').hide();buttons.eq(0).append('<i class="ace-icon fa fa-chevron-left"></i>');buttons.eq(1).append('<i
class="ace-icon fa fa-chevron-right"></i>');}function style_delete_form(form) {var buttons = form.next().find('.EditButton .fm-button');buttons.addClass('btn btn-sm btn-white btn-round').find('[class*="-icon"]').hide();//ui-icon, s-iconbuttons.eq(0).addClass('btn-danger').prepend('<i
class="ace-icon fa fa-trash-o"></i>');buttons.eq(1).addClass('btn-default').prepend('<i class="ace-icon fa fa-times"></i>')}function style_search_filters(form) {form.find('.delete-rule').val('X');form.find('.add-rule').addClass('btn btn-xs btn-primary');form.find('.add-group').addClass('btn
btn-xs btn-success');form.find('.delete-group').addClass('btn btn-xs btn-danger');}function style_search_form(form) {var dialog = form.closest('.ui-jqdialog');var buttons = dialog.find('.EditTable')buttons.find('.EditButton a[id*="_reset"]').addClass('btn
btn-sm btn-info').find('.ui-icon').attr('class','ace-icon fa fa-retweet');buttons.find('.EditButton a[id*="_query"]').addClass('btn btn-sm btn-inverse').find('.ui-icon').attr('class','ace-icon fa fa-comment-o');buttons.find('.EditButton a[id*="_search"]').addClass('btn
btn-sm btn-purple').find('.ui-icon').attr('class','ace-icon fa fa-search');}function beforeDeleteCallback(e) {var form = $(e[0]);if (form.data('styled'))return false;form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header"
/>')style_delete_form(form);form.data('styled', true);}function beforeEditCallback(e) {var form = $(e[0]);form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')style_edit_form(form);}//it causes some flicker when
reloading or navigating grid//it may be possible to have some custom formatter to do this as the grid is being created to prevent this//or go back to default browser checkbox styles for the gridfunction styleCheckbox(table) {/**$(table).find('input:checkbox').addClass('ace').wrap('<label
/>').after('<span class="lbl align-top" />')$('.ui-jqgrid-labels th[id*="_cb"]:first-child').find('input.cbox[type=checkbox]').addClass('ace').wrap('<label />').after('<span class="lbl align-top" />'); */}//unlike navButtons icons, action icons in rows seem
to be hard-coded//you can change them like this in here if you wantfunction updateActionIcons(table) {/**var replacement = {'ui-ace-icon fa fa-pencil' : 'ace-icon fa fa-pencil blue','ui-ace-icon fa fa-trash-o' : 'ace-icon fa fa-trash-o red','ui-icon-disk'
: 'ace-icon fa fa-check green','ui-icon-cancel' : 'ace-icon fa fa-times red'};$(table).find('.ui-pg-div span.ui-icon').each(function(){var icon = $(this);var $class = $.trim(icon.attr('class').replace('ui-icon', ''));if($class in replacement) icon.attr('class',
'ui-icon '+replacement[$class]);}) */}//replace icons with FontAwesome icons like abovefunction updatePagerIcons(table) {var replacement = {'ui-icon-seek-first' : 'ace-icon fa fa-angle-double-left bigger-140','ui-icon-seek-prev' : 'ace-icon fa fa-angle-left
bigger-140','ui-icon-seek-next' : 'ace-icon fa fa-angle-right bigger-140','ui-icon-seek-end' : 'ace-icon fa fa-angle-double-right bigger-140'};$('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function() {var icon = $(this);var
$class = $.trim(icon.attr('class').replace('ui-icon', ''));if ($class in replacement)icon.attr('class', 'ui-icon '+ replacement[$class]);})}function enableTooltips(table) {$('.navtable .ui-pg-button').tooltip({container : 'body'});$(table).find('.ui-pg-div').tooltip({container
: 'body'});}$(document).one('ajaxloadstart.page', function(e) {$(grid_selector).jqGrid('GridUnload');$('.ui-jqdialog').remove();});//日历start $('.date-picker').datepicker({autoclose: true,todayHighlight: true})//show datepicker when clicking on the icon.next().on(ace.click_event,
function(){$(this).prev().focus();});//日历end//查询$("#search").click(function(e){//获取查询条件var name = $("#name_sel").val();var sex = $("#sex_sel").val();//刷新jqgrid $(grid_selector).jqGrid("setGridParam",{page : 1,//传递查询参数postData:{'name'name,'sex'sex}}).trigger("reloadGrid");});//查询全部$("#search_all").click(function(e){//重置查询条件$("#name_sel").val('');$("#sex_sel").val('');var
name = $("#name_sel").val();var sex = $("#sex_sel").val();//刷新jqgrid$(grid_selector).jqGrid("setGridParam",{//传递查询参数postData:{'name'name,'sex'sex}}).trigger("reloadGrid");});}); </script> </BODY></HTML>
2、添加个人信息。个人信息属性字段少使用弹出框方式操作,属性字段多可选择跳转页面来实现,以下举例弹出框方式:
首先在页面编辑一个个人信息的隐藏dialog,此dialog可用于添加编辑和查看。
<!-- 新增编辑 -->
<div class="ui-jqdialog-content ui-widget-content hide"
id="dialog-addAndEdit">
<div style="width: 100%;">
<form name="FormPost" id="FrmGrid_grid-table" class="FormGrid"
οnsubmit="return false;"
style="width: auto; overflow: auto; position: relative; height: auto;">
<table id="TblGrid_grid-table" class="EditTable" cellspacing="0"
cellpadding="0" border="0">
<tbody>
<tr id="FormError" style="display: none">
<td class="ui-state-error" colspan="2"></td>
</tr>
<tr style="display: none" class="tinfo">
<td class="topinfo" colspan="2"></td>
</tr>
<tr class="FormData">
<td class="CaptionTD">
*姓名
</td>
<td class="DataTD">
<input type="text" size="24" maxlength="30"
id="name" name="name"
role="textbox">
</td>
</tr>
<tr class="FormData">
<td class="CaptionTD">
*姓别
</td>
<td class="DataTD">
<select id="sex" class="form-control">
<option value=""></option>
<option value="0">男</option>
<option value="1">女</option>
</select>
</td>
</tr>
<tr class="FormData">
<td class="CaptionTD">
*出生日期
</td>
<td class="DataTD">
<input type="text" size="24" maxlength="30"
id="date" name="date"
data-date-format="yyyy-mm-dd"
role="textbox" class="date-picker">
</td>
</tr>
</tbody>
</table>
</form>
</div>
</div>
需要添加和编辑查看时将列表初始化按钮中的添加编辑查看改为true,并写上对应方法名称:
var navButtons = jQuery(grid_selector).jqGrid('navGrid',
pager_selector,
{ //navbar options
edit : true,
editicon : 'ace-icon fa fa-pencil blue',
editfunc : _edit_row
add : true,
addicon : 'ace-icon fa fa-plus-circle purple',
addfunc : _add_row,
del : false,
delicon : 'ace-icon fa fa-trash-o red',
delfunc : _del_row,
search : false,
searchicon : 'ace-icon fa fa-search orange',
refresh : true,
refreshicon : 'ace-icon fa fa-refresh green',
view : true,
viewicon : 'ace-icon fa fa-search-plus grey',
viewfunc : _view_row,
},
在script标签中写上对应的方法:
添加个人信息,添加前先将所有字段清空,并做必填项验证。
//添加
function _add_row(){
$("#name").val("");
$('#sex').val("");
$('#date').val("");
$( "#dialog-addAndEdit" ).removeClass('hide').dialog({
modal: true,
width:'360',
height:'400',
title: "<div class='widget-header widget-header-small'><h4 class='smaller'><i class='ace-icon fa fa-check'></i> 添加个人信息</h4></div>",
title_html: true,
buttons: [
{
text: "确定",
"class" : "btn btn-primary btn-minier",
click: function() {
if($("#name").val()=="" || $("#name").val().indexOf(" ")!=-1){
alert"姓名不能为空!",{time:3000});
return;
}
if($("#sex").val()=="" || $("#sex").val().indexOf(" ")!=-1){
alert"性别不能为空!",{time:3000});
return;
}
if($("#date").val()=="" || $("#date").val().indexOf(" ")!=-1){
alert"性别不能为空!",{time:3000});
return;
}
_save_row_add();
$( this ).dialog( "close" );
}
},
{
text: "取消",
"class" : "btn btn-minier",
click: function() {
$( this ).dialog( "close" );
}
},
]
});
}
//保存添加
function _save_row_add(){
var data={
id : id,
name : $('#name').val(),
sex : $('#sex').val(),
date : $('#date').val()
}
$.ajax({
type : 'POST',
url :'',
dataType : 'json',
data :data,
success : function(data) {
if (data) {
if (data.status != "success") {
alert(data.data,{time:3000});
} else {
//刷新jqgrid
$(grid_selector).jqGrid().trigger("reloadGrid");
}
}
},
error : function(data) {
//alert(JSON.stringify(data));
}
});
}
编辑个人信息,根据选中行id通过getRowData获取选中行信息,赋值对应的个人信息中,并做必填项验证。
//编辑
function _edit_row(id){
//行数据
var rowData = $(grid_selector).jqGrid('getRowData',id);
$("#name").val(rowData.name);
$('#sex').val(rowData.sex);
$('#date').val(rowData.date);
$("#dialog-addAndEdit" ).removeClass('hide').dialog({
modal: true,
width:'360',
height:'400',
title: "<div class='widget-header widget-header-small'><h4 class='smaller'><i class='ace-icon fa fa-check'></i> 编辑个人信息</h4></div>",
title_html: true,
buttons: [
{
text: "确定",
"class" : "btn btn-primary btn-minier",
click: function() {
if($("#name").val()=="" || $("#name").val().indexOf(" ")!=-1){
layer.msg("姓名不能为空!",{time:3000});
return;
}
if($("#sex").val()=="" || $("#sex").val().indexOf(" ")!=-1){
layer.msg("性别不能为空!",{time:3000});
return;
}
if($("#date").val()=="" || $("#date").val().indexOf(" ")!=-1){
layer.msg("性别不能为空!",{time:3000});
return;
}
_save_row_edit(id);
$( this ).dialog( "close" );
}
},
{
text: "取消",
"class" : "btn btn-minier",
click: function() {
$( this ).dialog( "close" );
}
},
]
});
}
//保存编辑
function _save_row_edit(id){
var data={
id : id,
name : $('#name').val(),
sex : $('#sex').val(),
date : $('#date').val()
}
$.ajax({
type : 'POST',
url :'',
dataType : 'json',
data :data,
success : function(data) {
if (data) {
if (data.status != "success") {
layer.msg(data.data,{time:3000});
} else {
//刷新jqgrid
$(grid_selector).jqGrid().trigger("reloadGrid");
}
}
},
error : function(data) {
//alert(JSON.stringify(data));
}
});
}
删除个人信息,根据选中行id删除选中行信息
//删除
function _delete_row(id) {
$("#dialog-delete").removeClass('hide').dialog({
modal : true,
width : '250',
height : '150',
title : "<div class='widget-header'><h4 class='smaller'><i class='ace-icon fa fa-exclamation-triangle red'></i> 删除个人信息?</h4></div>",
title_html : true,
buttons : [{
html : "<i class='ace-icon fa fa-trash-o bigger-110'></i> 确定",
"class" : "btn btn-primary btn-minier",
click : function() {
_delete(id);
$(this).dialog("close");
}
}, {
html : "<i class='ace-icon fa fa-times bigger-110'></i> 取消",
"class" : "btn btn-minier",
click : function() {
$(this).dialog("close");
}
},
]
});
}
//保存删除
function _delete(id){
jQuery.ajax({
type : 'POST',
url : '',
dataType : 'json',
data : {
id :id
},
success : function(data) {
if (data) {
if (data.status != "success") {
layer.msg(data.data,{time:3000});
} else {
//刷新jqgrid
$(grid_selector).jqGrid().trigger("reloadGrid");
}
}
},
error : function(data) {}
});
}
后台Controller
@Controller
public class TestController {
@Resource
private TestService testService;
//日志
private static final Logger LOGGER = LoggerFactory.getLogger(TestController.class);
/**
* 个人信息列表页面
*/
@RequestMapping(method = {RequestMethod.POST, RequestMethod.GET}, value = "/test.do")//页面名称
public String test(HttpServletRequest request, ModelMap model) {
String method = request.getMethod();
LOGGER.debug("以 {} 方式访问个人信息列表页面", method);
model.addAttribute("pageHanName", "个人信息管理");
model.addAttribute("pageHanNameChild", "个人信息列表"); //页面名称
ActivityWebUtils.WrapperModle(request, model);
return "manage/" + model.get("pageName");//页面路径
}
/**
* 个人信息列表
* @param request
* @param response
* @param model
* @return
*/
@RequestMapping(method = RequestMethod.POST, value = "/testList.do")
public @ResponseBody Map<String, Object> testList(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
LOGGER.debug("个人信息列表");
ActivityModelMap modelMap = new ActivityModelMap(request);
String method = request.getMethod();
testService.getTesttList(modelMap, method, request);
return modelMap.getModelMap();
}
/**
* 保存新的个人信息
*/
@RequestMapping(method = RequestMethod.POST, value = "/add.do")
public @ResponseBody Map<String, Object> add(Test test,
HttpServletRequest request, HttpServletResponse response) {
LOGGER.debug("保存个人信息!");
ActivityModelMap modelMap = new ActivityModelMap(request);
try {
//获取当前登录人信息
ExtendUsers eUser = (ExtendUsers)request.getSession().getAttribute("CURRENT_USER_INFO");
if (eUser == null || test == null) {
modelMap.put("status", "exception");
} else {
if (testService.add(test, eUser, modelMap)) {
modelMap.put("status", "success");
modelMap.put("data", "保存个人信息成功!");
}
}
} catch(Exception e) {
LOGGER.error("保存个人信息的操作出现异常:{}", e);
modelMap.put("status", "exception");
}
return modelMap.getModelMap();
}
/**
* 编辑个人信息
*/
@RequestMapping(method = RequestMethod.POST, value = "/edit.do")
public @ResponseBody Map<String, Object> edit(Test test,
HttpServletRequest request, HttpServletResponse response) {
LOGGER.debug("编辑个人信息!");
ActivityModelMap modelMap = new ActivityModelMap(request);
try {
ExtendUsers eUser = (ExtendUsers)request.getSession().getAttribute("CURRENT_USER_INFO");
if (eUser == null || test == null) {
modelMap.put("status", "exception");
} else {
if (testService.edit(test, eUser ,modelMap)) {
modelMap.put("status", "success");
modelMap.put("data", "编辑个人信息成功!");
}
}
} catch(Exception e) {
LOGGER.error("编辑个人信息的操作出现异常:{}", e);
modelMap.put("status", "exception");
}
return modelMap.getModelMap();
}
/**
* 删除个人信息
*/
@RequestMapping(method = RequestMethod.POST, value = "/remove.do")
public @ResponseBody Map<String, Object> remove(
@RequestParam(value = "id", required = true)Long id,
HttpServletRequest request, HttpServletResponse response) {
LOGGER.debug("删除个人信息!");
ActivityModelMap modelMap = new ActivityModelMap(request);
try {
if ( id == null) {
modelMap.put("status", "exception");
} else {
if (testService.remove(id, modelMap)) {
modelMap.put("status", "success");
modelMap.put("data", "删除个人信息成功!");
}
}
} catch(Exception e) {
LOGGER.error("删除个人信息的操作出现异常:{}", e);
modelMap.put("status", "error");
modelMap.put("data", "删除个人信息的操作出现异常!");
}
return modelMap.getModelMap();
}
}
java实体类和查询类
public class Test implements Serializable,Cloneable{
private static final long serialVersionUID = 1L;
private Long id;//id
private String name; //姓名
private Integer sex; //性别
private String date; //出生日期
private Integer isDelete;//是否已删除
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public Integer getIsDelete(){
return isDelete;
}
public void setIsDelete(Integer isDelete){
this.isDelete = isDelete;
}
}
public class TestQuery extends BasePaginationQuery{
private Long id;//id
private String name; //姓名
private Integer sex; //性别
private String date; //出生日期
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
Service接口和实现层
public interface TestService {
/**
* 个人信息列表
* */
public void getTesttList(ActivityModelMap modelMap, String method, HttpServletRequest request);
/**
* 根据查询条件获取个人信息
* */
public List<Test> getTesttListByQuery(TestQuery testQuery);
/**
* 添加个人信息
* */
public boolean add(Test test, ExtendUsers eUser, ActivityModelMap modelMap);
/**
* 编辑个人信息
*/
public boolean edit(Test test, ExtendUsers eUser, ActivityModelMap modelMap);
/**
* 删除个人信息
* */
public boolean remove(Long id, ActivityModelMap modelMap);
}
@Service("TestService")
public class TestServiceImpl implements TestService{
@Resource
private TestDao testDao;
private static final Logger LOGGER = LoggerFactory.getLogger(TestServiceImpl.class);
@Override
public void getTesttList(ActivityModelMap modelMap, String method, HttpServletRequest request,String export) {
LOGGER.debug("Service层:个人信息列表");
TestQuery testQuery = new TestQuery();
//以id升序排序
testQuery.setSortBy("id");
testQuery.setSortType("2");
//当前页
String pageNum = request.getParameter("pageNumInput");
if (! StringUtils.isBlank(pageNum)) {
testQuery.setPage(Integer.parseInt(pageNum));
}
//每页条数
String pageSize = request.getParameter("pageSize");
if (! StringUtils.isBlank(pageSize)) {
testQuery.setPageSize(Integer.parseInt(pageSize));
}
//姓名
String name = request.getParameter("name");
if (! StringUtils.isBlank(name)) {
testQuery.setName(name);
}
//性别
String sex = request.getParameter("sex");
if (! StringUtils.isBlank(sex)) {
testQuery.setSex(sex);
}
Integer totalCount = testDao.getTestListCountByQuery(testQuery);
TotalInfo totalInfo = new TotalInfo(totalCount, testQuery.getPageSize(),
testQuery.getPage(), testQuery.getStartNum());
List<Test> test = this.getTestListByQuery(testQuery);
modelMap.put("dataRows", test);
modelMap.put("currPage",totalInfo.getCurrentPage());
modelMap.put("totalPage",totalInfo.getPageTotal());
modelMap.put("totalCount",totalInfo.getTotalCount());
}
@Override
public List<Test> getTesttListByQuery(TestQuery testQuery) {
LOGGER.debug("Service层:根据检索条件获取个人信息");
return testDao.getTestListByQuery(testQuery);
}
/**
* 添加个人信息
*/
@Override
public boolean add(Test test, ExtendUsers eUser,
ActivityModelMap modelMap) {
LOGGER.debug("Service层:添加个人信息");
boolean result = false;
Integer resultNum = testDao.add(eUser);
if (resultNum.compareTo(new Integer(1)) == 0) {
result = true;
} else {
modelMap.put("status", "failure");
modelMap.put("data", "添加个人信息失败");
}
return result;
}
/**
* 编辑个人信息
*/
@Override
public boolean edit(Test test, ExtendUsers eUser,
ActivityModelMap modelMap) {
LOGGER.debug("Service层:编辑个人信息");
boolean result = false;
Integer resultNum = testDao.edis(test);
if (resultNum.compareTo(new Integer(1)) == 0) {
result = true;
} else {
modelMap.put("status", "failure");
modelMap.put("data", "编辑个人信息失败");
}
return result;
}
/**
* 删除个人信息
*/
@Override
public boolean remove(Long id, ActivityModelMap modelMap) {
LOGGER.debug("Service层:删除个人信息");
boolean result = false;
Integer resultNum = testDao.remove(id);
if (resultNum.compareTo(new Integer(1)) == 0) {
result = true;
} else {
modelMap.put("status", "failure");
modelMap.put("data", "删除个人信息失败");
}
return result;
}
}
Dao接口和实现层
public interface TestDao {
/**
* 获取个人信息的数量
* @return Integer
*/
public Integer getTestListCountByQuery(TestQuery testQuery);
/**
* 获取个人信息
* @return List<Test>
*/
public List<Test> getTestListByQuery(TestQuery testQuery);
/**
* 添加个人信息
* @return Integer
*/
public Integer add(Test test);
/**
* 编辑个人信息
* @return Integer
*/
public Integer edit(Test test);
/**
* 删除个人信息
*/
public Integer remove (Long id);
}
@Repository(value = "testDao")
public class TestDaoImpl extends BaseDao implements TestDao {
private static final Logger LOGGER = LoggerFactory.getLogger(TestDaoImpl.class);
@Override
public Integer getTestListCountByQuery(TestQuery testQuery) {
LOGGER.debug("Dao层:获取个人信息的数量");
return (Integer)getSqlSession().selectOne("testDao.getTestListCountByQuery", testQuery);
}
@Override
public List<Test> getTestListByQuery(TestQuery testQuery) {
LOGGER.debug("Dao层:获取个人信息");
return getSqlSession().selectList("testDao.getTestListByQuery", testQuery);
}
@Override
public Integer add(Test test) {
LOGGER.debug("Dao层:添加个人信息");
return (Integer)insert("testDao.add",test);
}
@Override
public Integer edit(Test test) {
LOGGER.debug("Dao层:编辑个人信息");
return update("testDao.edit", test);
}
@Override
public Integer remove(Long id) {
LOGGER.debug("Dao层:删除个人信息:{}", id);
return update("testDao.remove",id);
}
}
mybatis
<?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="testDao">
<resultMap id="testResult" type="tese">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="sex" column="sex"/>
<result property="data" column="data"/>
<result property="isDelete" column="is_dalete"/>
</resultMap>
<sql id="allColumn">
id, name,sex,data
</sql>
<!-- 添加个人信息 -->
<insert id="add" parameterType="tese" useGeneratedKeys="false" keyProperty="id">
insert into test (
<trim suffix="" suffixOverrides=",">
id,
<if test="name != null">
name,
</if>
<if test="sex != null">
sex,
</if>
<if test="data != null">
data
</if>
</trim>
) values(
<trim suffix="" suffixOverrides=",">
test_seq.nextval,
<if test="name != null">
#{name},
</if>
<if test="sex != null">
#{sex},
</if>
<if test="data != null">
#{data}
</if>
</trim>
)
</insert>
<!-- 编辑个人信息 -->
<update id="edit" parameterType="test">
update test set
<trim suffix="" suffixOverrides=",">
<if test="name != null">
name = #{name},
</if>
<if test="sex != null">
sex = #{sex},
</if>
<if test="data != null">
data = #{data}
</if>
</trim>
where ID = #{id}
</update>
<!-- 删除个人信息 -->
<update id="remove" parameterType="Long">
update test set is_delete = 1
where id = #{id}
</update>
<!-- 获取个人信息的数量 -->
<select id="getTestListCountByQuery" resultType="Integer" parameterType="testQuery">
SELECT COUNT(*)
FROM test
<trim prefix="WHERE" prefixOverrides="AND | OR">
is_delete = 0
<if test="name != null">
AND name like '%'||'${name}'||'%'
</if>
<if test="sex != null">
AND sex = #{sex}
</if>
</trim>
</select>
<!-- 获取个人信息 -->
<select id="getTestListByQuery" resultType="test"
resultMap="testResult" parameterType="testQuery">
<if
test="startNum != null and startNum >= 0 and pageSize != null and pageSize > 0">
select * from(select a.*,ROWNUM rn from(
</if>
SELECT
<include refid="allColumn"/>
FROM test
<trim prefix="WHERE" prefixOverrides="AND | OR">
is_delete = 0
<if test="name != null">
AND name like '%'||'${name}'||'%'
</if>
<if test="sex != null">
AND sex = #{sex}
</if>
</trim>
<choose>
<when test="sortBy != null and sortBy != ''">
<if test="sortType == 1">
ORDER BY ${sortBy} DESC
</if>
<if test="sortType != 1">
ORDER BY ${sortBy} DESC
</if>
</when>
<otherwise>
ORDER BY id DESC
</otherwise>
</choose>
<if test="startNum != null and startNum >= 0 and pageSize != null and pageSize > 0">
<![CDATA[
) a where ROWNUM<=(${startNum}+${pageSize})) where rn>${startNum}
]]>
</if>
</select>
</mapper>