Java 如何在Velocity模板中访问会话或请求对象

Java 如何在Velocity模板中访问会话或请求对象,java,spring-mvc,velocity,Java,Spring Mvc,Velocity,我试图在某个velocity模板中访问HttpServletRequest,但从未成功。 我已经尝试过以下语法风格 当前URL:$req.get(“属性”).get(“当前URL”)) 结果>当前URL:$req.get(“属性”).get(“当前URL”)) 当前URL:$request.get(“属性”).get(“当前URL”)) 结果>当前URL:$request.get(“属性”).get(“当前URL”)) 当前URL:$request.get(“属性”).get(“当前URL”))

我试图在某个velocity模板中访问HttpServletRequest,但从未成功。 我已经尝试过以下语法风格

当前URL:$req.get(“属性”).get(“当前URL”)) 结果>当前URL:$req.get(“属性”).get(“当前URL”))

当前URL:$request.get(“属性”).get(“当前URL”)) 结果>当前URL:$request.get(“属性”).get(“当前URL”))

当前URL:$request.get(“属性”).get(“当前URL”)) 结果>当前URL:$request.get(“属性”).get(“当前URL”))

当前URL:${request.get(“属性”).get(“当前URL”)} 结果>当前URL:${request.get(“属性”).get(“当前URL”)}

注意:Web.xml看起来像


appServlet
org.springframework.web.servlet.DispatcherServlet
上下文配置位置
/WEB-INF/spring/appServlet/servlet-context.xml
1.
appServlet
/*
速度
org.apache.velocity.tools.view.servlet.VelocityViewServlet
org.apache.velocity.toolbox
/WEB-INF/toolbox.xml
org.apache.velocity.properties
/WEB-INF/velocity.properties
速度
*.vm

默认情况下,您将无法访问Velocity模板中的
HttpServletRequest
;您只能访问已放置在
上下文中的对象。因此,在backing Java类中,将您想要的信息添加到conext中:

context.put("url", request.getAttribute("CURRENT_URL"));

然后在Velocity模板中,您可以简单地引用
$url

对于VelocityTools,正确的引用是$request和$response,而不是$req和$res

方法名称为getAttribute,而不是get。因此,您可以:

$request.getAttribute('foo')

或者只是$request.foo


但不是$request.get('foo')

您需要根据会话滚动自己的类才能正确执行此操作

我立即遇到了这个问题,现在要创建一个会话类,我将通过values属性作为HashMaps列表来访问它

然后,您所需要做的就是在使用之前为velocity的上下文赋值一次

context.put("session", MySessionClass.values));

要获取特定参数,请执行以下操作:

$!request.getParameter('parameterName')
要获取整个查询字符串,请执行以下操作:

$!request.getQueryString()
试试这个

$request.getSession().getAttribute('userId')
$request.getSession().getAttribute('userId')