SpringBoot進階

慕課網連接

表單數據的驗證

在pojo類屬性的上面添加註解 
@Entity
public class Girl {

    @Id
    @GeneratedValue
    private Integer id;

    @NotBlank(message = "這個字段必傳")
    private String cupSize;

    @Min(value = 18, message = "未成年少女禁止入門")
//    @NotNull
//    @Max()
//    @Length()
    private Integer age;
}

校驗使用(使用@valid來驗證)java

@PostMapping(value = "/girls")
    public Result girlAdd(@Valid Girl girl, BindingResult bindingResult) {

        //使用BindingResult對象輸出校驗對象的出錯信息

        if (bindingResult.hasErrors()) {
            return ResultUtil.error(1, bindingResult.getFieldError().getDefaultMessage());
        }
 
        girl.setCupSize(girl.getCupSize());
        girl.setAge(girl.getAge());
 
        return ResultUtil.success(girlRepository.save(girl));
    }

AOP統一處理

在pom中添加依賴spring

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

並添加AOP操做類編程

@Aspect
@Component
public class HttpAspect {

}

添加方法mvc

@Before("execution(public * com.controller.GirlController.*(..))")
    public void before() {
      System.out.println("指定方法以前執行")
    }

   @After("execution(public * com.controller.GirlController.*(..))")
    public void after() {
      System.out.println("指定方法以後執行")
    }

/**
*    @Before: 方法執行以前
*    @After: 方法執行以後
*    @AfterReturning: 方法返回以後
*    (..)表示任何參數都會被攔截
*    *表明全部
*/

若是屢次爲這些方法進行切面編程可以使用@Pointcut註解app

@Ponitcut("execution(public * com.controller.GirlController.*(..))")
   public void log(){}

   @Before("log()")
    public void before() {
      System.out.println("指定方法以前執行")
    }

   @After("log()")
    public void after() {
      System.out.println("指定方法以後執行")
    }

實際項目開發中也不推薦使用控制檯輸出(使用日誌輸出)ide

@Aspect
@Component
public class HttpAspect {

   private final static Looger logger=LoggerFactory.getLogger;

    @After("log()")
    public void doAfter() {
        logger.info("指定方法以後執行")
    }

    //輸出方法的放回結果
    @AfterReturning(returning = "object", pointcut = "log()")
    public void doAfterReturning(Object object) {
        logger.info("response={}", object.toString());
    }

}

日誌添加有用信息(請求有關的數據)

@Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        //url
        logger.info("url={}", request.getRequestURL());

        //method
        logger.info("method={}", request.getMethod());

        //ip
        logger.info("ip={}", request.getRemoteAddr());

        //類方法
        logger.info("class_method={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());

        //參數
        logger.info("args={}", joinPoint.getArgs());
    }

異常的捕獲和處理

統一異常處理的步驟spring-boot

  1. 創建一個Result類  :http請求返回的最外層對象,包括code msg data工具

  2. 寫一個工具類:優化代碼(減小重複代碼)單元測試

//===========自定義異常類(spring只能捕獲運行時異常,因此繼承RuntimeException類)=============
public class GirlException extends RuntimeException{
	private Integer code;
	public GirlException(ResultEnum resultEnum) {
		super(resultEnum.getMsg());
		this.code=resultEnum.getCode();
	}
	public Integer getCode() {
		return code;
	}
	public void setCode(Integer code) {
		this.code = code;
	}
}

//==========異常捕獲===========
@ControllerAdvice
public class ExceptionHandle {
	private final static Logger logger=LoggerFactory.getLogger(ExceptionHandle.class);
	@ExceptionHandler(value=Exception.class)
	@ResponseBody
	public Result handle(Exception e) {
		if(e instanceof GirlException) {
			GirlException girlException=(GirlException)e;
			return ResultUitl.error(girlException.getCode(), girlException.getMessage());
		}else {
			logger.error("【系統異常】{}",e);
			return ResultUitl.error(-1, e.getMessage());
		}
	}
}

異常出現的狀況測試

//=========GirlController=======
 @RequestMapping("/girlGetAge/{id}")
	 public void getAge(@PathVariable("id") Integer id) throws Exception {
		 girlService.getAge(id);
	 }
//==========GirlService==============
//異常拋給controller
	public void getAge(Integer id) throws Exception{
		Girl girl=girlRepository.findOne(id);
		Integer age=girl.getAge();
		if(age<10) {
			throw new GirlException(ResultEnum.PRIMARY_SCHOOL);
		}else if(age>10 && age<16) {
			throw new GirlException(ResultEnum.MIDDLE_SCHOOL);
		}
	}
//=========ResultEnum==========
public enum ResultEnum {
	UNKONW_ERROR(-1,"未知錯誤"),
	SUCCESS(0,"成功"),
	PRIMARY_SCHOOL(100,"你在上小學"),
	MIDDLE_SCHOOL(101,"你在上初中"),
	;
	private Integer code;
	private String msg;
	get\set方法......
}

單元測試

測試controller

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class GrilController {
	@Autowired
	private MockMvc mvc;
	@Test
	public void girlList() throws Exception {
		mvc.perform(
				MockMvcRequestBuilders.get("/girl/girls"))
		.andExpect(MockMvcResultMatchers.status().isOk())
		.andExpect(MockMvcResultMatchers.content().string("abc"));
	}
}
相關文章
相關標籤/搜索