一、使用@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. jquery移动端一个按钮两个事件

    当一个按钮已经有一个事件,如点击,弹窗显示,若还要加个事件,可以用touchstart 如: var videoCover = $("#videoCover");//视频封面 $( ...

  2. Django + DRF + Elasticsearch 实现搜索功能

    django使用haystack来调用Elasticsearch搜索引擎  如何使用django来调用Elasticsearch实现全文的搜索 Haystack为Django提供了模块化的搜索.它的特 ...

  3. 浅谈对MVC的认识

    MVC是model(模型),view(视图),Controller(控制)的缩写. 模型层负责提供数据,和数据库相关的操作都交给模型层处理: 视图层提供交互的界面,其输出数据: 控制层负责接收各种请求 ...

  4. 前端html页面学习---html部分

    作为一个后台开发人员:本篇博客主要是关注前后台交互时需要掌握的html技术,不涉及css这一块的内容:主要是自学过程中的备忘 1:html常用标签标签的学习:不列出结束标签 <p>:段落: ...

  5. 用c语言实现三子棋

    1 game.c://实现三子棋的.c文件 #define _CRT_SECURE_NO_WARNINGS #include"game.h" void init_board(cha ...

  6. 第5章—构建Spring Web应用程序—关于spring中的validate注解后台校验的解析

    关于spring中的validate注解后台校验的解析 在后台开发过程中,对参数的校验成为开发环境不可缺少的一个环节.比如参数不能为null,email那么必须符合email的格式,如果手动进行if判 ...

  7. CentOS 配置使用 EPEL YUM 源

    EPEL(Extra Packages for Enterprise Linux)是一个由特别兴趣小组创建.维护并管理的,针对 红帽企业版 Linux(RHEL)及其衍生发行版(比如 CentOS. ...

  8. Python -- Windows编程 -- 注册表

    1.查询开机自启项 startUp.py import re import win32api, win32con def GetValues(fullname): #分割出基本项name[0] nam ...

  9. 恶性bug解决,Encoding 1252 data could not be found. Make sure you have correct international codeset assembly installed and enabled

    百度是没有的,google了下 这句话的意思是编码1252没找到,确保程序及是国际化格式 发生在我使用unity读取xlsx文件,在编辑器运行正常,但是发布出来不正常,报错 解决方案: 链接:http ...

  10. 解决Nginx 504 Gateway Time-out问题

    解决方案:在http里设置FastCGI相关参数,如: worker_processes 1; events { worker_connections 1024; } http { include m ...