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请求的内容 在日志中获取方法返回的内容
随机推荐
- 【学习笔记】dsu on tree
我也不知道为啥这要起这名,完完全全没看到并查集的影子啊…… 实际上原理就是一个树上的启发式合并. 特点是可以在$O(nlogn)$的时间复杂度内完成对无修改的子树的统计,复杂度优于莫队算法. 局限性也 ...
- sublime 把 tab 转成 4 个空格
Preferences -> Settings-User { "tab_size":4, "translate_tabs_to_spaces" ...
- webpack快速入门——CSS分离与图片路径处理
1.在终端安装extract-text-webpack-plugin 2.引入插件 const extractTextPlugin = require("extract-text-webpa ...
- 一个MySQL 5.7 分区表性能下降的案例分析
告知MySQL5.7.18的使用者分区表使用中存在的陷阱,避免在该版本上继续踩坑.同时通过对源码的讲解,升级MySQL5.7.18时分区表性能下降的根本原因,向MySQL源码爱好者展示分区表实现中锁的 ...
- pythonweb框架Flask学习笔记03-变量规则
#-*- coding:utf-8 -*- from flask import Flask app=Flask(__name__) @app.route('/post/<int:postid&g ...
- POJ 1047
#include <iostream> #define MAXN 100 using namespace std; char _m[MAXN]; int ans[MAXN]; int ma ...
- 学习微信小程序及知识占及v-if与v-show差别
注意点: 一.接口调用方式: getOpenid: function () { var that = this; return new Promise(function (resolve, rejec ...
- Python基础8:列表推导式(list)字典推导式(dict) 集合推导式(set)
推导式分为列表推导式(list),字典推导式(dict),集合推导式(set)三种 1.列表推导式也叫列表解析式.功能:是提供一种方便的列表创建方法,所以,列表解析式返回的是一个列表格式:用中括号括起 ...
- 【数组】Maximum Subarray
题目: Find the contiguous subarray within an array (containing at least one number) which has the larg ...
- WPF为ItemsControl设置ItemsPanelTemplate
1. 直接在XAML中以对象属性的方式 <ItemsControl x:Name="lstNew"> <ItemsControl.ItemsPanel> & ...