一、背景
在非前后端分离的web应用开发过程中,在html中不可避免的需要请求项目地址去访问接口或者静态资源,但是开发环境、测试环境以及生产环境不同,地址也不同,避免频繁修改代码,可以通过自动获取访问地址通过拦截器的方式,对页面返回地址信息。
二、代码
1、配置拦截器
BaseInterceptor.java
import com.fchsoft.wjcwsso.entity.User;
import com.fchsoft.wjcwsso.util.JWTUtils;
import com.fchsoft.wjcwsso.util.RedisKey;
import com.fchsoft.wjcwsso.util.ThreadLocalUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author pxm
* @version 0.1
* @description 基础拦截器
* @date 2024/12/13
*/
public class BaseInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
request.setAttribute("base",getBasePath(request));
return true;
}
public static String getBasePath(HttpServletRequest request){
StringBuffer basePathBuffer = new StringBuffer();
basePathBuffer.append(request.getScheme()).append("://").append(request.getServerName())
.append(':').append(request.getServerPort())
.append(request.getContextPath()).append('/');
return basePathBuffer.toString();
}
}
2、
InterceptorConfig.java
import com.fchsoft.wjcwsso.filter.BaseInterceptor;
import com.fchsoft.wjcwsso.filter.JWTInterceptor;
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.WebMvcConfigurer;
/**
* @author pxm
* @version 0.1
* @description
* @date 2024/12/11
*/
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new BaseInterceptor())
.addPathPatterns("/**");
}
}