Summary of Spring Boot Web Development

1. Form Validation

First, add validation annotations to the fields that need to be validated in the entity class. The validation annotation classes are mainly under the javax.validation.constraints package of validation-api-1.1.0.Final.jar, and hibernate-validator-5.3.6. Under the org.hibernate.validator.constraints package of Final.jar, commonly used validation annotations:   @Min @Max @Length @Email etc.

public class User {

	private Integer id;
	private String name;
	@Min(value=12,message="年龄不能小于12岁")
	private Integer age;

Then, add the @Valid annotation before the parameters that need to be verified , and use BindingResult to get the information that the verification failed

@RestController
public class UserController {

	@PostMapping("/addUser")
	public void getUserList(@Valid User user, BindingResult bindingResult) {
		if(bindingResult.hasErrors()) {
			// 打印出字段验证信息
			System.out.println(bindingResult.getFieldError().getDefaultMessage());
			System.out.println("BBBBBBBBB");
		}
		System.out.println("AAAAAAAAAAA");
	}
}

2. AOP handles requests uniformly

First, to introduce aop related jar package

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-aop</artifactId>
</dependency>

Then, create a new aop class

package com.codingos.springboot.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class HttpAspect {
	private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);

	@Pointcut("execution(public * com.codingos.springboot.controller.UserController.*(..))")
	public void log() {
	}

	/**
	 *  在被切入的方法执行之前执行
	 */
	@Before("log()")
	public void doBefore(JoinPoint joinPoint) {
		logger.info("***************** before aop 执行 ****************");
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		// url
		logger.info("url={}", attributes.getRequest().getRequestURL());
		// methond
		logger.info("method={}", attributes.getRequest().getMethod());
		// ip
		logger.info("ip={}", attributes.getRequest().getRemoteAddr());
		// 类方法
		logger.info("class_method={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
		// 参数
		logger.info("args={}", joinPoint.getArgs());
	}

	/**
	 *  在被切入的方法执行之后执行
	 */
	@After("log()")
	public void doAfter() {
		logger.info("************************ after aop 执行 **************************");
	}
	
	/**
	 * 用来获取返回值
	 */
	@AfterReturning(returning = "object",pointcut = "log()")
	public void doAfterReturning(Object object) {
		logger.info("response={}", object.toString());
	}
}

3. Unified return format

Unified return entity class

package com.codingos.springboot.common;

public class Result<T> {

	private Integer code;// 正常成功为0,异常失败为1
	private String message;
	private T data;
	
	public Result() {
	}

	public Integer getCode() {
		return code;
	}

	public void setCode(Integer code) {
		this.code = code;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public T getData() {
		return data;
	}

	public void setData(T data) {
		this.data = data;
	}
}

Back to Tools

public class ResultUtil<T> {

	public static <T> Result<T> success(T object) {
		Result<T> result = new Result<>();
		result.setCode(0);
		result.setMessage("成功");
		result.setData(object);
		return result;
	}
	
	public static <T> Result<T> success() {
		Result<T> result = new Result<>();
		result.setCode(0);
		result.setMessage("成功");
		return result;
	}
	
	public static <T> Result<T> error(Integer code, String message) {
		Result<T> result = new Result<>();
		result.setCode(code);
		result.setMessage(message);
		return result;
	}
}

Return status code (error code)

public enum ResultEnum {

	EXCEPTION(-1,"未知异常"),
	SUCCESS(0,"操作正常"),
	ERROR(1,"发生错误");

	private Integer code;
	private String message;
	
	private ResultEnum(Integer code, String message) {
		this.code = code;
		this.message = message;
	}

	public Integer getCode() {
		return code;
	}

	public void setCode(Integer code) {
		this.code = code;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
}

4. Unified exception handling

custom exception

public class CustomException extends RuntimeException {
	private static final long serialVersionUID = 7425266758852563283L;

	private Integer code;

	public CustomException(ResultEnum resultEnum) {
		super(resultEnum.getMessage());
		this.code = resultEnum.getCode();
	}

	public Integer getCode() {
		return code;
	}

	public void setCode(Integer code) {
		this.code = code;
	}
}

Unified exception handling class (exceptions are thrown up, and they are also thrown out at the controller layer)

@ControllerAdvice
public class ExceptionHandle {
	private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);

	@ExceptionHandler(value=Exception.class)
	@ResponseBody
	public Result<Object> handle(Exception e) {
		logger.error(ResultEnum.EXCEPTION.getMessage(), e);
		return ResultUtil.result(ResultEnum.EXCEPTION, e.getMessage());
	}
}

 

Code reference can go to  the spring-boot-web directory in
my code cloud  https://gitee.com/jayking/spring-boot-learning

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325470089&siteId=291194637