Reputation: 33605
greetings all I have a post method in a controller, which redirects to a new page I a way such like:
@RequestMapping(method = RequestMethod.POST)
public String post(HttpServletRequest request) {
return "redirect:http://www.x.appName.com/myPage";
}
suppose that the user already has a session before the redirection and I want to encode the new url before redirection to maintain the user session how to do so ?
Upvotes: 5
Views: 11487
Reputation: 514
UriComponentsBuilder's build method defaults to "false" which will then trigger the encoding:
UriComponentsBuilder.fromHttpUrl(url).build().toString()
Upvotes: 1
Reputation: 9
Spring doc is the ultimate resource for questions like this. Additionally you could download code of the right version from github, and debug for an answer. As for the question, check here http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/mvc.html#mvc-redirecting-redirect-prefix, or check the source code of class RedirectView below(applicable to spring 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);
}
}
In short, Spring does it for you if you know where to put the values.
Upvotes: 0
Reputation: 597096
You can pass the HttpServletResponse
as parameter, and use the encodeRedirectURL(..)
method:
String url = "http://www.x.appName.com/myPage";
url = response.encodeRedirectURL(url);
return "redirect:" + url;
But first make sure spring does not do this for you automatically.
Upvotes: 7