博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Hibernate-Validate结合SpringMVC数据验证
阅读量:6335 次
发布时间:2019-06-22

本文共 8926 字,大约阅读时间需要 29 分钟。

hot3.png

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")@ThrallValidpublic class QuoteGroupController extends BaseSpringController {    @Autowired    QuoteGroupService quoteGroupService;    @Autowired    CustomerQuoteConfigService customerQuoteConfigService;        /**     * 获取报价组     */    @RequestMapping(value = "/page", method = RequestMethod.POST)    public JsonResult
> selectByPaging(@RequestBody PageParam
pageParam) { LoginUserVO loginUserVO = new LoginUserVO(LoginHelper.getLoginSiteId(), LoginHelper.getLoginName()); Page
page = quoteGroupService.selectPaging(pageParam, loginUserVO); return success(page); } /** * 添加报价组 */ @RequestMapping(value = "/add", method = RequestMethod.POST) public JsonResult
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)@ResponseBodypublic 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
(); 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
(); 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 {}

转载于:https://my.oschina.net/famiover/blog/828444

你可能感兴趣的文章
【编译打包】folly-0.31-1.el7.centos.src.rpm
查看>>
移动用户体验设计中的原型应用
查看>>
A10虚拟化技术在“云计算”中的应用
查看>>
windows7显示摄像头图标的方法
查看>>
nginx apache Smokeping 安装配置
查看>>
实战1:创建Windows Server 2008域
查看>>
DAO-数据访问对象(Data Access Object) 模式
查看>>
失声的黄莺
查看>>
foreman架构的引入3-安装Foreman1.5.3架构(all-in-one)
查看>>
职业机会成本
查看>>
深入研究java.lang.ProcessBuilder类
查看>>
解析入口参数为实体的表达式树
查看>>
【原创】利用MySQL 的GROUP_CONCAT函数实现聚合乘法
查看>>
使用RHEL6.3+PXE+DHCP+Apache+NFS+KickStart 无人值守安装RHEL6.3
查看>>
Bing Maps进阶系列四:路由功能服务(RouteService)
查看>>
46. Permutations——本质和树DFS遍历无异 fun: for i in nums fun(i)
查看>>
Java线程:大总结
查看>>
java.lang.OutOfMemoryError: GC overhead limit exceeded
查看>>
Android--MediaPlayer高级
查看>>
C#:10进制转2进制函数
查看>>