Spring Boot 表单验证、AOP统一处理请求日志、单元测试
一、使用@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统一处理请求日志、单元测试的更多相关文章
- spring boot 表单验证
1 设置某个字段的取值范围 1.1 取值范围验证:@Min,@Max ① 实例类的属性添加注解@Min ② Controller中传入参数使用@Valid注解 1.2 不能为空验证:@NotNull ...
- Spring进行表单验证
转自:https://www.tianmaying.com/tutorial/spring-form-validation 开发环境 IDE+Java环境(JDK 1.7或以上版本) Maven 3. ...
- SpringBoot学习笔记(七):SpringBoot使用AOP统一处理请求日志、SpringBoot定时任务@Scheduled、SpringBoot异步调用Async、自定义参数
SpringBoot使用AOP统一处理请求日志 这里就提到了我们Spring当中的AOP,也就是面向切面编程,今天我们使用AOP去对我们的所有请求进行一个统一处理.首先在pom.xml中引入我们需要的 ...
- spring boot中表单验证的使用
一.前言 为啥子要搞这个表单验证呢?答案简单而现实,举个栗子,你辛辛苦苦的写了一个录入个人信息的功能,比如年龄这个位置,用户就没看到一下子写了个性别男,一提交,直接报错了,是不是很尴尬呢, 作为一个测 ...
- Flask10 登录模块、表单框架、表单渲染、表单验证、bookie、请求之前钩子、g对象、编写装饰器
from flask import Flask from flask import request from flask import render_template from flask_wtf i ...
- Spring MVC 表单验证
1. 基于 JSR-303(一个数据验证的规范): import javax.validation.constraints.Min; import javax.validation.constrain ...
- Spring常用表单验证注解
下面是主要的验证注解及说明: 注解 适用的数据类型 说明 @AssertFalse Boolean, boolean 验证注解的元素值是false @AssertTrue Boolean, boole ...
- spring boot -表单校验步骤 +@NotEmpty,@NotNull和@NotBlank的区别
1.实体类属性上添加注解规则 如 public class User { @NotBlank private Integer id ; 2.在方法中添加注解@Valid和一个校验结果参数(Bindin ...
- Springboot中AOP统一处理请求日志
完善上面的代码: 现在把输出信息由先前的system.out.println()方式改为由日志输出(日志输出的信息更全面) 现在在日志中输出http请求的内容 在日志中获取方法返回的内容
随机推荐
- 操作实践题 - HTML 列表综合应用
通过对列表的综合应用,编写如下效果网页: 解答: <html> <head> <title>操作实践题</title> <meta http-eq ...
- Redis的Pub/Sub机制存在的问题以及解决方案
Redis的Pub/Sub机制使用非常简单的方式实现了观察者模式,但是在使用过程中我们发现,它仅仅是实现了发布订阅机制,但是很多的场景没有考虑到.例如一下的几种场景: 1.数据可靠性无法保证 一个re ...
- Android中获取正在运行的服务-------ActivityManager.RunningServiceInfo的使用
关于PackageManager和ActivityManager的使用 ,自己也写了一些DEMO 了,基本上写的线路参考了Settings模块下的 应用程序,大家如果真正的有所兴趣,建议大家看看源码, ...
- debug 工具
git blame 查看某个文件的修改记录  二分查找确定 bug 来源 启动  输入 git bisect start,启动流程 输入 git bisect bad,标记当前是错误的 输入 gi ...
- 了解ORACLE培训OCA-OCP-OCM课程表
了解ORACLE培训OCA-OCP-OCM课程表考试号: OCA 1Z0-007$125 Oracle Database 10g:SQL Fundamentals 本课程培养学生必要的SQ ...
- subtext 安装PythonIDE -Anaconda
安装PythonIDE -Anaconda 打开subtext,通过快捷键 cmd+shift+P 打开 Package Control 来安装其他的插件了. 输入 install 然后你就能看见屏幕 ...
- C++基础知识 基类指针、虚函数、多态性、纯虚函数、虚析构
一.基类指针.派生类指针 父类指针可以new一个子类对象 二.虚函数 有没有一个解决方法,使我们只定义一个对象指针,就可以调用父类,以及各个子类的同名函数? 有解决方案,这个对象指针必须是一个父类类型 ...
- 【链表】Add Two Numbers
题目: You are given two linked lists representing two non-negative numbers. The digits are stored in r ...
- Map map=new HashMap()
Map是接口,hashMap是Map的一种实现.接口不能被实例化.Map map=new HashMap(); 就是将map实例化成一个hashMap.这样做的好处是调用者不需要知道map具体的实现, ...
- Android 开发服务类 04_ServletForPOSTMethod
ServletForPOSTMethod 业务类 package com.wangjialin.internet.servlet; import java.io.IOException; import ...