Spring MVC - 重定向后保留请求参数 [英] Spring MVC - keep request parameters after redirect
问题描述
我有一种情况,我的前端开发人员想要为每个链接添加几个参数。他需要那些作为链接指向的视图中的参数。
I have a situation here where my frontend developer wants to add several parameters to every link. He needs those as parameters in the view where the link points to.
每个 @Controller
方法只返回字符串。这由标准的viewresolver支持,使用所述String作为viewname:
Each @Controller
method will return Strings only. This is backed by a standard viewresolver using said String as viewname:
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
每当Controller返回重定向时:
但是,来自原始请求的请求参数被删除,他无法在.jsp
Whenever the Controller returns a redirect:
however, the request parameters from the original request are dropped and he can not access them in the .jsp
是否有任何简洁的方法来确保即使在 redirect:
'ing,url参数出现在被重定向到的视图中?
Is there any neat way to ensure that even after redirect:
'ing, the url parameters are present in the view which was redirected to?
推荐答案
由于Bozho建议的解决方案对我的需求不太满意,我写了一个过滤器,它完全符合我的要求。不确定在将来的情况下是否会出现任何问题,但在此之前,请随意使用我的实施:
Since the solutions suggested by Bozho where not quite satisfactory for my needs, I wrote a filter which does exactly what I want. Not sure if any problems might occur in future cases but until then, feel free to use my implementation:
/**
*
* @author Lennart Koester (University of Innsbruck, 2012)
*/
@Service
public class RedirectFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
String queryString = ((HttpServletRequest) request).getQueryString();
if (queryString != null) {
RedirectAwareResponseWrapper res = new RedirectAwareResponseWrapper((HttpServletResponse) response);
chain.doFilter(request, res);
if (res.isRedirected()) {
((HttpServletResponse) response).sendRedirect(res.getLocation() + "?" + queryString);
}
} else {
chain.doFilter(request, response);
}
}
@Override
public void destroy() {
}
class RedirectAwareResponseWrapper extends HttpServletResponseWrapper {
private boolean redirected = false;
private String location;
public RedirectAwareResponseWrapper(HttpServletResponse response) {
super(response);
}
@Override
public void sendRedirect(String location) throws IOException {
redirected = true;
this.location = location;
//IMPORTANT: don't call super() here
}
public boolean isRedirected() {
return redirected;
}
public String getLocation() {
return location;
}
}
}
这篇关于Spring MVC - 重定向后保留请求参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!