Html JSP 中的 Spring MVC 请求 URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6970115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring MVC Request URLs in JSP
提问by Snowy Coder Girl
I am writing a web application using Spring MVC. I am using annotations for the controllers, etc. Everything is working fine, except when it comes to actual links in the application (form actions, <a>
tags, etc.) Current, I have this (obviously abbreviated):
我正在使用 Spring MVC 编写一个 Web 应用程序。我正在为控制器等使用注释。一切正常,除了应用程序中的实际链接(表单操作、<a>
标签等)。当前,我有这个(显然是缩写的):
//In the controller
@RequestMapping(value="/admin/listPeople", method=RequestMethod.GET)
//In the JSP
<a href="/admin/listPeople">Go to People List</a>
When I directly enter the URL like "http://localhost:8080/MyApp/admin/listPeople", the page loads correctly. However, the link above does not work. It looses the application name "MyApp".
当我直接输入像“http://localhost:8080/MyApp/admin/listPeople”这样的 URL 时,页面加载正确。但是,上面的链接不起作用。它失去了应用程序名称“MyApp”。
Does anyone know if there is a way to configure Spring to throw on the application name on there?
有谁知道是否有办法配置 Spring 以在那里抛出应用程序名称?
Let me know if you need to see any of my Spring configuration. I am using the standard dispatcher servlet with a view resolver, etc.
如果您需要查看我的任何 Spring 配置,请告诉我。我正在使用带有视图解析器等的标准调度程序 servlet。
回答by craftsman
You need to prepend context path to your links.
您需要为链接添加上下文路径。
// somewhere on the top of your JSP
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
...
<a href="${contextPath}/admin/listPeople">Go to People List</a>
回答by Jason Gritman
The c:url
tag will append the context path to your URL. For example:
该c:url
标记会将上下文路径附加到您的 URL。例如:
<c:url value="/admin/listPeople"/>
Alternately, I prefer to use relative URLs as much as possible in my Spring MVC apps as well. So if the page is at /MyApp/index
, the link <a href="admin/listPeople">
will take me to the listPeople
page.
或者,我更喜欢在我的 Spring MVC 应用程序中尽可能多地使用相对 URL。因此,如果页面位于/MyApp/index
,则链接<a href="admin/listPeople">
会将我带到该listPeople
页面。
This also works if you are deeper in the URL hierarchy. You can use the ..
to traverse back up a level. So on the page at/MyApp/admin/people/aPerson
, using <a href="../listPeople">
will like back to the list page
如果您在 URL 层次结构中更深入,这也适用。您可以使用..
来返回一个级别。所以在页面上/MyApp/admin/people/aPerson
,使用<a href="../listPeople">
会喜欢回到列表页面
回答by sinuhepop
I prefer to use BASE tag:
我更喜欢使用 BASE 标签:
<base href="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/" />
Then, all your links can be like:
然后,您的所有链接都可以是:
<a href="admin/listPeople">Go to People List</a>
回答by Chris Eccles
As i have just been trying to find the answer to this question and this is the first google result.
因为我刚刚试图找到这个问题的答案,这是第一个谷歌结果。
This can be done now using the MvcUriComponentsBuilder
现在可以使用 MvcUriComponentsBuilder 来完成
This is part of the 4.0 version of Spring MVC
这是 Spring MVC 4.0 版本的一部分
The method needed is fromMappingName
需要的方法是 fromMappingName
From the documentation :
从文档:
Create a URL from the name of a Spring MVC controller method's request mapping. The configured HandlerMethodMappingNamingStrategy determines the names of controller method request mappings at startup. By default all mappings are assigned a name based on the capital letters of the class name, followed by "#" as separator, and then the method name. For example "PC#getPerson" for a class named PersonController with method getPerson. In case the naming convention does not produce unique results, an explicit name may be assigned through the name attribute of the @RequestMapping annotation.
This is aimed primarily for use in view rendering technologies and EL expressions. The Spring URL tag library registers this method as a function called "mvcUrl".
For example, given this controller:
根据 Spring MVC 控制器方法的请求映射的名称创建 URL。配置的 HandlerMethodMappingNamingStrategy 在启动时确定控制器方法请求映射的名称。默认情况下,所有映射都根据类名的大写字母分配一个名称,后跟“#”作为分隔符,然后是方法名。例如,“PC#getPerson”用于名为 PersonController 的类,方法为 getPerson。如果命名约定没有产生唯一的结果,可以通过 @RequestMapping 注释的 name 属性分配一个显式名称。
这主要用于视图渲染技术和 EL 表达式。Spring URL 标记库将此方法注册为名为“mvcUrl”的函数。
例如,给定这个控制器:
@RequestMapping("/people")
class PersonController {
@RequestMapping("/{id}")
public HttpEntity getPerson(@PathVariable String id) { ... }
}
A JSP can prepare a URL to the controller method as follows:
JSP 可以为控制器方法准备一个 URL,如下所示:
<%@ taglib uri="http://www.springframework.org/tags" prefix="s" %>
<a href="${s:mvcUrl('PC#getPerson').arg(0,"123").build()}">Get Person</a>
回答by dontsayinever.gaveyounothin
You could use a servletRelativeAction. I'm not sure what versions this is available in (I'm using 4.0.x currently) and I haven't seen much documentation on this, but if you look at the code backing the spring form you can probably guess. Just make sure the path you pass it starts with a "/".
您可以使用 servletRelativeAction。我不确定它在哪些版本中可用(我目前使用的是 4.0.x)并且我还没有看到太多关于此的文档,但是如果您查看支持 spring 表单的代码,您可能会猜到。只需确保您传递的路径以“/”开头。
Example:
例子:
<form:form class="form-horizontal" name="form" servletRelativeAction="/j_spring_security_check" method="POST">
See org.springframework.web.servlet.tags.form.FormTag:
参见 org.springframework.web.servlet.tags.form.FormTag:
protected String resolveAction() throws JspException {
String action = getAction();
String servletRelativeAction = getServletRelativeAction();
if (StringUtils.hasText(action)) {
action = getDisplayString(evaluate(ACTION_ATTRIBUTE, action));
return processAction(action);
}
else if (StringUtils.hasText(servletRelativeAction)) {
String pathToServlet = getRequestContext().getPathToServlet();
if (servletRelativeAction.startsWith("/") && !servletRelativeAction.startsWith(getRequestContext().getContextPath())) {
servletRelativeAction = pathToServlet + servletRelativeAction;
}
servletRelativeAction = getDisplayString(evaluate(ACTION_ATTRIBUTE, servletRelativeAction));
return processAction(servletRelativeAction);
}
else {
String requestUri = getRequestContext().getRequestUri();
ServletResponse response = this.pageContext.getResponse();
if (response instanceof HttpServletResponse) {
requestUri = ((HttpServletResponse) response).encodeURL(requestUri);
String queryString = getRequestContext().getQueryString();
if (StringUtils.hasText(queryString)) {
requestUri += "?" + HtmlUtils.htmlEscape(queryString);
}
}
if (StringUtils.hasText(requestUri)) {
return processAction(requestUri);
}
else {
throw new IllegalArgumentException("Attribute 'action' is required. " +
"Attempted to resolve against current request URI but request URI was null.");
}
}
}
回答by Kevin
I usually configure tomcat to use context root of "/" or deploy the war as ROOT.war. Either way the war name does not become part of the URL.
我通常将tomcat配置为使用“/”的上下文根或将war部署为ROOT.war。无论哪种方式,War名称都不会成为 URL 的一部分。
回答by Scaramouche
Since it's been some years I thought I'd chip in for others looking for this. If you are using annotations and have a controller action like this for instance:
因为已经有几年了,我想我会为其他人寻找这个。例如,如果您正在使用注释并具有这样的控制器操作:
@RequestMapping("/new") //<--- relative url
public ModelAndView newConsultant() {
ModelAndView mv = new ModelAndView("new_consultant");
try {
List<Consultant> list = ConsultantDAO.getConsultants();
mv.addObject("consultants", list);
} catch (Exception e) {
e.printStackTrace();
}
return mv;
}
in your .jsp (view) you add this directive
在您的 .jsp(视图)中添加此指令
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
and simply use
并简单地使用
<spring:url value="/new" var="url" htmlEscape="true"/>
<a href="${url}">New consultant</a>
where
在哪里
value
's value should match @RequestMapping
's argument in the controller action and
value
的值应与@RequestMapping
控制器操作中的参数匹配,并且
var's
value is the name of the variable you use for href
var's
value 是您使用的变量的名称 href
HIH
HIH