一、使用@Valid表单验证

于实体类中添加@Min等注解

 @Entity
public class Girl { @Id
@GeneratedValue
private Integer id; private String cupSize;
@Min(value = 18,message = "未成年禁止入内!")
private Integer age;
...
}

给指定的访问方法参数添加@Valid 注解,并使用BindingResult bindingResult对象获取返回结果

 @PostMapping(value = "/girls")
public Girl addgirl(@Valid Girl girl, BindingResult bindingResult){
if (bindingResult.hasErrors()){
System.out.println(bindingResult.getFieldError().getDefaultMessage());
return null;
}
girl.setCupSize(girl.getCupSize());
girl.setAge(girl.getAge());
return girlRepository.save(girl);
}

二、使用AOP处理请求

使用AOP统一处理请求日志

在pom文件中添加aop依赖,

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

新建aspect类:

 @Aspect
@Component
public class HttpAspect { @Pointcut("execution(public * com.cenobitor.controller.GirlController.girlList(..))")
public void log(){
} @Before("log()")
public void doBefore(){
System.out.println(11111111);
} @After("log()")
public void doAfter(){
System.out.println(22222222);
} }

 /*
* 以日志的形式取代sout,显示更详细的信息
* */
@Aspect
@Component
public class HttpAspect {
//import org.slf4j.Logger;
private final static Logger LOGGER = LoggerFactory.getLogger(HttpAspect.class);
//设置切点,简化代码
@Pointcut("execution(public * com.cenobitor.controller.GirlController.girlList(..))")
public void log(){
} //获取请求信息
@Before("log()")
public void doBefore(JoinPoint joinPoint){ 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("222222222222");
}
//打印返回结果
@AfterReturning(returning = "object",pointcut = "log()")
public void doAfterReturning(Object object){
LOGGER.info("response={}",object.toString());
}
}

三、单元测试

  • 基本代码:
 @RestController
public class CustomerController {
@Autowired
private CustomerService customerService; @GetMapping(value = "customer_findById")
public Customer findById(@RequestParam("id") Integer id){
return customerService.findById(id);
}
}vv
 @Service
@Transactional
public class CustomerServiceImpl implements CustomerService {
@Autowired
private CustomerRepository customerRepository; @Override
public Customer findById(Integer id) {
return customerRepository.findOne(id);
}
}
  • service层测试
 @RunWith(SpringRunner.class)
@SpringBootTest
public class CustomerServiceTest {
@Autowired
private CustomerService customerService; @Test
public void findByIdTest(){
Customer customer = customerService.findById(1);
Assert.assertEquals("张三",customer.getName()); }
}
  • API测试(即controller层测试):
 @RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class CustomerControllerTest {
@Autowired
private MockMvc mvc; @Test
public void findById() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/customer_findById?id=1"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string("abc"));//返回结果
}
}
  • 常用命令:

    • 执行打包并进行单元测试

mvn clean package

    • 执行打包并跳过所有单元测试

mvn clean package -Dmaven.test.skip=true

Spring Boot 表单验证、AOP统一处理请求日志、单元测试的更多相关文章

  1. spring boot 表单验证

    1 设置某个字段的取值范围 1.1 取值范围验证:@Min,@Max ① 实例类的属性添加注解@Min ② Controller中传入参数使用@Valid注解 1.2 不能为空验证:@NotNull ...

  2. Spring进行表单验证

    转自:https://www.tianmaying.com/tutorial/spring-form-validation 开发环境 IDE+Java环境(JDK 1.7或以上版本) Maven 3. ...

  3. SpringBoot学习笔记(七):SpringBoot使用AOP统一处理请求日志、SpringBoot定时任务@Scheduled、SpringBoot异步调用Async、自定义参数

    SpringBoot使用AOP统一处理请求日志 这里就提到了我们Spring当中的AOP,也就是面向切面编程,今天我们使用AOP去对我们的所有请求进行一个统一处理.首先在pom.xml中引入我们需要的 ...

  4. spring boot中表单验证的使用

    一.前言 为啥子要搞这个表单验证呢?答案简单而现实,举个栗子,你辛辛苦苦的写了一个录入个人信息的功能,比如年龄这个位置,用户就没看到一下子写了个性别男,一提交,直接报错了,是不是很尴尬呢, 作为一个测 ...

  5. Flask10 登录模块、表单框架、表单渲染、表单验证、bookie、请求之前钩子、g对象、编写装饰器

    from flask import Flask from flask import request from flask import render_template from flask_wtf i ...

  6. Spring MVC 表单验证

    1. 基于 JSR-303(一个数据验证的规范): import javax.validation.constraints.Min; import javax.validation.constrain ...

  7. Spring常用表单验证注解

    下面是主要的验证注解及说明: 注解 适用的数据类型 说明 @AssertFalse Boolean, boolean 验证注解的元素值是false @AssertTrue Boolean, boole ...

  8. spring boot -表单校验步骤 +@NotEmpty,@NotNull和@NotBlank的区别

    1.实体类属性上添加注解规则 如 public class User { @NotBlank private Integer id ; 2.在方法中添加注解@Valid和一个校验结果参数(Bindin ...

  9. Springboot中AOP统一处理请求日志

    完善上面的代码: 现在把输出信息由先前的system.out.println()方式改为由日志输出(日志输出的信息更全面) 现在在日志中输出http请求的内容 在日志中获取方法返回的内容

随机推荐

  1. flask之信号

    Flask框架中的信号基于blinker,其主要就是让开发者可是在flask请求过程中定制一些用户行为. pip3 install blinker 1. 内置信号 request_started = ...

  2. 带你走进php大马的结构模块编写之路

    本文原创作者:Laimooc 第一部分:前沿综述 本次我主要写了[文件的创建].[文件的删除].[文件的上传].[目录浏览].[命令执行]小模块,以及[组合的目录浏览和文件删除功能]的模块: 实验环境 ...

  3. Django中指定生成表名的方法

    在模型类中定义元类: class Meta: de_table = 'tableName' #指定表名

  4. Java并发编程实践读书笔记(4)任务取消和关闭

    任务的取消 中断传递原理 Java中没有抢占式中断,就是武力让线程直接中断. Java中的中断可以理解为就是一种简单的消息机制.某个线程可以向其他线程发送消息,告诉你“你应该中断了”.收到这条消息的线 ...

  5. 【BZOJ3217】ALOEXT 分块

    题目传送门:http://www.lydsy.com/JudgeOnline/problem.php?id=3217 分块过掉辣!!!!!!$O(n^{1.5}+q\times \sqrt{n})$的 ...

  6. Cygwin安装配置

    1.下载安装Cygwin   我们可以到Cygwin的官方网站下载Cygwin的安装程序,地址是: http://www.cygwin.com/ 或者直接使用下载连接来下载安装程序,下载连接是: ht ...

  7. Vue路由-命名视图实现经典布局

    Vue路由-命名视图实现经典布局 相关Html: <!DOCTYPE html> <html lang="en"> <head> <met ...

  8. 【Java并发编程】:并发新特性—障碍器CyclicBarrier

    CyclicBarrier(又叫障碍器)同样是Java5中加入的新特性,使用时需要导入Java.util.concurrent.CylicBarrier.它适用于这样一种情况:你希望创建一组任务,它们 ...

  9. Intellij-怎么避免import.*包,以及import包顺序问题

    Intellij版本 IntelliJ IDEA 2018.1.2 (Ultimate Edition) Build #IU-181.4668.68, built on April 24, 2018 ...

  10. 【字符串】Reverse Words in a String(两个栈)

    题目: Given an input string, reverse the string word by word. For example,Given s = "the sky is b ...