springboot–自定义propertyeditor

     2022-04-15     325

关键词:

前言

PropertyEditor最初是属于Java Bean规范定义的,有意思的是,Spring也大规模的使用了PropertyEditors,以便实现以各种形式展现对象的属性;

举个例子,常见的用于解析Http请求参数,通常需要在展现层把原始Java对象解析成对人友好的参数,这时候就经常需要用到自定义PropertyEditor

org.springframework.beans.propertyeditors 包下,Spring已经内置了一些PropertyEditors,如解析Boolean, Currency, 和URL对象;然而这只是其中一部分常见的editors,在真实项目开发过程中,往往不满足我们的业务需求;

当默认的这些PropertyEditors不满足我们的需求的时候,我们需要自定义PropertyEditor,举个例子,假如我们要开发一个图书管理的应用,实现可以通过 ISBN去搜索图书,同样,图书详情里也需要展示ISBN信息,这里我们可以通过自定义PropertyEditor实现,详细开发过程如下:

创建自定义PropertyEditor

我们需要继承java.beans.PropertyEditorSupport类来实现自定义PropertyEditor,如下所示:
IsbnEditor.java

package com.howtodoinjava.app.editors;
 
import java.beans.PropertyEditorSupport;
import org.springframework.util.StringUtils;
import com.howtodoinjava.app.model.Isbn;
 
public class IsbnEditor extends PropertyEditorSupport {
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        if (StringUtils.hasText(text)) {
            setValue(new Isbn(text.trim()));
        } else {
            setValue(null);
        }
    }
 
    @Override
    public String getAsText() {
        Isbn isbn = (Isbn) getValue();
        if (isbn != null) {
            return isbn.getIsbn();
        } else {
            return "";
        }
    }
}

其中Isbn 类如下:
Isbn.java

package com.howtodoinjava.app.model;
 
public class Isbn {
    private String isbn;
 
    public Isbn(String isbn) {
        this.isbn = isbn;
    }
 
    public String getIsbn() {
        return isbn;
    }
     
    public String getDisplayValue() {
        return isbn;
    }
}

注册自定义PropertyEditor

下一步需要在Spring应用中注册我们刚刚编写的自定义PropertyEditor

注册很简单,只需要创建一个带@InitBinder注解的方法,其中该方法需要接收一个WebDataBinder类型的参数;

注意事项:
PropertyEditors并不是线程安全的,对于每一个请求,我们都需要new一个PropertyEditor对象,并用WebDataBinder去注册;

HomeController.java

@Controller
public class HomeController {
 
    //...
 
    @InitBinder
    public void initBinder(WebDataBinder binder) {
      binder.registerCustomEditor(Isbn.class, new IsbnEditor());
    }
}

通过自定义PropertyEditor接收参数并展现

当我们创建完自定义PropertyEditor并注册后,就可以在Controller里使用它了,
HomeController.java

@Controller
public class HomeController {
     
    private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());
 
    @RequestMapping(value = "/books/{isbn}", method = RequestMethod.GET)
    public String getBook(@PathVariable Isbn isbn, Map<String, Object> model)
    {
        LOGGER.info("You searched for book with ISBN :: " + isbn.getIsbn());
        model.put("isbn", isbn);
        return "index";
    }
     
    @InitBinder
    public void initBinder(WebDataBinder binder) {
      binder.registerCustomEditor(Isbn.class, new IsbnEditor());
    }
}

现在我们就可以直接通过@PathVariable Isbn isbn去接收isbn参数了,目前我们的IsbnEditor非常简单,但是我们可以在这个基础上添加很多校验规则,非常简便;
接下来,我们可以编写一个jsp文件,去展示信息:
index.jsp

<!DOCTYPE html>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html lang="en">
<body>
    <h2>ISBN You searched is :: ${ isbn.displayValue }</h2>
</body>
</html>

Demo测试

直接运行Spring Boot应用即可;
SpringBootWebApplication.java

package com.howtodoinjava.app.controller;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.support.SpringBootServletInitializer;
 
@SpringBootApplication
public class SpringBootWebApplication extends SpringBootServletInitializer {
     
    public static void main(String[] args) throws Exception {
        SpringApplication.run(SpringBootWebApplication.class, args);
    }
}

在浏览器中输入http://localhost:8080/books/978-3-16-148410-0 地址测试;
观察后台日志打印及前端展现:

2017-03-16 13:40:00 - You searched for book with ISBN :: 978-3-16-148410-0

技术分享图片

springboot初步认识---自定义filter

SpringBoot自动添加了OrderedCharacterEncodingFilter和HiddenHttpMethodFilter,直接自定义Filter。步骤:1.实现Filter接口,实现Filter方法2.添加@Configuration 注解,将自定义Filter加入过滤链自定义的filter类:@ConfigurationpublicclassWebConfigurati 查看详情

springboot自定义异常

