我有两个表单,action
具有same-url
,以下表单位于页面http://www.domain.com/pre- foo-url
,即
<form:form commandName="some" class="form" action="/app/same-url">
<form:input path="title"/>
<input type="hidden" name="redirect" value="foo"/>
<button>OK</button>
</form:form>
另一种形式位于http://www.domain.com/bar/{id}
<form:form commandName="some" class="form" action="/app/same-url">
<form:input path="tile"/>
<input type="hidden" name="redirect" value="bar"/>
<button>OK</button>
</form:form>
我的 Controller 中有两种方法,一种用于决定重定向到
@RequestMapping(value = "/same-url", method = RequestMethod.POST)
public String handleRedirect(@RequestParam("redirect") String redirect) {
if (redirect.equals("foo")) {
return "redirect:/foo";
} else {
return "redirect:/bar/{id}"; // this {id} must get the value from http://www.domain.com/bar/{id}<-- Here
}
}
从 return "redirect:/bar/{id}";
获取 id 值的其他方法并转到 /bar/{id}
请求映射
@RequestMapping(value = "/bar/{id}", method = RequestMethod.GET)
public String handleBar(@PathVariable Integer id) {
// some logic here
return "go-any-where";
}
现在如何从 http://www.domain.com/bar/{id}
获取值并在将其重定向到 redirect:/bar/{id} 时进行设置}
,
最佳答案
我有一个适合您需求的解决方案,首先我必须指出您的需求,然后我会写下我的答案。
First:
-You need to get the
/{id}
fromhttp://www.domain.com/bar/{id}
, it means you want to get the value of last part of url.
您可以在页面http://www.domain.com/bar/{id}
上添加以下代码来获取该值
<c:set var="currentPage" value="${requestScope['javax.servlet.forward.request_uri']}"/> <!--This will give you the path to current page eg- http://www.domain.com/bar/360 -->
<c:set var="splitURI" value="${fn:split(currentPage, '/')}"/> <!--This will split the path of current page -->
<c:set var="lastValue" value="${splitURI[fn:length(splitURI)-1]}"/><!--This will give you the last value of url "360" in this case -->
<c:out value="${lastValue}"></c:out> <!--use this to make sure you are getting correct value(for testing only) -->
Scond:
-You have to pass value of
/{id}
which is got fromhttp://www.domain.com/bar/{id}
.
使用 as 形式传递此内容。
<form:form commandName="some" class="form" action="/app/same-url">
<form:input path="title"/>
<input type="hidden" name="redirect" value="bar"/>
<input type="hidden" name="path-var" value="${lastValue}"/>
<button>OK</button>
<form:form>
At Last:
-You want to be redirected to
redirect:/bar/{id}"
.
这可以使用下面的方法来完成。
@RequestMapping(value = "/add-category", method = RequestMethod.POST)
public String handleRedirect(@RequestParam("redirect") String redirect, @RequestParam("path-var") String pathVar) {
if (redirect.equals("foo")) {
return "redirect:/foo";
} else {
return "redirect:/bar/" + pathVar;
}
}
重要
This is not the Last/Best solution for the problem above.
这个问题可能还有其他/更好的解决方案。
Add this tag lib
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
, when using any jstl function just asfn:length()
.
希望这对您有用。
关于java - 如何使用 jSTL 从 url 获取一些值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33049869/