0

I'm new to backend development. I wrote my first HttpServlet, it works fine. My problem, after my code executed, I'd like to forward the user to a detail page. I can see in logs, the forwarded page's codes are executed, but the old jsp is still on screen.

This code is called when the user clicks on a row (select a user)

    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();
        }
    }
}

and this is my 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>

I can see on the serverlog, the Logger.logUserDao()'s output, and there is the expected user. But I still see the first jsp on the screen.

user3057944
  • 701
  • 1
  • 8
  • 19
  • I don't think this post: (https://stackoverflow.com/questions/4112686/how-to-use-servlets-and-ajax) answers my question. I don't have problem with forwarding with ajax, I try to forward from a HttpServlet, my sencond.jsp executed well, but it doesn't appear on the browser. – user3057944 Jun 14 '17 at 12:20
  • Read last section of answer. – BalusC Jun 14 '17 at 16:48

0 Answers0