Spring Web的UrlPathHelper的主要方法

本文详细介绍了SpringWeb中处理HTTP请求时的路径解析方法,包括getLookupPathForRequest、getPathWithinServletMapping和getPathWithinApplication等核心函数的使用场景与实现原理。同时,针对SpringBoot结合Freemarker的模板引擎在开发阶段遇到的静态资源刷新问题,提出了两种优化方案,一种是在application.yml中直接指定静态资源位置,另一种是通过自定义环境配置,修改静态资源加载路径,以提高开发效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基于Spring Web开发的应用,下面这几个方法比较常用,标记一下

/**
 * Return the mapping lookup path for the given request, within the current
 * servlet mapping if applicable, else within the web application.
 * <p>Detects include request URL if called within a RequestDispatcher include.
 * @param request current HTTP request
 * @return the lookup path
 * @see #getPathWithinApplication
 * @see #getPathWithinServletMapping
 */
public String getLookupPathForRequest(HttpServletRequest request)
/**
 * Return the path within the servlet mapping for the given request,
 * i.e. the part of the request's URL beyond the part that called the servlet,
 * or "" if the whole URL has been used to identify the servlet.
 * <p>Detects include request URL if called within a RequestDispatcher include.
 * <p>E.g.: servlet mapping = "/*"; request URI = "/test/a" -> "/test/a".
 * <p>E.g.: servlet mapping = "/"; request URI = "/test/a" -> "/test/a".
 * <p>E.g.: servlet mapping = "/test/*"; request URI = "/test/a" -> "/a".
 * <p>E.g.: servlet mapping = "/test"; request URI = "/test" -> "".
 * <p>E.g.: servlet mapping = "/*.test"; request URI = "/a.test" -> "".
 * @param request current HTTP request
 * @return the path within the servlet mapping, or ""
 */
public String getPathWithinServletMapping(HttpServletRequest request)
/**
 * Return the path within the web application for the given request.
 * <p>Detects include request URL if called within a RequestDispatcher include.
 * @param request current HTTP request
 * @return the path within the web application
 */
public String getPathWithinApplication(HttpServletRequest request)

使用spring boot+Freemarker,模版名称后缀是.html,请求的路径中.html,可能包括静态资源和模版资源,spring boot会优先检查静态资源是否存在,如果存在,就不会再查询模版资源了,但spring boot中缺省的静态资源检查路径有5个,检查太多了,并且,由于静态资源缺省定在main/resources下,这里的资源必须经过编译发布部署,开发阶段,静态资源改了,刷新比较麻烦,此处直接更改静态资源到绝对路径:file:///media/dd,此种方式有两种:

第一种:

application.yml中

spring

  resources

    static-locations:

      - file:///

这种方式,是非常简单的,也比较高效,但如果访问的资源来自模版,则还要检查4次

第二种:

自定义一个环境配置,spring.static.location=${project.root}/xxx

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/**")
            .addResourceLocations(staticLocation)
            .setCachePeriod(0);
}

这种方式,只检查一个location,感到要省时一些,但多了一个自定义配置,并且解决了刷新问题,这个是关键

转载于:https://my.oschina.net/u/2266730/blog/800270

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值