【问题标题】:How to find the base URL of the current webapp in Spring?如何在 Spring 中找到当前 webapp 的基本 URL?
【发布时间】:2011-10-12 11:28:44
【问题描述】:

我想从 Controller 中找到 Spring 中 webapp 的绝对 URL。我知道 JSTL c:url,但我需要来自控制器内部的这些信息。

@Controller
public class AuthorizeController {

    @Autowired
    private Authorizer auth;

    @RequestMapping("/auth")
    public String sendToAuthorization() {        
        String baseUrl = "http://localhost:8080/tasks/";
        return "redirect:" +  auth.getAuthorizationUrl(baseUrl);
    }

}

如您所见,baseUrl 是硬编码的,我可以通过 Spring 配置将其提供给 Authorizer 类,但我确信可以从 Controller 中的 Spring 获取此信息。我试图用谷歌搜索“spring mvc url”,但找不到解决这个问题的方法。

【问题讨论】:

    标签: java servlets spring-mvc


    【解决方案1】:

    这个答案很晚,但是如果您不想将 servlet 对象推送到方法签名中,Boris 的答案的一个变体是使用实用程序类/方法中的RequestContextHolder。这也将提供抽象回退逻辑的能力(例如,从属性文件中提取)。俗气的例子:

    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    if(null != requestAttributes && requestAttributes instanceof ServletRequestAttributes) {
      HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
      // build URL from request
    }
    else {
      // fallback logic if request won't work...
    }
    

    这假定您已将org.springframework.web.context.request.RequestContextListener 注册为web.xml 中的侦听器

    【讨论】:

      【解决方案2】:

      我认为只有在处理请求时才能获取 absolute url,因为您的服务器可能有许多 IP 地址和域名。

       @RequestMapping("/auth")
          public String sendToAuthorization(HttpServletRequest request) {        
          String baseUrl = String.format("%s://%s:%d/tasks/",request.getScheme(),  request.getServerName(), request.getServerPort());
      
      
              return "redirect:" +  auth.getAuthorizationUrl(baseUrl);
          }
      

      至于servlet,在web.xml中也可能有几个映射。

      similar question

      附:无论如何,在运行时解析 url 对我来说并不是一个好主意。

      【讨论】:

      • 我明白,它可能有 mod_jk、url 重写和 servlet 不会意识到这一点。还阅读了您链接的另一个问题,我认为我最好的选择是使用spring XML配置在bean中注入这个基本URL。谢谢。
      猜你喜欢
      • 2011-10-31
      • 2012-03-31
      • 2022-07-10
      • 2015-12-10
      • 1970-01-01
      • 2010-11-20
      • 1970-01-01
      相关资源
      最近更新 更多