Spring Boot 系列教程7-EasyUI-datagrid
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
如果觉得我的文章对您有帮助,请予以打赏。您的支持将鼓励我继续创作!谢谢! 
 
Spring Boot 系列教程7-EasyUI-datagrid的更多相关文章
- Spring Boot 系列教程15-页面国际化
		internationalization(i18n) 国际化(internationalization)是设计和制造容易适应不同区域要求的产品的一种方式. 它要求从产品中抽离所有地域语言,国家/地区和 ... 
- Spring Boot 系列教程8-EasyUI-edatagrid扩展
		edatagrid扩展组件 edatagrid组件是datagrid的扩展组件,增加了统一处理CRUD的功能,可以用在数据比较简单的页面. 使用的时候需要额外引入jquery.edatagrid.js ... 
- Spring Boot 系列教程19-后台验证-Hibernate Validation
		后台验证 开发项目过程中,后台在很多地方需要进行校验操作,比如:前台表单提交,调用系统接口,数据传输等.而现在多数项目都采用MVC分层式设计,每层都需要进行相应地校验. 针对这个问题, JCP 出台一 ... 
- Spring Boot 系列教程18-itext导出pdf下载
		Java操作pdf框架 iText是一个能够快速产生PDF文件的java类库.iText的java类对于那些要产生包含文本,表格,图形的只读文档是很有用的.它的类库尤其与java Servlet有很好 ... 
- Spring Boot 系列教程17-Cache-缓存
		缓存 缓存就是数据交换的缓冲区(称作Cache),当某一硬件要读取数据时,会首先从缓存中查找需要的数据,如果找到了则直接执行,找不到的话则从内存中找.由于缓存的运行速度比内存快得多,故缓存的作用就是帮 ... 
- Spring Boot 系列教程16-数据国际化
		internationalization(i18n) 国际化(internationalization)是设计和制造容易适应不同区域要求的产品的一种方式. 它要求从产品中抽离所有地域语言,国家/地区和 ... 
- Spring Boot 系列教程14-动态修改定时任务cron参数
		动态修改定时任务cron参数 不需要重启应用就可以动态的改变Cron表达式的值 不能使用@Scheduled(cron = "${jobs.cron}")实现 DynamicSch ... 
- Spring Boot 系列教程12-EasyPoi导出Excel下载
		Java操作excel框架 Java Excel俗称jxl,可以读取Excel文件的内容.创建新的Excel文件.更新已经存在的Excel文件,现在基本没有更新了 http://jxl.sourcef ... 
- Spring Boot 系列教程11-html页面解析-jsoup
		需求 需要对一个页面进行数据抓取,并导出doc文档 html解析器 jsoup 可直接解析某个URL地址.HTML文本内容.它提供了一套非常省力的API,可通过DOM,CSS以及类似于JQuery的操 ... 
随机推荐
- Java Lambda表达式入门[转]
			原文链接: Start Using Java Lambda Expressions http://blog.csdn.net/renfufei/article/details/24600507 下载示 ... 
- 【Python@Thread】锁示例
			当出现竞态条件时候,即在同一个时刻只有一个线程可以进入临界区,需要使用同步. 常见的同步原语有两种:锁/互斥,信号量. 锁是最简单,最低级的机制. 首先看一个不使用锁时候的多线程示例: from at ... 
- javascript基础(二)类型转换
			原文http://pij.robinqu.me/ 类型转换 当期望使用一个布尔值的时候,可以提供任意类型值,JavaScript将根据需要自行转换类型.类型转换可以分为隐式转换和显式转换. 显式转换 ... 
- 自己造容器List
			//自己造容器--List /* 1.iterator 2.头迭代器 3.尾迭代器 4.链表长 5.判空 6.清除 7.取头元素 8.取尾元素 9.头插入 10.尾插入 11.头删除 12.尾删除 1 ... 
- Redis持久存储-AOF&RDB
			Redis中数据存储模式有2种:cache-only,persistence;cache-only即只做为"缓存"服务,不持久数据,数据在服务终止后将消失,此模式下也将不存在&qu ... 
- PHP中使用CURL(四)
			为了安全,我们的web服务主机往往不能上网.维护的时候,也是通过跳板机,ssh登录后去操作.有时候我们的程序需要访问外网.比如需要调用外网其他程序的某个接口.这时可以通过PHP的CURL函数的CURL ... 
- UI弹出键盘和收回键盘
			点击textfield,会自动弹出键盘 要让键盘收回来,先设置个代理:[field setTextFieldDelegate:self]; 可设置成自己,也可设置成其他对象,只要在对应的类中,遵循U ... 
- JS 经典代码段总结  start from 2016-08-22
			1.for(var i = 0, max = myArray.length; i < max ; i++){ //用myArrayy[i]来做点什么 } 用max存储myArray的长度,防止每 ... 
- Jenkins - 持续集成环境搭建【转】
			1. Jenkins 概述 Jenkins是一个开源的持续集成工具.持续集成主要功能是进行自动化的构建.自动化构建包括自动编译.发布和测试,从而尽快地发现集成错误,让团队能够更快的开发内聚的软件. 2 ... 
- HTTP基础知识
			HTTP是计算机通过网络进行通信的规则,是一种无状态的协议,不建立持久的连接(客户端向服务器发送请求,web服务器返回响应,接着连接就被关闭了): 一个完整的HTTP请求连接,通常有下面7个步骤: 1 ... 
