在 Spring MVC 中获取当前 URL 的最佳方法是什么? [英] What's the best way to get the current URL in Spring MVC?

查看:61
本文介绍了在 Spring MVC 中获取当前 URL 的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据客户端用于活动请求的 URL 创建 URL.有什么比使用当前的 HttpServletRequest 对象和它的 getParameter...() 方法来重建完整的 URL 包括(并且仅)它的 GET 参数更聪明.

I'd like to create URLs based on the URL used by the client for the active request. Is there anything smarter than taking the current HttpServletRequest object and it's getParameter...() methods to rebuilt the complete URL including (and only) it's GET parameters.

澄清:如果可能,我想退出使用 HttpServletRequest 对象.

Clarification: If possible I want to resign from using a HttpServletRequest object.

推荐答案

好吧,有两种方法可以更轻松地访问这些数据,但是该界面并没有提供通过一次调用获取整个 URL 的可能性.您必须手动构建它:

Well there are two methods to access this data easier, but the interface doesn't offer the possibility to get the whole URL with one call. You have to build it manually:

public static String makeUrl(HttpServletRequest request)
{
    return request.getRequestURL().toString() + "?" + request.getQueryString();
}

我不知道有什么方法可以使用任何 Spring MVC 工具来做到这一点.

I don't know about a way to do this with any Spring MVC facilities.

如果您想访问当前请求而不将其传递到任何地方,则必须在 web.xml 中添加一个侦听器:

If you want to access the current Request without passing it everywhere you will have to add a listener in the web.xml:

<listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

然后用这个来获取绑定到当前线程的请求:

And then use this to get the request bound to the current Thread:

((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest()

这篇关于在 Spring MVC 中获取当前 URL 的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