Spring MVC - 重定向后保留请求参数

时间:2012-03-13 14:38:08

标签: java spring redirect spring-mvc request

我有一种情况,我的前端开发人员想要为每个链接添加几个参数。他需要那些作为链接指向的视图中的参数。

每个@Controller方法仅返回字符串。这由使用所述String作为viewname的标准viewresolver支持:

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
        p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />

每当Controller返回redirect:时,原始请求中的请求参数将被删除,并且他无法在.jsp中访问它们

是否有任何简洁的方法可以确保即使在redirect:之后,url参数也会出现在重定向到的视图中?

2 个答案:

答案 0 :(得分:3)

您需要一个闪光范围。它已经从3.1.RC1春季开始实施 - see the request

答案 1 :(得分:2)

由于Bozho建议的解决方案对我的需求不太满意,我写了一个过滤器,它完全符合我的要求。不确定在将来的情况下是否会出现任何问题,但在此之前,请随意使用我的实现:

/**
*
* @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;
    }

}
}