ssm(3-2)Springmvc拓展
阿新 • • 發佈:2018-11-10
1.rest風格
2.1配置正則例項
@AllArgsConstructor @NoArgsConstructor @Data @Accessors(chain = true) //lombok public class User implements Serializable { private String name; }
@RestController //responsebody +controller public class UserController { @GetMapping("/user/{name:.*}") public User testUser(@PathVariable(required = false,value = "name") User user){ System.out.println(user.getClass()); return user; } }
@SpringBootApplication public class MvcDemoApplication { public static void main(String[] args) { SpringApplication.run(MvcDemoApplication.class, args); } }
@Configuration @ComponentScan(value = "springmvc.demo")//掃描包 public class MVCConfig { }
spring.http.encoding.charset=UTF-8 #處理編碼 spring.http.encoding.force=true spring.http.encoding.enabled=true server.tomcat.uri-encoding=UTF-8
[email protected]與@Validated
@valid與@Validated的區別,@Validated是spring中的,是在@valid基礎上而來的,在@valid的基礎上增加分組功能,這裡就直接說@Validated,沒有加分組都需要認證,加了分組只有符合分組的才需要認證,一般不使用分組
3.1基本使用
@AllArgsConstructor @NoArgsConstructor @Data @Accessors(chain = true) public class User implements Serializable { @NotNull(message="不能為空")//含有屬性groups private String name; }
@RestController public class UserController { @GetMapping("/user") public User testUser(@Validated User user, BindingResult result){ result.getAllErrors().stream().forEach((x)->{ System.out.println(x.getObjectName()+":"+x.getDefaultMessage()); }); System.out.println(user.getClass()); return user; } }
輸出結果:user:不能為空
備註:假如沒有BindingResult result,那麼在進入testUser之前就會被攔截,message="不能為空"並沒有什麼作用,加入BindingResult result之後,才會進入testUser方法,在沒有進入方法時的異常頁面見後該篇4
3.2自定義符合valid的註解
這裡定義的是@NoNull註解
//會自動載入,不需要其他的配置 public class MyValidAnnotation implements ConstraintValidator<MyNotNull,Object> { /* obj:需要驗證的引數 */ @Override public boolean isValid(Object obj, ConstraintValidatorContext constraintValidatorContext) { System.out.println(obj); return false; } @Override public void initialize(MyNotNull constraintAnnotation) { } }
@Target({ElementType.METHOD, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy =MyValidAnnotation.class ) public @interface MyNotNull { String message() default "{javax.validation.constraints.NotNull.message}"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
@AllArgsConstructor @NoArgsConstructor @Data @Accessors(chain = true) public class User implements Serializable { @MyNotNull(message="不能為空---MyNotNull") private String name; }
@RestController public class UserController { @GetMapping("/user") public User testUser(@Validated User user, BindingResult result){ result.getAllErrors().stream().forEach((x)->{ System.out.println(x.getObjectName()+":"+x.getDefaultMessage()); }); return user; } }
4.異常訊息的處理
4.1驗證異常訊息的處理上述已經說明
4.2直接被攔截的異常處理
springboot會相應的轉向我們在resources下新建的resources的error的相應的錯誤程式碼的頁面
還可以是如下這樣,表示以4開頭的錯誤頁面
4.3執行過程中出現的異常
4.3.1直接丟擲異常
@GetMapping("/user/error") public User testUser1(@Validated User user, BindingResult result) throws Exception { throw new Exception("出錯了"); }
4.3.2 throw自定義異常類
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR,reason = "內部出錯了!") public class MyException extends RuntimeException { }
@GetMapping("/user/error") public User testUser1(@Validated User user, BindingResult result) throws Exception { throw new MyException(); }
4.3.3 使用@ExceptionHandler
註解
@ResponseBody @GetMapping("/testExceptionHandler") public User testUser1(@Validated User user, BindingResult result) throws Exception { int i=10/0; return user; }
@ExceptionHandler({Exception.class}) public String testExceptionHandler(){ return "redirect:/error.html"; //重定向 }
4.3.4 修改狀態碼及原因,@ResponseStatus也能在
@ExceptionHandler({Exception.class}) @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR,reason = "內部錯誤") public void testExceptionHandler(){ }
備註:這樣之後不會去相應的頁面,也就是加入有返回值例如return "redirect:/error.html";,會失效
[email protected]定製全域性的異常,類中的@ExceptionHandler優先順序高於@ControllerAdvice中的@ExceptionHandler優先順序
@ControllerAdvice public class MyExceptionHandler { @ExceptionHandler({Exception.class}) @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR,reason = "內部錯誤") public void testExceptionHandler(){ } }
5.jsonview