怎么在SpringBoot項(xiàng)目中定制一個(gè)攔截器

怎么在Spring Boot項(xiàng)目中定制一個(gè)攔截器?針對這個(gè)問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡單易行的方法。

為桐城等地區(qū)用戶提供了全套網(wǎng)頁設(shè)計(jì)制作服務(wù),及桐城網(wǎng)站建設(shè)行業(yè)解決方案。主營業(yè)務(wù)為成都網(wǎng)站設(shè)計(jì)、成都做網(wǎng)站、桐城網(wǎng)站設(shè)計(jì),以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠的服務(wù)。我們深信只要達(dá)到每一位用戶的要求,就會得到認(rèn)可,從而選擇與我們長期合作。這樣,我們也可以走得更遠(yuǎn)!

添加攔截器不僅是在WebConfiguration中定義bean,Spring Boot提供了基礎(chǔ)類WebMvcConfigurerAdapter,我們項(xiàng)目中的WebConfiguration類需要繼承這個(gè)類。

繼承WebMvcConfigurerAdapter;

為LocaleChangeInterceptor添加@Bean定義,這僅僅是定義了一個(gè)interceptor spring bean,但是Spring boot不會自動(dòng)將它加入到調(diào)用鏈中。

攔截器需要手動(dòng)加入調(diào)用鏈。

修改后完整的WebConfiguration代碼如下:

package com.test.bookpub;

import org.apache.catalina.filters.RemoteIpFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;

@Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter {
  @Bean  public RemoteIpFilter remoteIpFilter() {
    return new RemoteIpFilter();
  }

  @Bean  public LocaleChangeInterceptor localeChangeInterceptor() {
    return new LocaleChangeInterceptor();
  }
  @Override  public void addInterceptors(InterceptorRegistry registry {
    registry.addInterceptor(localeChangeInterceptor());
  }
}

使用mvn spring-boot:run運(yùn)行程序,然后通過httpie訪問http://localhost:8080/books?locale=foo,在終端看到如下錯(cuò)誤信息。

Servlet.service() for servlet [dispatcherServlet] in context with path [] 
threw exception [Request processing failed; nested exception is 
java.lang.UnsupportedOperationException: Cannot change HTTP accept 
header - use a different locale resolution strategy] with root cause

關(guān)于怎么在Spring Boot項(xiàng)目中定制一個(gè)攔截器問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關(guān)知識。

本文名稱:怎么在SpringBoot項(xiàng)目中定制一個(gè)攔截器
文章地址:http://bm7419.com/article32/igddsc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App開發(fā)動(dòng)態(tài)網(wǎng)站、品牌網(wǎng)站建設(shè)自適應(yīng)網(wǎng)站、網(wǎng)站策劃、建站公司

廣告

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

成都網(wǎng)站建設(shè)公司