将值从Servlet传递到JSP

时间:2011-08-24 09:43:13

标签: java forms java-ee servlets

我想从列表中选择一个用户,并在输入字段中显示这些值(以便管理员可以更改它们)

JSP具有从用户列表中选择用户的表单:

         <form action="UserSelectionController" method="POST">
             <select name="selectedUser" onchange="this.form.submit()">
                <%
                  Object[] userList_ref = UserListService.getUserList();
                  for (int i = 0; i < userList_ref.length; i++) {%>
                        <option  size="5" value="<%=userList_ref[i]%>">           <%=userList_ref[i]%></option> <% }%>
             </select>
        </form>

UserSelectionController从数据库中读出值,如下所示:(此处只有dopost方法)

Protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    this.connectToDataBase();

    Statement stmt_ref = null;
    try {
        stmt_ref = (Statement) connection.createStatement();
        ResultSet results_ref = stmt_ref.executeQuery("SELECT salutation,firstname,lastname,street,houseNr,zip,city,country,email,password FROM User WHERE email = '" + request.getParameter("selectedUser") + "'");

        while (results_ref.next()){
            salutation = results_ref.getString("salutation");
            firstname = results_ref.getString("firstname");
            lastname = results_ref.getString("lastname");
            street = results_ref.getString("street");
            houseNr = results_ref.getInt("houseNr");
            zip = results_ref.getInt("zip");
            city = results_ref.getString("city");
            country = results_ref.getString("country");
            email = results_ref.getString("email");
            password = results_ref.getString("password");
        }
    } catch (SQLException ex) {
        Logger.getLogger(UserSelectionController.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.out.println ("Paramter SelectedUser: "+request.getParameter("selectedUser"));
    System.out.println ("Firstname: "+firstname);

    response.sendRedirect(AbsoluteTerms.DOMAIN_USER_SETTINGS);
}

它还使用getter方法将值带回JSP:

    public String getFirstname() {
    return firstname;
}

系统输出println测试显示servlet中的正确值。 Redirect将转到数据来源的同一JSP。回到JSP我想在输入字段中显示值:

   <jsp:useBean id="userSelection" class="servlets.UserSelectionController" />
   <input type="text" name="firstname" value="<% userSelection.getFirstname();%>" />

可悲的是,这里的值为null。我能做什么。任何线索都会很棒。 最好的问候,丹尼尔

2 个答案:

答案 0 :(得分:2)

您正在使用您的servlet,作为dto。这不好。

创建另一个pojo,它将是DTO。它只有成员变量是字符串,并且是accopmanying getters / setters。使用查询结果填充其成员,并将dto放入session:

request.setAttribute("userSelectionDTO",userSelectionDTO);

然后更改jsp,使其引用dto:

 <jsp:useBean id="userSelection" class="servlets.UserSelectionDTO" />
 <input type="text" name="firstname" value="<% userSelection.getFirstname();%>"

This可能有用,并在jsp中使用JSTL

答案 1 :(得分:0)

当NimChimpsky写或只是将所选用户保留在http会话中时。