在項目中引用靜態資源文件或者進行ajax請求時我們有時候會使用 ${basePath} ,其實這就是一種獲取絕對路徑的方式:
那么在springboot項目中要怎么配置才能使用 basePaht呢?
第一步:自定義攔截器(實現 HandlerInterceptor )
代碼:
package com.slm.tools.project.config;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author: create by slm
* @version: v1.0
* @description: com.slm.tools.project.config
* @date:2019/4/9
*/
public class PathInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
String path = httpServletRequest.getContextPath();
String scheme = httpServletRequest.getScheme();
String serverName = httpServletRequest.getServerName();
int port = httpServletRequest.getServerPort();
String basePath = scheme + "://" + serverName + ":" + port + path;
httpServletRequest.setAttribute("basePath", basePath);
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
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
34
35
36
37
第二步:注冊第一步中自定義的攔截器
代碼:
package com.slm.tools.project.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* @author: create by slm
* @version: v1.0
* @description: com.slm.tools.project.config
* @date:2019/4/9
*/
@Configuration
public class PathInterceptorConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new PathInterceptor()).addPathPatterns("/**");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
到這配置就算完了,接下來到前端測試使用一下
第三步:測試
我這里使用ajax進行測試:
function encrypt() {
var txt =$("#txt").val();
$.ajax({
url:"${basePath}/md5/encrypt",
dataType:"json",
data:{
txt:txt
},
success:function (data) {
$("#16MD5").html(data.MD516);
$("#16MD5Upper").html(data.MD516Upper);
$("#32MD5").html(data.MD532);
$("#32MD5Upper").html(data.MD532Upper);
}
}
)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
打開頁面按F12鍵觀察:
可以看到我們已經通過${basePaht}獲取到了絕對路徑。
結束