@RequestMapping(method = RequestMethod.POST)
public String post(HttpServletRequest request) {
return "redirect:http://www.x.appName.com/myPage";
}
假设用户在重定向之前已经有会话 我想在重定向之前编码新的url以维护用户会话 该怎么做?
答案 0 :(得分:6)
您可以将HttpServletResponse
作为参数传递,并使用encodeRedirectURL(..)
方法:
String url = "http://www.x.appName.com/myPage";
url = response.encodeRedirectURL(url);
return "redirect:" + url;
但首先要确保春天不会自动为你做这件事。
答案 1 :(得分:0)
Spring doc是这类问题的终极资源。此外,您可以从github下载正确版本的代码,并调试答案。至于问题,请查看http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/mvc.html#mvc-redirecting-redirect-prefix,或查看下面的RedirectView类的源代码(适用于春季4.1.0):
protected void appendQueryProperties(StringBuilder targetUrl, Map<String, Object> model, String encodingScheme)
throws UnsupportedEncodingException {
// Extract anchor fragment, if any.
String fragment = null;
int anchorIndex = targetUrl.indexOf("#");
if (anchorIndex > -1) {
fragment = targetUrl.substring(anchorIndex);
targetUrl.delete(anchorIndex, targetUrl.length());
}
// If there aren't already some parameters, we need a "?".
boolean first = (targetUrl.toString().indexOf('?') < 0);
for (Map.Entry<String, Object> entry : queryProperties(model).entrySet()) {
Object rawValue = entry.getValue();
Iterator<Object> valueIter;
if (rawValue != null && rawValue.getClass().isArray()) {
valueIter = Arrays.asList(ObjectUtils.toObjectArray(rawValue)).iterator();
}
else if (rawValue instanceof Collection) {
valueIter = ((Collection<Object>) rawValue).iterator();
}
else {
valueIter = Collections.singleton(rawValue).iterator();
}
while (valueIter.hasNext()) {
Object value = valueIter.next();
if (first) {
targetUrl.append('?');
first = false;
}
else {
targetUrl.append('&');
}
String encodedKey = urlEncode(entry.getKey(), encodingScheme);
String encodedValue = (value != null ? urlEncode(value.toString(), encodingScheme) : "");
targetUrl.append(encodedKey).append('=').append(encodedValue);
}
}
// Append anchor fragment, if any, to end of URL.
if (fragment != null) {
targetUrl.append(fragment);
}
}
简而言之,如果您知道将值放在何处,Spring会为您做到。
答案 2 :(得分:0)
UriComponentsBuilder的构建方法默认为“ false”,然后将触发编码:
===
content1a
===
content1b
===
content2a
===
content2b