SpringBoot使用进阶
来源:互联网 发布:知乎回答排名规则 编辑:程序博客网 时间:2024/06/10 20:55
一、表单验证
在实体内注解验证信息
package com.lei.domain;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.validation.constraints.Min;@Entitypublic class Girl { //@GeneratedValue自增 @Id @GeneratedValue private Integer id; private String name; //年龄最小为18,如果低于18提示信息为:不允许未成年入内 @Min(value = 18,message = "不允许未成年入内") private Integer age; private String cupSize; //一定要有个无参的构造方法 public Girl() { } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCupSize() { return cupSize; } public void setCupSize(String cupSize) { this.cupSize = cupSize; }}
输出表单验证是否通过(Controller)
/** * 添加一个女生 * BindingResult 存放验证不通过的对象 */ @PostMapping(value = "/addGirl") public Result<Girl> addGirl(@Valid Girl girl, BindingResult bindingResult){ if (bindingResult.hasErrors()){ return ResultUtil.error(1,bindingResult.getFieldError().getDefaultMessage()); } return ResultUtil.success(girlRepository.save(girl)); }
二、AOP统一处理添加依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency>
Http请求拦截
package com.lei.aspect;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.annotation.*;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;import javax.servlet.http.HttpServletRequest;/** * Http请求拦截 */@Aspect@Componentpublic class HttpAsPect { private final static Logger logger = LoggerFactory.getLogger(HttpAsPect.class); //定义一个切面方法,拦截GirlController下面的所有方法,(..) ..代表所有参数 @Pointcut("execution(public * com.lei.controller.GirlController.*(..))") public void log(){ } @Before("log()") public void doBefore(JoinPoint joinPoint){ logger.info("调用方法前。。。。。"); ServletRequestAttributes attributes =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); //url logger.info("url={}",request.getRequestURL()); //ip logger.info("ip={}",request.getRemoteAddr()); //method logger.info("method={}",request.getMethod()); //类方法 logger.info("class_method={}",joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName()); //参数 logger.info("args={}",joinPoint.getArgs()); } @After("log()") public void doAfter(){ logger.info("调用方法后。。。。。。"); } //return 后 @AfterReturning(returning = "object",pointcut = "log()") public void doAfterReturning(Object object){ logger.info("response={}",object.toString()); }}三、统一异常处理
1、定义统一的返回模型
package com.lei.domain;/** * 返回前台对象 */public class Result<T> { /** 0为成功,1为失败*/ private Integer code; private String msg; 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; }}返回对象模型的工具类
package com.lei.utils;import com.lei.domain.Result;/** * 返回结果的工具类 */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 error(Integer code,String msg){ Result result = new Result(); result.setCode(code); result.setMsg(msg); return result; }}
2、定义自己的异常并统一捕获
1)定义异常枚举
package com.lei.enums;public enum ExceptionEnum { UNKNOW_ERROR(-1,"未知错误"), SUCCESS(0,"成功"), XIAO_SCHOOL(100,"你还在上小学吧"), MIDDLE_SCHOOL(101,"你在上初中吧"); private Integer code; private String msg; ExceptionEnum(Integer code, String msg) { this.code = code; this.msg = msg; } public Integer getCode() { return code; } public String getMsg() { return msg; }}
2)定义自己的异常类package com.lei.exception;import com.lei.enums.ExceptionEnum;/** * Girl的异常类 */public class GirlException extends RuntimeException{ private Integer code; public GirlException(ExceptionEnum exceptionEnum) { super(exceptionEnum.getMsg()); this.code = exceptionEnum.getCode(); } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; }}3)捕获异常的Handler
package com.lei.handler;import com.lei.domain.Result;import com.lei.enums.ExceptionEnum;import com.lei.exception.GirlException;import com.lei.utils.ResultUtil;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.ResponseBody;/** * 异常类的Handler */@ControllerAdvicepublic class ExceptionHandle { private static final Logger logger = LoggerFactory.getLogger(ExceptionHandle.class); @ExceptionHandler(value = Exception.class) @ResponseBody public Result getAgeHandle(Exception e){ if (e instanceof GirlException){ GirlException girlException = (GirlException)e; return ResultUtil.error(girlException.getCode(),girlException.getMessage()); }else { logger.info("系统异常:{}",e); throw new GirlException(ExceptionEnum.UNKNOW_ERROR); } }}4) service层使用异常类public void getAge(Integer id) throws Exception{ Girl girl = girlRepository.findOne(id); Integer age = girl.getAge(); //验证,如果年龄太小就给前端返回信息 if (age<10){ throw new GirlException(ExceptionEnum.XIAO_SCHOOL); }else if (age>10&&age<16){ throw new GirlException(ExceptionEnum.MIDDLE_SCHOOL); } //验证通过之后,做下面的逻辑.... }
四、单元测试
测试Service层的用例
package com.lei.service;import org.junit.Assert;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;import static org.junit.Assert.*;@RunWith(SpringRunner.class)@SpringBootTestpublic class GirlServiceTest { @Autowired private GirlService girlService; @Test public void findOneAge() throws Exception { Assert.assertEquals(new Integer(12),girlService.findOneAge(1)); }}测试Controller层的用例
package com.lei.controller;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;import org.springframework.test.web.servlet.MockMvc;import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;import org.springframework.test.web.servlet.result.MockMvcResultMatchers;import static org.junit.Assert.*;@RunWith(SpringRunner.class)@SpringBootTest@AutoConfigureMockMvcpublic class GirlControllerTest { @Autowired private MockMvc mvc; @Test public void getAll() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/girl/getAll")) .andExpect(MockMvcResultMatchers.status().isOk())//判断链接是否可以访问 .andExpect(MockMvcResultMatchers.content().string("123456"));//判断返回的内容是不是我们想要的 }}
阅读全文
0 0
- SpringBoot使用进阶
- SpringBoot进阶之单元测试
- 期末考核SpringBoot进阶之Web进阶
- SpringBoot进阶之Web笔记
- springboot使用
- SpringBoot进阶之使用异常替代返回错误码(拦截异常并统一处理)
- Springboot 之 JPA数据库操作进阶篇
- SpringBoot进阶之JPA实现分页、排序
- springboot笔记(2)springboot-Mybatis使用
- SpringBoot-04SpringBoot使用JdbcTemplate操作数据库
- springboot系列文章(四)-springboot使用fastjson
- SpringBoot入门-13(springboot配置使用YML)
- SpringBoot 中使用 Log4j
- springboot中使用Druid
- springboot 使用心得
- SpringBoot中使用redis
- SpringBoot中使用Filter
- springboot使用shiro
- JAVA排序汇总
- Spring-Data-Redis之RedisTemplate的使用
- Ubuntu 常用终端命令
- jupyter notebook资料
- 蓝桥杯 算法训练 邮票
- SpringBoot使用进阶
- 利用Docker,构建宝塔linux面板镜像
- codeforces Round #451 (Div. 2) Phone Numbers
- Linux安装JDK
- 录音文件与Base64编码相互转换的方法
- Ubuntu 常用快捷键
- 大型分布式网站架构设计与实践 第四章
- Java基础—常用DOS命令
- 37. Sudoku Solver