小言_互联网的博客

Spring Boot学习笔记(五)Spring Boot 参数校验、自定义Filter、自定义Property

373人阅读  评论(0)

Spring Boot 参数校验、自定义Filter、自定义Property

上一章:Spring Boot对 Json 的支持

1、参数校验

参数校验在我们日常开发中非常常见,例如判断属性是否为空、长度是否符合要求等,在以往的开发模式中往往需要写一堆if else来处理这些逻辑,很繁琐、效率不高。

  • 解决方案:Spring Boot中使用@Valid + BindingResult(注解限定名称 + 限制条件/提示信息)

在原来实体类的属性前加:

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;
    }

}


对不同的属性,添加不同的校验内容

  • Spring Boot的参数校验其实是依赖于hibernate-validator来进行的

现在模拟对参数User进行参数校验,使用@Valid + BindingResult,校验后如果有错误将错误打印

  • WebContrller.java里加入代码如下:
    @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());
            }
        }
    }
  • 在WebControllerTest.java 中添加测试方法:
    @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() {

    }

}

  • 再新建一个WebConfiguration的类,将自定义的Filter加入过滤链:
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开发过程中,经常需要使用自定义的一些配置文件

  • 在web目录下的application.properties设置title和description两个值:
  • 在web文件下建立MyProperties.java
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;
    }

}

  • 在test文件夹下建立PropertiesTest.java测试文件:
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());
    }
}

转载:https://blog.csdn.net/Stephanie17395/article/details/97423084
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场