事情的起源:有人問我,說編寫了一個/hello訪問路徑,但是吧,不管是輸入/hello還是/hello.html,還是/hello.xxx都能進行訪問。當時我還以為他對代碼進行處理了,后來發(fā)現(xiàn)不是,后來發(fā)現(xiàn)這是Spring Boot路由規(guī)則。好了,有廢話了下,那么看看我們解決上面這個導致的問題。
構建web應用程序時,并不是所有的URL請求都遵循默認的規(guī)則。有時,我們希望RESTful URL匹配的時候包含定界符“.”,這種情況在Spring中可以稱之為“定界符定義的格式”;有時,我們希望識別斜杠的存在。Spring提供了接口供開發(fā)人員按照需求定制。
核心的開發(fā)步驟就是兩步:
(1)啟動類 extends WebMvcConfigurationSupport
(2)重寫configurePathMatch方法;
具體實現(xiàn)代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
package com.kfit; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; /** * * @author Angel --守護天使 * @version v.0.1 * @date 2016年7月29日下午7:06:11 */ @SpringBootApplication public class ApiCoreApp extends WebMvcConfigurationSupport{ /** * 1、 extends WebMvcConfigurationSupport * 2、重寫下面方法; * setUseSuffixPatternMatch : 設置是否是后綴模式匹配,如“/user”是否匹配/user.*,默認真即匹配; * setUseTrailingSlashMatch : 設置是否自動后綴路徑模式匹配,如“/user”是否匹配“/user/”,默認真即匹配; */ @Override publicvoid configurePathMatch(PathMatchConfigurer configurer) { configurer.setUseSuffixPatternMatch( false ) .setUseTrailingSlashMatch( true ); } publicstaticvoid main(String[] args) { SpringApplication.run(ApiCoreApp. class , args); } } |
其中訪問代碼:
1
2
3
4
|
@RequestMapping ( "/user" ) public String hello(){ return "/user" ; } |
以上代碼有兩句核心的代碼:
setUseSuffixPatternMatch(boolean useSuffixPatternMatch):
設置是否是后綴模式匹配,如“/user”是否匹配/user.*,默認真即匹配;
當此參數(shù)設置為true的時候,那么/user.html,/user.aa,/user.*都能是正常訪問的。
當此參數(shù)設置為false的時候,那么只能訪問/user或者/user/( 這個前提是setUseTrailingSlashMatch 設置為true了)。
setUseTrailingSlashMatch (boolean useSuffixPatternMatch):
設置是否自動后綴路徑模式匹配,如“/user”是否匹配“/user/”,默認真即匹配;
當此參數(shù)設置為true的會后,那么地址/user,/user/都能正常訪問。
當此參數(shù)設置為false的時候,那么就只能訪問/user了。
當以上兩個參數(shù)都設置為true的時候,那么路徑/user或者/user.aa,/user.*,/user/都是能正常訪問的,但是類似/user.html/ 是無法訪問的。
當都設置為false的時候,那么就只能訪問/user路徑了。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://412887952-qq-com.iteye.com/blog/2315107