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

查看:246
本文介绍了在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天全站免登陆