欧美一区二区三区老妇人-欧美做爰猛烈大尺度电-99久久夜色精品国产亚洲a-亚洲福利视频一区二区

SpringBoot如何自定義參數(shù)解析器

本篇內(nèi)容主要講解“SpringBoot如何自定義參數(shù)解析器”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“SpringBoot如何自定義參數(shù)解析器”吧!

我們提供的服務(wù)有:網(wǎng)站建設(shè)、做網(wǎng)站、微信公眾號(hào)開發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認(rèn)證、夏縣ssl等。為上千余家企事業(yè)單位解決了網(wǎng)站和推廣的問題。提供周到的售前咨詢和貼心的售后服務(wù),是有科學(xué)管理、有技術(shù)的夏縣網(wǎng)站制作公司

SpringMVC提供了各種姿勢的http參數(shù)解析支持,從前面的GET/POST參數(shù)解析篇也可以看到,加一個(gè)@RequsetParam注解就可以將方法參數(shù)與http參數(shù)綁定,看到這時(shí)自然就會(huì)好奇這是怎么做到的,我們能不能自己定義一種參數(shù)解析規(guī)則呢?

本文將介紹如何實(shí)現(xiàn)自定義的參數(shù)解析,并讓其生效

<!-- more -->

I. 環(huán)境搭建

首先得搭建一個(gè)web應(yīng)用才有可能繼續(xù)后續(xù)的測試,借助SpringBoot搭建一個(gè)web應(yīng)用屬于比較簡單的活;

創(chuàng)建一個(gè)maven項(xiàng)目,pom文件如下

<parent>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-parent</artifactid>
    <version>2.1.7</version>
    <relativepath /> <!-- lookup parent from update -->
</parent>

<properties>
    <project.build.sourceencoding>UTF-8</project.build.sourceencoding>
    <project.reporting.outputencoding>UTF-8</project.reporting.outputencoding>
    <spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-web</artifactid>
    </dependency>
</dependencies>

<build>
    <pluginmanagement>
        <plugins>
            <plugin>
                <groupid>org.springframework.boot</groupid>
                <artifactid>spring-boot-maven-plugin</artifactid>
            </plugin>
        </plugins>
    </pluginmanagement>
</build>
<repositories>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>

II. 自定義參數(shù)解析器

對(duì)于如何自定義參數(shù)解析器,一個(gè)較推薦的方法是,先搞清楚springmvc接收到一個(gè)請(qǐng)求之后完整的處理鏈路,然后再來看在什么地方,什么時(shí)機(jī),來插入自定義參數(shù)解析器,無論是從理解還是實(shí)現(xiàn)都會(huì)簡單很多。遺憾的是,本篇主要目標(biāo)放在的是使用角度,所以這里只會(huì)簡單的提一下參數(shù)解析的鏈路,具體的深入留待后續(xù)的源碼解析

1. 參數(shù)解析鏈路

http請(qǐng)求流程圖,來自 SpringBoot是如何解析HTTP參數(shù)的

SpringBoot如何自定義參數(shù)解析器

既然是參數(shù)解析,所以肯定是在方法調(diào)用之前就會(huì)被觸發(fā),在Spring中,負(fù)責(zé)將http參數(shù)與目標(biāo)方法參數(shù)進(jìn)行關(guān)聯(lián)的,主要是借助org.springframework.web.method.support.HandlerMethodArgumentResolver類來實(shí)現(xiàn)

/**
 * Iterate over registered {@link HandlerMethodArgumentResolver}s and invoke the one that supports it.
 * @throws IllegalStateException if no suitable {@link HandlerMethodArgumentResolver} is found.
 */
@Override
@Nullable
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
		NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {

	HandlerMethodArgumentResolver resolver = getArgumentResolver(parameter);
	if (resolver == null) {
		throw new IllegalArgumentException("Unknown parameter type [" + parameter.getParameterType().getName() + "]");
	}
	return resolver.resolveArgument(parameter, mavContainer, webRequest, binderFactory);
}

上面這段核心代碼來自org.springframework.web.method.support.HandlerMethodArgumentResolverComposite#resolveArgument,主要作用就是獲取一個(gè)合適的HandlerMethodArgumentResolver,實(shí)現(xiàn)將http參數(shù)(webRequest)映射到目標(biāo)方法的參數(shù)上(parameter)

所以說,實(shí)現(xiàn)自定義參數(shù)解析器的核心就是實(shí)現(xiàn)一個(gè)自己的HandlerMethodArgumentResolver

