Spring Boot 菜鸟教程

Spring Boot 菜鸟教程 8 EasyUI edatag

2017-01-20  本文已影响214人  JeGe

edatagrid扩展组件

可以直接在数据表格里面进行CRUD

项目图片##

这里写图片描述这里写图片描述

AjaxResult.java,改变输出属性适应edatagrid.onError方法##

package com.jege.spring.boot.json;

/**
 * @author JE哥
 * @email 1272434821@qq.com
 * @description:返回的json对象
 */
public class AjaxResult {
  private static final String OK = "ok";
  private static final String ERROR = "error";

  private boolean isError = false;
  private String msg = OK;

  public AjaxResult success() {
    return this;
  }

  public AjaxResult failure() {
    isError = true;
    msg = ERROR;
    return this;
  }

  public AjaxResult failure(String message) {
    isError = true;
    msg = message;
    return this;
  }

  public boolean getIsError() {
    return isError;
  }

  public void setIsError(boolean isError) {
    this.isError = isError;
  }

  public String getMsg() {
    return msg;
  }

  public void setMsg(String msg) {
    this.msg = msg;
  }

}

CommonExceptionAdvice.jave,修改了返回的http状态##

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"%>
<!-- 额外添加的jquery.edatagrid.js -->
<script type="text/javascript" src="${ctx}/static/easyui/jquery.edatagrid.js"></script>
<script type="text/javascript">
    // 页面加载完毕之后才能写jQuery的代码
    $(function() {
        $('#userDatagrid').edatagrid({
            url : '/user/json',
            saveUrl : '/user/save',
            updateUrl : '/user/save',
            destroyUrl : '/user/delete',
            onError : function(index, data) {
                $.messager.alert('错误提示', data.msg, 'error');
            }
        });
    });
</script>
</head>
<body>
    <!-- 数据表格组件 -->
    <table id="userDatagrid" title="用户管理" fit="true" border="false" fitColumns="true" singleSelect="true"
        pagination="true" rownumbers="true" toolbar="#userDatagridToolbar"
        data-options="onSave:function(){
          $('#userDatagrid').edatagrid('reload');
        },
        destroyMsg:{
            norecord:{// 在没有记录选择的时候执行
                title:'警告',
                msg:'没有选择要删除的行!!!'
        },
            confirm:{// 在选择一行的时候执行      
              title:'确定',
                msg:'你真的要删除吗?'
            }
        }">
        <thead>
            <tr>
                <th data-options="field:'id',hidden:true">编号</th>
                <th field="name" width="50" sortable="true" editor="{type:'validatebox',options:{required:true}}">名称</th>
                <th field="age" width="50" sortable="true"
                    editor="{type:'numberbox',options:{required:true,min:20,max:80,precision:0}}">年龄</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 href="javascript:;" onclick="javascript:$('#userDatagrid').edatagrid('addRow')"
                    class="easyui-linkbutton c1" iconCls="icon-add">添加</a> <a href="javascript:;"
                    onclick="javascript:$('#userDatagrid').edatagrid('saveRow')" class="easyui-linkbutton c2"
                    iconCls="icon-save">保存</a> <a href="javascript:;"
                    onclick="javascript:$('#userDatagrid').edatagrid('destroyRow')" class="easyui-linkbutton c3"
                    iconCls="icon-remove">删除</a> <a href="javascript:;"
                    onclick="javascript:$('#userDatagrid').edatagrid('cancelRow')" class="easyui-linkbutton c4"
                    iconCls="icon-cancel">取消</a><a href="javascript:;"
                    onclick="javascript:$('#userDatagrid').edatagrid('reload')" class="easyui-linkbutton c5"
                    iconCls="icon-reload">刷新</a>
            </div>
            <div style="float: right">
                <form method="post">
                    关键字:<input name="q" size="10" /> <a href="javascript:;"
                        onclick="javascript:$('#userDatagrid').edatagrid('load', {q : $('input[name=q]').val()});"
                        class="easyui-linkbutton c5" iconCls="icon-search">搜索</a>
                </form>
            </div>
        </div>
    </div>
</body>
</html>

其他关联代码

删除异常运行流程

源码地址

https://github.com/je-ge/spring-boot

如果觉得我的文章或者代码对您有帮助,可以请我喝杯咖啡。
**您的支持将鼓励我继续创作!谢谢! **

微信打赏微信打赏
支付宝打赏支付宝打赏
上一篇下一篇

猜你喜欢

热点阅读