文档章节

Hibernate-Validate结合SpringMVC数据验证

ShortHand
 ShortHand
发布于 2017/01/20 15:50
字数 732
阅读 153
收藏 0

1.实体类:

package com.thrall.business.vo;

import com.thrall.business.vaild.VaildQuoteGroupVOAdd;
import com.thrall.business.vaild.VaildQuoteGroupVOEdit;
import org.hibernate.validator.constraints.Length;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.io.Serializable;
import java.util.Date;

public class QuoteGroupVO implements Serializable {

    private static final long serialVersionUID = 1L;

    @NotNull(groups = {VaildQuoteGroupVOEdit.class})
    private Long id;

    @Length(min = 3, max = 20, message = "报价组名长度必须在[3-20]之间!", groups = {VaildQuoteGroupVOAdd.class, VaildQuoteGroupVOEdit.class})
    @Pattern(regexp = "^[\\u4e00-\\u9fa5a-zA-Z0-9]+$", message = "报价组名不能包含特殊字符!", groups = {VaildQuoteGroupVOAdd.class,VaildQuoteGroupVOEdit.class})
    private String name;

    private Long siteId;

    @NotNull(message = "报价组启用时间不能为空!")
    private Date beginDate;

    @NotNull(message = "报价组结束时间不能为空!")
    private Date endDate;

    private Integer shipType;

    private Date gmtCreate;

    private String creator;

    private Date gmtModified;

    private String editor;

    private Integer type;

    private Integer status;

    private String customers;

    private Long customerId;

    private String customerName;

    private String customerIds;
    private String beginTime;
    private String endTime;

    public String getBeginTime() {
        return beginTime;
    }

    public void setBeginTime(String beginTime) {
        this.beginTime = beginTime;
    }

    public String getEndTime() {
        return endTime;
    }

    public void setEndTime(String endTime) {
        this.endTime = endTime;
    }

    public Long getCustomerId() {
        return customerId;
    }

    public void setCustomerId(Long customerId) {
        this.customerId = customerId;
    }

    public String getCustomers() {
        return customers;
    }

    public void setCustomers(String customers) {
        this.customers = customers;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }


    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 == null ? null : name.trim();
    }

    public Long getSiteId() {
        return siteId;
    }


    public void setSiteId(Long siteId) {
        this.siteId = siteId;
    }


    public Date getBeginDate() {
        return beginDate;
    }


    public void setBeginDate(Date beginDate) {
        this.beginDate = beginDate;
    }


    public Date getEndDate() {
        return endDate;
    }


    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }


    public Integer getShipType() {
        return shipType;
    }


    public void setShipType(Integer shipType) {
        this.shipType = shipType;
    }

    public Date getGmtCreate() {
        return gmtCreate;
    }

    public void setGmtCreate(Date gmtCreate) {
        this.gmtCreate = gmtCreate;
    }

    public String getCreator() {
        return creator;
    }

    public void setCreator(String creator) {
        this.creator = creator;
    }

    public Date getGmtModified() {
        return gmtModified;
    }

    public void setGmtModified(Date gmtModified) {
        this.gmtModified = gmtModified;
    }


    public String getEditor() {
        return editor;
    }


    public void setEditor(String editor) {
        this.editor = editor == null ? null : editor.trim();
    }


    public Integer getType() {
        return type;
    }


    public void setType(Integer type) {
        this.type = type;
    }


    public String getCustomerName() {
        return customerName;
    }

    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }


    public String getCustomerIds() {
        return customerIds;
    }

    public void setCustomerIds(String customerIds) {
        this.customerIds = customerIds;
    }

}

2. Controller类:

package com.thrall.web.controller;

import com.commons.Page;
import com.thrall.business.service.CustomerQuoteConfigService;
import com.thrall.business.service.QuoteGroupService;
import com.thrall.business.vaild.ThrallValid;
import com.thrall.business.vaild.VaildQuoteGroupVOAdd;
import com.thrall.business.vaild.VaildQuoteGroupVOEdit;
import com.thrall.business.vo.LoginUserVO;
import com.thrall.business.vo.QuoteGroupVO;
import com.thrall.common.utils.Constants;
import com.thrall.common.utils.date.DateUtils;
import com.thrall.common.utils.page.PageParam;
import com.thrall.dal.domain.CustomerQuoteConfig;
import com.thrall.dal.domain.QuoteGroup;
import com.thrall.web.base.BaseSpringController;
import com.thrall.web.base.JsonResult;
import com.thrall.web.base.LoginHelper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

/**
 * Created by dongrj on 2017/1/9 12:46:02.
 * Email: dongrongjun163.com
 */

@RestController
@RequestMapping("/quotegroup")
@ThrallValid
public class QuoteGroupController extends BaseSpringController {

    @Autowired
    QuoteGroupService quoteGroupService;

    @Autowired
    CustomerQuoteConfigService customerQuoteConfigService;
    

    /**
     * 获取报价组
     */
    @RequestMapping(value = "/page", method = RequestMethod.POST)
    public JsonResult<Page<QuoteGroupVO>> selectByPaging(@RequestBody PageParam<QuoteGroupVO> pageParam) {
        LoginUserVO loginUserVO = new LoginUserVO(LoginHelper.getLoginSiteId(), LoginHelper.getLoginName());
        Page<QuoteGroupVO> page = quoteGroupService.selectPaging(pageParam, loginUserVO);
        return success(page);
    }