2. HandlerMethodArgumentResolver

實(shí)現(xiàn)一個(gè)自定義的參數(shù)解析器,首先得有個(gè)目標(biāo),我們?cè)趃et參數(shù)解析篇里面,當(dāng)時(shí)遇到了一個(gè)問題,當(dāng)傳參為數(shù)組時(shí),定義的方法參數(shù)需要為數(shù)組,而不能是List,否則無法正常解析;現(xiàn)在我們則希望能實(shí)現(xiàn)這樣一個(gè)參數(shù)解析,以支持上面的場景

為了實(shí)現(xiàn)上面這個(gè)小目標(biāo),我們可以如下操作

a. 自定義注解ListParam

定義這個(gè)注解,主要就是用于表明,帶有這個(gè)注解的參數(shù),希望可以使用我們自定義的參數(shù)解析器來解析;

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ListParam {
    /**
     * Alias for {@link #name}.
     */
    @AliasFor("name") String value() default "";

    /**
     * The name of the request parameter to bind to.
     *
     * @since 4.2
     */
    @AliasFor("value") String name() default "";
}
b. 參數(shù)解析器ListHandlerMethodArgumentResolver

接下來就是自定義的參數(shù)解析器了,需要實(shí)現(xiàn)接口HandlerMethodArgumentResolver

public class ListHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(ListParam.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
            NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        ListParam param = parameter.getParameterAnnotation(ListParam.class);
        if (param == null) {
            throw new IllegalArgumentException(
                    "Unknown parameter type [" + parameter.getParameterType().getName() + "]");
        }

        String name = "".equalsIgnoreCase(param.name()) ? param.value() : param.name();
        if ("".equalsIgnoreCase(name)) {
            name = parameter.getParameter().getName();
        }
        String ans = webRequest.getParameter(name);
        if (ans == null) {
            return null;
        }

        String[] cells = StringUtils.split(ans, ",");
        return Arrays.asList(cells);
    }
}

上面有兩個(gè)方法:

  • supportsParameter就是用來表明這個(gè)參數(shù)解析器適不適用

    • 實(shí)現(xiàn)也比較簡單,就是看參數(shù)上有沒有前面定義的ListParam注解

  • resolveArgument 這個(gè)方法就是實(shí)現(xiàn)將http參數(shù)粗轉(zhuǎn)換為目標(biāo)方法參數(shù)的具體邏輯

    • 上面主要是為了演示自定義參數(shù)解析器的過程,實(shí)現(xiàn)比較簡單,默認(rèn)只支持List<string>

3. 注冊(cè)

上面雖然實(shí)現(xiàn)了自定義的參數(shù)解析器,但是我們需要把它注冊(cè)到HandlerMethodArgumentResolver才能生效,一個(gè)簡單的方法如下

@SpringBootApplication
public class Application extends WebMvcConfigurationSupport {

    @Override
    protected void addArgumentResolvers(List<handlermethodargumentresolver> argumentResolvers) {
        argumentResolvers.add(new ListHandlerMethodArgumentResolver());
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }
}

4. 測試

為了驗(yàn)證我們的自定義參數(shù)解析器ok,我們開兩個(gè)對(duì)比的rest服務(wù)

@RestController
@RequestMapping(path = "get")
public class ParamGetRest {
    /**
     * 自定義參數(shù)解析器
     *
     * @param names
     * @param age
     * @return
     */
    @GetMapping(path = "self")
    public String selfParam(@ListParam(name = "names") List<string> names, Integer age) {
        return names + " | age=" + age;
    }

    @GetMapping(path = "self2")
    public String selfParam2(List<string> names, Integer age) {
        return names + " | age=" + age;
    }
}

演示demo如下,添加了ListParam注解的可以正常解析,沒有添加注解的會(huì)拋異常

SpringBoot如何自定義參數(shù)解析器

到此,相信大家對(duì)“SpringBoot如何自定義參數(shù)解析器”有了更深的了解,不妨來實(shí)際操作一番吧!這里是創(chuàng)新互聯(lián)網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

網(wǎng)站標(biāo)題:SpringBoot如何自定義參數(shù)解析器
文章鏈接:http://chinadenli.net/article8/giccip.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供營銷型網(wǎng)站建設(shè)、外貿(mào)建站、網(wǎng)站內(nèi)鏈、網(wǎng)站收錄、微信公眾號(hào)、自適應(yīng)網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都做網(wǎng)站