如何使用jsp

时间:2018-11-17 03:37:11

标签: java json jsp

我想将视图从HTML列表更改为JSON数据。

这是我在控制器中的代码:-

private void listFeedback(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, IOException, ServletException {
        Feedback p = new Feedback();
        int seller_id = Integer.parseInt(request.getParameter("seller_id"));
        List<Feedback> feedbacks = p.all(seller_id);
        String format = request.getParameter("format");
        if(format == "json"){
            String json = new Gson().toJson(feedbacks);

            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(json);
            RequestDispatcher dispatcher = request.getRequestDispatcher("feedbacks/demo.jsp");
            dispatcher.forward(request, response);
        }
        request.setAttribute("feedbacks", feedbacks);
        RequestDispatcher dispatcher = request.getRequestDispatcher("feedbacks/list.jsp");
        dispatcher.forward(request, response);
    }

但是,它仍然可以像以前一样被查看,没有任何改变。我希望将其重定向到demo.jsp,以便可以具有JSON视图。有人会帮我做同样的事情吗?

更新

我只是忘了把其他东西放在那里 所以,这是正确的代码

else{
    request.setAttribute("feedbacks", feedbacks);
            RequestDispatcher dispatcher = request.getRequestDispatcher("feedbacks/list.jsp");
            dispatcher.forward(request, response);
}

非常感谢您回答我的问题。

1 个答案:

答案 0 :(得分:0)

看起来format的值为空或不是json。如果执行if中存在的代码,您将最终出错(下一行代码将转发到另一个jsp)。

  

“提交响应后无法转发”

进行以下更改以使其起作用:

当您想返回JSON时,您无需转发。只需在以下代码中添加以下内容

if("json".equals(format)){
                String json = new Gson().toJson(feedbacks);
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write(json);
                return; // return from here or change to if-else
}

整个代码:

    private void listFeedback(HttpServletRequest request, HttpServletResponse response)
                throws SQLException, IOException, ServletException {
            Feedback p = new Feedback();
            int seller_id = Integer.parseInt(request.getParameter("seller_id"));
            List<Feedback> feedbacks = p.all(seller_id);


      String format = request.getParameter("format");
        if("json".equals(format)){
            String json = new Gson().toJson(feedbacks);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(json);
            return;// return from here or change to if-else
        }
        request.setAttribute("feedbacks", feedbacks);
        RequestDispatcher dispatcher = request.getRequestDispatcher("feedbacks/list.jsp");
        dispatcher.forward(request, response);
    }