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',width:10">名稱</th> <th data-options="field:'age',width: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="width: 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="width: 90px">保存</a> <a data-url="cancelUser" href="javascript:void(0)" class="easyui-linkbutton c7" iconCls="icon-cancel" style="width: 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
如果覺得我的文章對您有幫助,請予以打賞。您的支持將鼓勵我繼續創作!謝謝!

