Spring Boot 参数校验、自定义Filter、自定义Property
1、参数校验
参数校验在我们日常开发中非常常见,例如判断属性是否为空、长度是否符合要求等,在以往的开发模式中往往需要写一堆if else来处理这些逻辑,很繁琐、效率不高。
在原来实体类的属性前加:
public class User {
@NotEmpty(message = "姓名不能为空")
private String name;
@Max(value = 100, message = "年龄不能大于100岁")
@Min(value = 18, message = "必须年满18岁!")
private int age;
@NotEmpty(message = "密码不能为空")
@Length(min = 6, message = "密码长度不能小于6位")
private String pass;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
}
对不同的属性,添加不同的校验内容
现在模拟对参数User进行参数校验,使用@Valid + BindingResult,校验后如果有错误将错误打印
@RequestMapping("/saveUser")
public void saveUser(@Valid User user, BindingResult result) {
System.out.println("user: " + user);
if (result.hasErrors()) {
List<ObjectError> errorList = result.getAllErrors();
for (ObjectError error : errorList) {
System.out.println(error.getCode() + "-" + error.getDefaultMessage());
}
}
}
@Test
public void saveUsers() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post("/saveUser")
.param("name", "")
.param("age", "666")
.param("pass", "test"));
}
运行结果:
结果显示均已经触发了校验规则,返回了错误信息,在实际使用过程中可以对错误信息进行包装,最后返回到前端进行展示。
2、自定义Filter
- Filters 常用于记录请求日志、排除有 XSS 威胁的字符、执行权限验证等。
- Spring Boot 自动添加了 OrderedCharacterEncodingFilter 和
HiddenHttpMethodFilter,并且可以⾃定义 Filter。 - 实现FIlter接口,实现Filter方法,添加@Configuration注解,将自定义的Filter加入过滤链
-
在web目录下建立MyFilter类,实现Filter接口
package wen.demo07232.web;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
//自定义内容
System.out.println("this is my Filter, url: " + request.getRequestURI());
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
package wen.demo07232.web;
import org.apache.catalina.filters.RemoteIpFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class WebConfiguration {
@Bean
public RemoteIpFilter remoteIpFilter() {
return new RemoteIpFilter();
}
@Bean
public FilterRegistrationBean testFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new MyFilter());
registration.addUrlPatterns("/*");
registration.addInitParameter("paraName", "paramValue");
registration.setName("MyFilter");
registration.setOrder(1);
return registration;
}
}
添加完后启动项目,访问之前设置好的任意Url,都会看到控制台打印如下信息:
this is my Filter, url: /
3、自定义Property
在web开发过程中,经常需要使用自定义的一些配置文件
package wen.demo07232.web;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class MyProperties {
@Value("${wen.demo07232.title}")
private String title;
@Value("${wen.demo07232.description}")
private String description;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import wen.demo07232.Application;
import wen.demo07232.web.MyProperties;
import javax.annotation.Resource;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class PropertiesTest {
@Resource
private MyProperties properties;
@Test
public void testProperties() throws Exception {
System.out.println("title:" + properties.getTitle());
System.out.println("description:" + properties.getDescription());
}
}
- 值得一提的是:@SpringBootTest(classes = Application.class)中的(classes = Application.class)一定要加,然在IDEA2019版下会报“SpringBoot Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration”错误:解决方案
- 紧接着启动测试方法,我发现IDEA出现了中文乱码问题:解决方案
- 运行结果:
下一章:Spring Data JPA:分类查询、自定义查询、联表(多表查询)
转载:https://blog.csdn.net/Stephanie17395/article/details/97423084
查看评论