HttpServlet getRequestDispatcher()。forward()不显示新的jsp

时间:2017-06-14 12:09:50

标签: java jsp servlets

我是后端开发的新手。我写了我的第一个HttpServlet,它运行正常。我的问题是,在执行代码之后,我想将用户转发到详细信息页面。我可以在日志中看到转发的页面代码已执行,但旧的jsp仍然在屏幕上。

当用户点击一行(选择用户)时调用此代码

    private void readUserById(HttpServletRequest request, HttpServletResponse response) {
    int userId = Integer.valueOf(request.getParameter(Prefs.REQUEST_PARAMS_USER_ID_KEY));
    UserDao userDao = new UserDao();
    UserDao.UserDaoResult daoResult = userDao.readUser(userId);
    User user = daoResult.getUser();
    if (user != null) {
        Gson gson = new Gson();
        String userJson = gson.toJson(user);
        request.setAttribute(Prefs.REQUEST_USER_JSON_KEY, userJson);
        try {
            getServletContext().getRequestDispatcher("/userdetails.jsp").forward(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这是我的userdetail.jsp

<%@ page import="utils.Logger" %>
<%@ page import="com.google.gson.Gson" %>

<%@ page import="model.User" %>
<%@ page import="com.google.gson.reflect.TypeToken" %>
<%@ page import="java.lang.reflect.Type" %><%--
  Created by IntelliJ IDEA.
  User: molnard
  Date: 2017. 06. 14.

  Time: 12:22
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>User Details</title>
</head>
<body>
<%
    String userJson = request.getAttribute("userJson").toString();
    Logger.logUserDetails(userJson);
    Gson gson = new Gson();
    Type type = new TypeToken<User>() {
    }.getType();
    User user = gson.fromJson(userJson, type);
    Logger.logUserDao("userdetails.jsp\nUser name: "+user.getUserName()+"\nUser age: "+user.getUserAge());
%>
<span>User name: <%=user.getUserName()%></span><br>
<span>User age: <%=user.getUserAge()%></span>
</body>
</html>

我可以在serverlog上看到Logger.logUserDao()的输出,并且有预期的用户。 但我仍然在屏幕上看到第一个jsp。

0 个答案:

没有答案