引言
在springboot 1.x 版本的時候,如果要制定訪問規則,例如:*.action 這種格式,只需要在配置文件中進行如下配置即可:
server.servlet.path=*.action
但是,到了springboot2.x版本,使用過的兄弟們會發現,這個配置方式被劃了一橫,表示已經被廢棄了,那麼今天,就告訴大家,怎麼通過配置,達到配置規則這個目的。
解決方式
首先,要明確的是,web有三大組件,Linstener -> Fliter -> Servlet,其中,servlet用於:接受請求、處理請求、返回響應我們可以從這點入手。
在springboot的依賴中,找到 ServletRegistrationBean 這個類,隨即下載源碼,可以找到其中的一個方法。
/**
* Add URL mappings, as defined in the Servlet specification, for the servlet.
* @param urlMappings the mappings to add
* @see #setUrlMappings(Collection)
*/
public void addUrlMappings(String... urlMappings) {
Assert.notNull(urlMappings, "UrlMappings must not be null");
this.urlMappings.addAll(Arrays.asList(urlMappings));
}
由註釋不難看出,添加一個或者多個url映射,不難看出他的參數是可以是多個,那麼,我們通過改寫配置調用這個方法,或許可以達到我們的目的。
重寫配置
首先,新建一個java類,我這裏命名爲:Myconfig
package com.jackosn.config;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.DispatcherServlet;
@Configuration
public class MyConfig {
@Bean
public ServletRegistrationBean MyBean(){
ServletRegistrationBean bean = new ServletRegistrationBean();
bean.addUrlMappings("*.action","*.aaa");
return bean;
}
}
代碼比較簡單,大家看看就好啦。
講道理,這樣子就可以達到我們的目的,但是在啓動的時候呢,報錯了。
Servlet must not be null
轉念一想,可能需要把Servlet當成參數傳進去,所以,改寫配置類如下:
package com.jackosn.config;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.DispatcherServlet;
@Configuration
public class MyConfig {
@Bean
public ServletRegistrationBean MyBean(DispatcherServlet servlet){
ServletRegistrationBean bean = new ServletRegistrationBean(servlet);
bean.addUrlMappings("*.action","*.aaa");
return bean;
}
}
以上。
祝大家敲碼愉快~