使用注解对对象属性字段进行判空、长度及日期格式校验

1.实体类属性添加注解

import java.util.Date;

import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;

public class Student {
	@Length(min=4,max=10,message="字段长度不能超过4至10个字符")
	private String name ;
	
	@NotEmpty(message="年龄不能为空!")
	private int age ;
	
	@DateTimeFormat(pattern="yyyy-MM-dd")
	private Date date ;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + ", date=" + date
				+ "]";
	}		
}

2.控制层使用实体对象使用注解

import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.liuchao.domain.Student;
@Controller
public class IndexController {
	
	private static final Logger log = Logger.getLogger(IndexController.class);
	
	@RequestMapping("/test")
	public String test(@Valid Student student){	
		return "index";
	}
}

3.声明统一异常处理类,捕捉不同类型的异常

import java.io.IOException;
import java.lang.reflect.UndeclaredThrowableException;

import org.apache.log4j.Logger;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.liuchao.bean.APPFinalConfig;
import com.liuchao.bean.JResult;

@ControllerAdvice
@ResponseBody
public class ExceptionHandle {
	
	public static final Logger log = Logger.getLogger(ExceptionHandle.class);

	
	/**
	 * @Description: 对象参数异常处理
	 * @author lc
	 * @param ex
	 * @throws
	 * @return JResult    返回类型
	 */
	@ExceptionHandler(BindException.class)
	@ResponseBody
	public JResult  bindException(BindException ex) {
		log.error(APPFinalConfig.ERROR, ex);
		JResult result = new JResult();
		result.setErrorCode(APPFinalConfig.ERROR);
		result.setState("-1001");
		StringBuilder msg = new StringBuilder() ;
		BindException exception = (BindException)ex ;
		for (FieldError error : exception.getBindingResult().getFieldErrors()) {
            /*msg.append("参数");
            msg.append(error.getField());
            msg.append("=");
            msg.append(error.getRejectedValue());
            msg.append(",说明:");*/
			msg.append(error.getDefaultMessage());
		}
		result.setDescription(msg.toString());
		return result ;
	}
		
		/**
		 * @Title: exceptionHandle
		 * @Description: 参数异常处理
		 * @author lc
		 * @param ex
		 * @throws IOException
		 * @return JResult    返回类型
		 */
		@ExceptionHandler(UndeclaredThrowableException.class)
		@ResponseBody
		public JResult  parameterException(UndeclaredThrowableException ex){

			log.error(APPFinalConfig.ERROR, ex);
			JResult result = new JResult();
			result.setErrorCode(APPFinalConfig.ERROR);
			result.setState("-1001");
			result.setDescription(ex.getCause().getMessage());
			return result ;
		}
	
	/**
	 * @Title: exceptionHandle
	 * @Description: 默认异常处理
	 * @author lc
	 * @param ex
	 * @throws IOException
	 * @return JResult    返回类型
	 */
	@ExceptionHandler(Exception.class)
	@ResponseBody
	public JResult  exceptionHandle( Exception ex) {

		log.error(APPFinalConfig.ERROR, ex);
		ex.printStackTrace();
		JResult result = new JResult();
		result.setErrorCode(APPFinalConfig.ERROR);
		result.setState("-1001");
		result.setDescription("系统出现异常");
		return result ;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值