    /**
     * 添加报价组
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public JsonResult<Integer> addQuoteGroup(@RequestBody @Validated({VaildQuoteGroupVOAdd.class}) QuoteGroupVO quoteGroupVO) throws ExecutionException, InterruptedException {
        quoteGroupVO = changeDate(quoteGroupVO);
        String message = validate(quoteGroupVO);
        if (StringUtils.isNotEmpty(message)) return fail(500, message);
        LoginUserVO loginUserVO = new LoginUserVO(LoginHelper.getLoginSiteId(), LoginHelper.getLoginName());
        quoteGroupService.addQuoteGroupVO(quoteGroupVO, loginUserVO);
        return success();
    }
}

3. ExceptionAdvice

package com.thrall.web.base;

import com.thrall.business.vaild.ThrallValid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
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;

/**
 * Created by dongrj on 2017/1/9 12:46:02.
 * Email: dongrongjun@cn
 * 用于处理所有ThrallValid标记的异常情况
 */

@ControllerAdvice(annotations = ThrallValid.class)
@ResponseBody
public class ExceptionAdvice {

    private static Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);

    @ExceptionHandler(BindException.class)
    public JsonResult handleBindException(BindException e) {
        logger.error("参数绑定失败", e);
        BindingResult bindingResult = e.getBindingResult();
        FieldError fieldError = bindingResult.getFieldError();
        String message = fieldError.getDefaultMessage();
        JsonResult result=new JsonResult<Integer>();
        result.setCode(500);
        result.setMessage(message);
        return result;
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        logger.error("参数验证失败", e);
        BindingResult bindingResult = e.getBindingResult();
        FieldError fieldError = bindingResult.getFieldError();
        String message = fieldError.getDefaultMessage();
        JsonResult result=new JsonResult<Integer>();
        result.setCode(500);
        result.setMessage(message);
        return result;
    }


    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public void handleException(Exception e) {
        logger.error("通用异常!", e);
    }
}

4.分组类

package com.thrall.business.vaild;

/**
 * Created by dongrj on 2017/1/17 16:08:43.
 * Email: dongrongjun@cn
 */
public interface VaildQuoteGroupVOEdit {
}

© 著作权归作者所有

ShortHand
粉丝 4
博文 78
码字总数 16508
作品 0
静安
高级程序员
私信 提问
Struts、Hibernate和Spring常见面试题的问与答

原文:http://www.java-home.com/thread-574-1-1.html Hibernate工作原理及为什么要用? 原理: 1.读取并解析配置文件 2.读取并解析映射信息,创建SessionFactory 3.打开Sesssion 4.创建事务...

迷路的阿修罗
2010/12/03
659
0
第二部分:Spring,hibernate,struts的面试笔试题

Hibernate工作原理及为什么要用? 原理: 1.读取并解析配置文件 2.读取并解析映射信息,创建SessionFactory 3.打开Sesssion 4.创建事务Transation 5.持久化操作 6.提交事务 7.关闭Session 8...

小梅菜鸟
2012/02/26
152
0
Spring MVC 中的Hibernate Validater问题

Hibernate Validater中的注解可以定义@NotNull之类的注解,可是在有的业务处理中是可以为空的,有的又不行,回到Spring MVC ,肯定不能处理所有的验证,难道我还要写个Interceptor或者Validate判断...

天使会唱歌
2011/01/09
2.1K
5
Spring Validation实现原理分析

最近要做动态数据的提交处理,即需要分析提交数据字段定义信息后才能明确对应的具体字段类型,进而做数据类型转换和字段有效性校验,然后做业务处理后提交数据库,自己开发一套校验逻辑的话周...

68号小喇叭
2018/07/08
0
0
jPA自动创建数据库表的一些配置

hibernate.cfg.xml 中hibernate.hbm2ddl.auto配置节点如下: <properties> <property name="hibernate.show_sql" value="true" /> <property name="hibernate.hbm2ddl.auto" value="create" ......

Edwinn
2012/05/22
9.1K
0

没有更多内容

加载失败,请刷新页面

加载更多

Executor线程池原理与源码解读

线程池为线程生命周期的开销和资源不足问题提供了解决方 案。通过对多个任务重用线程,线程创建的开销被分摊到了多个任务上。 线程实现方式 Thread、Runnable、Callable //实现Runnable接口的...

小强的进阶之路
今天
6
0
maven 环境隔离

解决问题 即 在 resource 文件夹下面 ,新增对应的资源配置文件夹,对应 开发,测试,生产的不同的配置内容 <resources> <resource> <directory>src/main/resources.${deplo......

之渊
今天
8
0
详解箭头函数和普通函数的区别以及箭头函数的注意事项、不适用场景

箭头函数是ES6的API,相信很多人都知道,因为其语法上相对于普通函数更简洁,深受大家的喜爱。就是这种我们日常开发中一直在使用的API,大部分同学却对它的了解程度还是不够深... 普通函数和...

OBKoro1
今天
7
0
轻量级 HTTP(s) 代理 TinyProxy

CentOS 下安装 TinyProxy yum install -y tinyproxy 启动、停止、重启 # 启动service tinyproxy start# 停止service tinyproxy stop# 重启service tinyproxy restart 相关配置 默认...

Anoyi
今天
2
0
Linux创建yum仓库

第一步、搞定自己的光盘 #创建文件夹 mkdir -p /media/cdrom #挂载光盘 mount /dev/cdrom /media/cdrom #编辑配置文件使其永久生效 vim /etc/fstab 第二步,编辑yun源 vim /ect yum.repos.d...

究极小怪兽zzz
今天
6
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部