生名一个异常类:比如用户登录授权异常类:/***自定义业务异常对象*/publicclassAuthorizationExceptionextendsRuntimeException{/***@FieldsserialVersionUID:TODO*/privatestaticfinallongserialVersionUID=1L;privateintcode;privateObjectdata 查看详情

springboot自定义错误页面

springboot自定义错误页面1.加入配置:@BeanpublicEmbeddedServletContainerCustomizercontainerCustomizer(){return(container->{ErrorPageerror401Page=newErrorPage(HttpStatus.UNAUTHORIZED,"/401.html");Error 查看详情

springboot自定义配置

在springboot中自定义配置项,一下只是其中的一种实现方式application.propertiesalipay.url=https://openapi.alipaydev.com/gateway.doalipay.format=JSONalipay.charset=UTF-8alipay.sign_type=RSA2第一种方式:自定义一个配置属性的实体类1@ConfigurationPr 查看详情

springboot返回自定义http状态码

参考技术A本文介绍SpringBoot返回自定义HTTP状态码的方法。 查看详情

springboot学习笔记自定义starter(代码片段)

springBoot学习笔记(四)自定义starter自定义starter自定义zdy-spring-boot-starter编写simpleBeanMyAutoConfiguration注解EnableRegisterServer配置标记类ConfigMarker创建/META-INF/spring.factories结果展示自定义starterstarter机制Sp 查看详情

springboot自定义异常

一、自定义异常GlobalExceptionHandlerpackagecom.ermao.exception;importcom.ermao.common.Result;importorg.springframework.web.bind.annotation.ControllerAdvice;importorg.springframework.web.bind.annotation.Excep 查看详情

springboot自定义异常处理

1.自定义异常类importlombok.Data;@DatapublicclassUserExceptionextendsRuntimeException{privateLongid;publicUserException(Longid){super("usernotexist");this.id=id;}publicUserException(Stringmessage,Longid){sup 查看详情

springboot——springboot四大核心之起步依赖(自定义starter)(代码片段)

...目录:1.开始2.聊聊起步依赖3.自定义starter3.1新建一个SpringBoot普通项目3.2在这个项目的pom文件添加依赖3.3自定义一个XXXProperties属性配置类3.4自定义一个Service3.5自定义一个XXXAutoConfig自动配置类3.6重点:spring.factories配置文... 查看详情

springboot实战:如何自定义servletfilter

1.前言有些时候我们需要在 SpringBootServletWeb 应用中声明一些自定义的 ServletFilter来处理一些逻辑。比如简单的权限系统、请求头过滤、防止 XSS 攻击等。本篇将讲解如何在 SpringBoot 应用中声明自定义Servle... 查看详情

springboot中自定义注解

1、首先我们了解一下如何自定义一个注解。   @Target(),下面是@Target的描述*Theconstantsofthisenumeratedtypeprovideasimpleclassificationofthe*syntacticlocationswhereannotationsmayappearinaJavaprogram.These*constant 查看详情

springboot之自定义查询query

  下面讲解下SpringBoot之自定义查询Query的实例SpringBoot之自定义查询Query有HQL语句查询(Hibernate),还可以采用sql语句本地查询BookDao类查询接口1packagecom.hik.dao;23importjava.util.List;45importorg.springframework.data.jpa.repository.J 查看详情

springboot核心-自定义starter(代码片段)

...1.4.自动配置类1.5.注册配置2.使用自定义的starter2.1.创建好SpringBoot项目2.2.引入我们自定义的starter3.查看引入的具体依赖4.工具类中使用5.启动测试为了加深对SpringBoot中自动装配的理解,我们自定义一个starter 查看详情

自定义springboot的运行动画---美女

nice 查看详情

springboot之加载自定义配置文件

SpringBoot默认加载配置文件名为:application.properties和application.yml,如果需要使用自定义的配置文件,则通过@PropertySource注解指定。 JavaBean:packageorg.springboot.model;importlombok.Data;importorg.springframework.boot.context.pr 查看详情

springboot自定义错误页面

springboot 默认是whitelabel错误页面java8写法:@BeanpublicEmbeddedServletContainerCustomizercontainerCustomizer(){return(container->{ErrorPageerror401Page=newErrorPage(HttpStatus.UNAUTHORIZED,"/401.html" 查看详情

springboot+自定义注解+自定义aop前置增强+自定义异常+自定义异常捕获

开篇想要在一些方法执行之前要进行一个逻辑判断,本来想使用拦截器来进行拦截但是后来还是说声算了.想到使用AOP的前置增强和自定义异常和自定义异常捕获可以解决这个问题,一次性用了这么多,就是想把之前比较模糊的东西... 查看详情

springboot的自定义配置

参考技术ASpringBoot免除了项目中大部分的手动配置,对一些特定情况,我们可以通过修改全局配置文件以适应具体生产环境,可以说,几乎所有的配置都可以写在application.properties文件中,SpringBoot会自动加载全局配置文件,从而... 查看详情