58

springboot入门09 – 实现伪静态

 4 years ago
source link: https://www.zhyea.com/2020/03/08/springboot-basic-09-pseudo-static.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

最近想了下springboot前端路径的伪静态实现。

通过百度最容易找到的方案是使用 urlrewritefilter 这个依赖。不过一想到要为这么一件事情就添加一个依赖,还要再添加一个配置文件,还要挨个写一遍所有的路径映射就觉得头疼,所以pass。

跟踪了一下springboot WEB请求处理的过程,找到了一个关键类: UrlPathHelper 。在获取Handler之前,由这个类负责解析请求路径。正好可以在 WebMvcConfigurer 中配置 UrlPathHelper 类的实例,这就给了我们动些手脚的空间。

更贴心的是,springboot获取请求路径的第一选择不是调用 HttpServletRequest . getRequestURI ( ) 方法或者 HttpServletRequest . getServletPath ( ) 方法,而是从 HttpServletRequest attribute 中获取,这样能省下不少力气。

来看下实现方式。

1. 实现伪静态路径解析类

伪静态路径解析类是 UrlPathHelper 类的一个子类,通过重写 getRequestUri ( ) 方法实现了伪静态路径的处理。

代码如下:

public class PseudoStaticPathHelper extends UrlPathHelper {
 
    private static final String SUFFIX = ".html";
 
    @Override
    public String getRequestUri(HttpServletRequest request) {
        String uri = request.getRequestURI();
        if (!uri.endsWith(SUFFIX)) {
            return super.getRequestUri(request);
        }
        
        String path = (String) request.getAttribute(INCLUDE_REQUEST_URI_ATTRIBUTE);
        if (null == path) {
            int idx = uri.indexOf(SUFFIX);
            uri = uri.substring(0, idx);
            request.setAttribute(INCLUDE_REQUEST_URI_ATTRIBUTE, uri);
            request.setAttribute(INCLUDE_SERVLET_PATH_ATTRIBUTE, uri);
        }
 
        return super.getRequestUri(request);
    }
    
}

代码中的核心部分是下面两句:

request.setAttribute(INCLUDE_REQUEST_URI_ATTRIBUTE, uri);
request.setAttribute(INCLUDE_SERVLET_PATH_ATTRIBUTE, uri);

在后面处理中,springboot会优先从 Attribute 中获取请求路径。

2. 添加 WebMvcConfigurer 配置类

然后需要在 WebMvcConfigurer 中配置 PseudoStaticPathHelper 实例。

实现方式如下:

@Configuration
public class WebConfig implements WebMvcConfigurer {
 
    private UrlPathHelper urlPathHelper = new PseudoStaticPathHelper();
 
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.setUrlPathHelper(urlPathHelper);
    }
}

然后——这样就可以了。

不写示例代码了。在 Calf 这个项目中有类似的用法,有需要就看看。

End!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK