jQueryEasyUI
jQuery EasyUI是一组基于jQuery的UI插件集合体,而jQuery EasyUI的目标就是帮助web开发者更轻松的打造出功能丰富并且美观的UI界面。开发者不需要编写复杂的javascript,也不需要对css样式有深入的了解,开发者需要了解的只有一些简单的html标签。
案例使用EasyUI插件
- datagrid:向用户展示列表数据。
- dialog:创建或编辑一条单一的用户信息。
- form:用于提交表单数据。
- messager:显示一些操作信息。
对user表进行CRUD,分页,简单查询
- 列表
- 新增
- 修改
项目图片
InitApplicationListener
在启动服务器的时候,插入默认数据
package com.jege.spring.boot.controller;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import com.jege.spring.boot.data.jpa.entity.User;
import com.jege.spring.boot.data.jpa.repository.UserRepository;
/**
* @author JE哥
* @email 1272434821@qq.com
* @description:spring的事件监听器的处理机制:在启动服务器的时候,插入默认数据
*/
@Component
public class InitApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
ApplicationContext context = event.getApplicationContext();
UserRepository userRepository = context.getBean("userRepository", UserRepository.class);
for (int i = 1; i < 21; i++) {
User user = new User("user" + i, 25 + i);
userRepository.save(user);
}
}
}
CommonExceptionAdvice
package com.jege.spring.boot.exception;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import com.jege.spring.boot.json.AjaxResult;
/**
* @author JE哥
* @email 1272434821@qq.com
* @description:全局异常处理
*/
@ControllerAdvice
@ResponseBody
public class CommonExceptionAdvice {
private static Logger logger = LoggerFactory.getLogger(CommonExceptionAdvice.class);
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MissingServletRequestParameterException.class)
public AjaxResult handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
logger.error("缺少请求参数", e);
return new AjaxResult().failure("required_parameter_is_not_present");
}
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(HttpMessageNotReadableException.class)
public AjaxResult handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
logger.error("参数解析失败", e);
return new AjaxResult().failure("could_not_read_json");
}
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public AjaxResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
logger.error("参数验证失败", e);
BindingResult result = e.getBindingResult();
FieldError error = result.getFieldError();
String field = error.getField();
String code = error.getDefaultMessage();
String message = String.format("%s:%s", field, code);
return new AjaxResult().failure(message);
}
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(BindException.class)
public AjaxResult handleBindException(BindException e) {
logger.error("参数绑定失败", e);
BindingResult result = e.getBindingResult();
FieldError error = result.getFieldError();
String field = error.getField();
String code = error.getDefaultMessage();
String message = String.format("%s:%s", field, code);
return new AjaxResult().failure(message);
}
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(ConstraintViolationException.class)
public AjaxResult handleServiceException(ConstraintViolationException e) {
logger.error("参数验证失败", e);
Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
ConstraintViolation<?> violation = violations.iterator().next();
String message = violation.getMessage();
return new AjaxResult().failure("parameter:" + message);
}
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(ValidationException.class)
public AjaxResult handleValidationException(ValidationException e) {
logger.error("参数验证失败", e);
return new AjaxResult().failure("validation_exception");
}
/**
* 405 - Method Not Allowed
*/
@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public AjaxResult handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
logger.error("不支持当前请求方法", e);
return new AjaxResult().failure("request_method_not_supported");
}
/**
* 415 - Unsupported Media Type
*/
@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
public AjaxResult handleHttpMediaTypeNotSupportedException(Exception e) {
logger.error("不支持当前媒体类型", e);
return new AjaxResult().failure("content_type_not_supported");
}
/**
* 500 - Internal Server Error
*/
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler(ServiceException.class)
public AjaxResult handleServiceException(ServiceException e) {
logger.error("业务逻辑异常", e);
return new AjaxResult().failure("业务逻辑异常:" + e.getMessage());
}
/**
* 500 - Internal Server Error
*/
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler(Exception.class)
public AjaxResult handleException(Exception e) {
logger.error("通用异常", e);
return new AjaxResult().failure("通用异常:" + e.getMessage());
}
/**
* 操作数据库出现异常:名称重复,外键关联
*/
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler(DataIntegrityViolationException.class)
public AjaxResult handleException(DataIntegrityViolationException e) {
logger.error("操作数据库出现异常:", e);
return new AjaxResult().failure("操作数据库出现异常:字段重复、有外键关联等");
}
}
user.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户管理</title>
<%@include file="/WEB-INF/page/common.jsp"%>
<script type="text/javascript">
// 页面加载完毕之后才能写jQuery的代码
$(function() {
// 声明并缓存easyui组件
var userDatagrid = $("#userDatagrid");
var userDialog = $("#userDialog");
var userForm = $("#userForm");
var userSearchForm = $("#userSearchForm");
// 表单的添加方法
userForm.form({
url : "/user/save",
onSubmit : function() {
// 在表单提交前,做一下验证
return userForm.form("validate");
},
//data是后台save方法返回的json字符串
success : function(data) {
// 需要自己把字符串转变成json对象,easyiui没有提供转换
data = $.parseJSON(data);
// 判断保存是否成功
if (data.meta.success) {
// 成功就关掉对话框
userDialog.dialog("close");
//重新加载最新的数据
userDatagrid.datagrid("reload");
} else {
$.messager.alert('错误提示', data.meta.message, 'error');
}
}
});
// 创建操作data-url的json对象,把页面所有linkbutton组件的操作都统一添加到此对象上面
var urlObjectUser = {
addUser : function() {
// 清空对话框里面的表单内容,防止原来的数据有缓存
userForm.form("clear");
// 打开对话框,修改标题,然后居中
userDialog.dialog("open").dialog("setTitle", "添加用户");
},
updateUser : function() {
// 获取选中行数据
var selectedRow = userDatagrid.datagrid("getSelected");
// 判断是否选中行
if (!selectedRow) {
$.messager.alert("操作提示", "请先选中一行数据,在修改!!", "info");
return;
}
// 清空对话框里面的表单内容
userForm.form("clear");
//修改的时候才查询上级null数据
$('#parentCombotree').combotree({
url : '${ctx}/user/getTreeByParent'
});
// 使用easyui的form组件load方法,只要是相同的名称,会自动回显数据
userForm.form("load", selectedRow);
// 打开对话框
userDialog.dialog("open").dialog("setTitle", "编辑用户");
},
removeUser : function() {
// 获取选中行数据
var row = userDatagrid.datagrid("getSelected");
// 判断是否选中行
if (!row) {
$.messager.alert("操作提示", "请选中一行数据,在删除!!", "info");
return;
}
$.get("/user/delete?id=" + row.id, function(data) {
if (data.meta.success) {//删除成功
userDatagrid.datagrid("reload");
} else {
$.messager.alert('错误提示', data.meta.message, 'error');
}
}, 'json');
},
reloadUser : function() {//调用重新加载数据的方法
userDatagrid.datagrid("reload");
},
saveUser : function() {//提交表单
userForm.submit();
},
cancelUser : function() {//关闭对话框
userDialog.dialog("close");
},
searchUser : function() {//简单搜索
userDatagrid.datagrid("load", {
q : $("input[name=q]").val()
});
}
};
// 对页面所有linkbutton组件,统一监听
$("a[data-url]").on("click", function() {
// 获取linkbutton的data-url信息
var url = $(this).data("url");
//如果此目标方法是存在的并且linkbutton组件没有被禁用,才可以点击
if (urlObjectUser[url] && !$(this).linkbutton('options').disabled) {
//调用动态的方法
urlObjectUser[url]();
}
});
});
</script>
</head>
<body>
<!-- 数据表格组件 -->
<table id="userDatagrid" class="easyui-datagrid" url="/user/json" title="用户管理" fit="true" border="false"
fitColumns="true" singleSelect="true" pagination="true" rownumbers="true" toolbar="#userDatagridToolbar">
<thead>
<tr>
<th data-options="field:'id'">编号</th>
<th data-options="field:'name',10">名称</th>
<th data-options="field:'age',10">年龄</th>
</tr>
</thead>
</table>
<!-- 数据表格组件工具栏 -->
<div class="easyui-layout" fit="true">
<div id="userDatagridToolbar" region="north" border="false"
style="border-bottom: 1px solid #ddd; height: 32px; padding: 2px 5px; background: #fafafa;">
<div style="float: left;">
<a data-url="addUser" href="javascript:void(0)" class="easyui-linkbutton c1" iconCls="icon-add">添加</a> <a
data-url="updateUser" href="javascript:void(0)" class="easyui-linkbutton c2" iconCls="icon-edit">编辑</a> <a
data-url="removeUser" href="javascript:void(0)" class="easyui-linkbutton c3" iconCls="icon-remove">删除</a>
<a data-url="reloadUser" href="javascript:void(0)" class="easyui-linkbutton c4" iconCls="icon-reload">刷新</a>
<a href="javascript:void(0)" class="easyui-linkbutton c8" iconCls="icon-search" data-url="searchUser"
disabled="true">不能点击的按钮,点击了也没有事件处理</a>
</div>
<div style="float: right">
<form method="post">
关键字:<input name="q" size="10" /> <a data-url="searchUser" href="javascript:void(0)"
class="easyui-linkbutton c5" iconCls="icon-search">搜索</a>
</form>
</div>
</div>
</div>
<!-- 添加/编辑用户对话框 -->
<div id="userDialog" class="easyui-dialog" style=" 360px; height: 260px; padding: 10px 20px"
title="管理用户对话框" data-options="closed:true,modal:true,buttons:'#userDialogButtons',resizable:true">
<form id="userForm" method="post">
<input type="hidden" name="id" />
<div class="ftitle">用户信息</div>
<table align="center">
<tr>
<td>名称:</td>
<td><input class='easyui-validatebox' required="true" type='text' name='name'></input></td>
</tr>
<tr>
<td>年龄:</td>
<td><input class='easyui-numberbox' required="true" min="20" max="80" precision="0" type='text'
name='age'></input></td>
</tr>
</table>
</form>
</div>
<!-- 对话框按钮组件 -->
<div id="userDialogButtons">
<a data-url="saveUser" href="javascript:void(0)" class="easyui-linkbutton c6" iconCls="icon-ok"
style=" 90px">保存</a> <a data-url="cancelUser" href="javascript:void(0)" class="easyui-linkbutton c7"
iconCls="icon-cancel" style=" 90px">取消</a>
</div>
</body>
</html>
其他关联代码
- Spring Boot 系列教程7-EasyUI-datagrid
http://blog.csdn.net/je_ge/article/details/5332652599999999 - Spring Boot 系列教程5-热部署-devtools模块
http://blog.csdn.net/je_ge/article/details/53326525 - Spring Boot 系列教程2-Data JPA
http://blog.csdn.net/je_ge/article/details/53294949
删除异常运行流程
- 修改UserController.delete,添加int a = 1 / 0;出现通用异常:/ by zero
源码地址
https://github.com/je-ge/spring-boot
如果觉得我的文章对您有帮助,请予以打赏。您的支持将鼓励我继续创作!谢谢!