转发到我收到请求的同一个JSP页面(没有无限循环)?

时间:2016-10-29 20:45:13

标签: java jsp servlets java-ee-6

我有一个页面ProductsIndexController,您猜对了,我列出了产品。当客户端请求此页面时,我希望它映射到的{servlet - productListing.jsp - 从数据库中提取一些数据并将其传递回javax.servlet.ServletException: AS-WEB-CORE-00089

我的问题是,因为(我假设)我将请求转发到servlet映射到的同一页面,它导致无限重定向和此错误<% ArrayList<Product> products = (ArrayList<Product>)request.getAttribute("products"); %> <!-- Display data by looping over products -->

有解决方法吗?作为一个快速解决方案,我现在只是直接从JSP页面调用模型方法,但我宁愿不这样做。

productListing.jsp(因为我喜欢它)

@WebServlet({ "/ProductIndexController", "/productListing.jsp" })
public class ProductIndexController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {       
        try {
            ArrayList<Product> products = Product.all();
            request.setAttribute("products", products);
        } catch (Exception e) {
            Notice notice = new Notice();
            notice.addErrorMessage("Couldn't fetch products: " + e.getMessage());
            request.setAttribute("notice", notice);
        }
        request.getRequestDispatcher("/productListing.jsp").forward(request, response);
    }

ProductIndexController(servlet)

{{1}}

1 个答案:

答案 0 :(得分:0)

您可以做的是重定向,添加请求参数,说redirected,并在网址中将其设置为redirected,然后在您的servlet代码中,只需调用request.getParamemter("redirected") ,如果此请求参数存在,请不要调用重定向,否则调用重定向

if (request.getParameter("redirected") == null)
    // pay attention to the ?redirected=redirected in the url
    request.getRequestDispatcher("/productListing.jsp?redirected=redirected").forward(request, response)

当该请求参数为null时,您知道该请求来自您的jsp,而不是重定向的响应