springboot进阶之web进阶

慕课网完整教程

以下教程完整源码

@Valid 表单验证

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//控制器
@PostMapping("/insert")
public Gril insert(@Valid Gril g1, BindingResult bindingResult){
if(bindingResult.hasErrors()){
System.out.println(bindingResult.getFieldError().getDefaultMessage());
}
Gril g=new Gril();
g.setAge(g1.getAge());
g.setCupSize(g1.getCupSize());

return grilRepository.save(g);

}

//实体类
@Min(value = 18,message = "没成年不能插入数据库")
private Integer age;

AOP 面向切面编程思想

  • 图解:将通用业务从具体逻辑中分离出来

AOP记录http请求

  • @After
  • @Before
  • @AfterReturning

统一异常处理

自己写返回格式

  • 新建Result类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
public class Result<T> {
//错误码
private Integer code;
//错误信息
private String msg;
//数据 T是个泛型
private T data;

public Integer getCode() {
return code;
}

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

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}

public T getData() {
return data;
}

public void setData(T data) {
this.data = data;
}
}
/*//通一异常处理 单个对象返回json举例
//错误时
{
"code":1,
"msg":"金额必传",
"data":null
}
//正确时
{
"code":0,
"msg":"成功",
"data":{
"id":20,
"cupSize":"B",
"age":25,
"money":1.2
}
}*/
  • 在controller类使用
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    public Object insert(@Valid  Gril g1, BindingResult bindingResult){
    if(bindingResult.hasErrors()){
    // System.out.println(bindingResult.getFieldError().getDefaultMessage());
    //改进 统一异常处理 @Autowrite引入报错
    Result result=new Result();
    result.setCode(1);
    result.setMsg(bindingResult.getFieldError().getDefaultMessage());
    result.setData(null);
    return result;

    }
    Gril g=new Gril();
    g.setAge(g1.getAge());
    g.setCupSize(g1.getCupSize());
    Result result=new Result();
    result.setCode(0);
    result.setMsg("成功");
    result.setData(grilRepository.save(g));

    return result;

    }


把上面的代码用工具类ResultUtil 封装

  • 实现年龄判断并做相应处理 统一异常返回格式。
  • ResultUtil.err(1,”未成年禁止入内”);
  • @ControllerAdvance
  • @ExceptionHandel
  • @ResponseBody
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    //新建工具类
    public class ResultUtil {
    public static Result success(Object object){
    Result result=new Result();
    result.setCode(0);
    result.setMsg("成功");
    result.setData(object);
    return result;
    }
    public static Result success(){
    return success(null);
    }
    public static Result err(Integer code,String msg){
    Result result=new Result();
    result.setCode(code);
    result.setMsg(msg);
    return result;

    }
    }
    //GrilService
    public void getAge(Integer id)throws Exception{
    Gril gril=grilRepository.getOne(id);
    if(gril.getAge()<10){
    throw new Exception("你在上小学");
    }else if(gril.getAge()<30){
    throw new Exception("你在上初中");
    }
    }
    //Controller
    @GetMapping(value = "/getAge/{id}")
    public void getAge(@PathVariable("id")Integer id)throws Exception{
    grilService.getAge(id);
    }
    //ExceptionHandel
    @ControllerAdvice
    public class ExceptionHandel {
    //获取具体Controller类抛出的异常
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result handel(Exception e){
    return ResultUtil.err(100,e.getMessage());
    }

    }

在改进 自定义异常GrilException

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public class GrilException extends RuntimeException{
private Integer code;

public GrilException(Integer code ,String msg) {
super(msg);
this.code = code;
}

public Integer getCode() {
return code;
}

public void setCode(Integer code) {
this.code = code;
}
}
//使用
//GrilService
public void getAge(Integer id)throws Exception{
Gril gril=grilRepository.getOne(id);
if(gril.getAge()<10){
throw new GrilException(100,"你在上小学");
}else if(gril.getAge()<30){
throw new GrilException(101,"你在上初中");
}
}
//GrilController
@GetMapping(value = "/getAge/{id}")
public void getAge(@PathVariable("id")Integer id)throws Exception{
grilService.getAge(id);
}
//ExceptionHandel
@ControllerAdvice
public class ExceptionHandel {
private final static Logger logger=LoggerFactory.getLogger(ExceptionHandler.class);
//获取具体Controller类抛出的异常
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Result handel(Exception e){
if(e instanceof GrilException){
GrilException grilException=(GrilException)e;
return ResultUtil.err(grilException.getCode(),grilException.getMessage());
}else {
logger.error("【系统异常】{}");
return ResultUtil.err(-1,"未知错误");
}

}

在改进 把错误码方法enum中管理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
//ResultEnum
public enum ResultEnum {
UNKNOW_ERROR(-1,"未知错误"),
SUCCESS(0,"成功"),
PRIMARY_SCHOOL(100,"还在上小学"),
MIDDLE_SCHOOL(101,"还在上初中"),
;


private Integer code;
private String msg;

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

public Integer getCode() {
return code;
}

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

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}
}
//使用
//GrilService
public void getAge(Integer id)throws Exception{
Gril gril=grilRepository.getOne(id);

if(gril.getAge()<10){
throw new GrilException(ResultEnum.PRIMARY_SCHOOL.getCode(),ResultEnum.PRIMARY_SCHOOL.getMsg());
}else if(gril.getAge()<30){
throw new GrilException(ResultEnum.MIDDLE_SCHOOL.getCode(),ResultEnum.MIDDLE_SCHOOL.getMsg());
}
}
//GrilController
public void getAge(Integer id)throws Exception{
Gril gril=grilRepository.getOne(id);

if(gril.getAge()<10){
throw new GrilException(ResultEnum.PRIMARY_SCHOOL);
}else if(gril.getAge()<30){
throw new GrilException(ResultEnum.MIDDLE_SCHOOL);
}
}
//报错 需改 GrilException
public class GrilException extends RuntimeException{
private Integer code;

public GrilException(ResultEnum resultEnum) {
super(resultEnum.getMsg());
this.code = resultEnum.getCode();
}

public Integer getCode() {
return code;
}

public void setCode(Integer code) {
this.code = code;
}
}
//ExceptionHandel 不用改
@ControllerAdvice
public class ExceptionHandel {
private final static Logger logger=LoggerFactory.getLogger(ExceptionHandler.class);
//获取具体Controller类抛出的异常
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Result handel(Exception e){
if(e instanceof GrilException){
GrilException grilException=(GrilException)e;
return ResultUtil.err(grilException.getCode(),grilException.getMessage());
}else {
logger.error("【系统异常】{}");
return ResultUtil.err(-1,"未知错误");
}

}

}

单元测试

  • 对api接口(Mappering(url)) /service/ controller方法进行测试
  • @RunWith
  • @SpringBootTest
  • @AutoConfigureMockMvc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class GrilControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void grilList() throws Exception{
mvc.perform(MockMvcRequestBuilders.get("/grilList"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string("abc"));

}
}

多个单元测试

  • 项目打包时会自动运行测试类 有错则打包失败