简体   繁体   中英

How do I pre-fill text fields in a form with info from a database in a .jsp?

I'm trying to create a form that updates an entry in a MySQL database. The table is a users table that contains various fields related to the user. I need this page to work as an update form that takes a username that is passed to it via the previous page and pre-fills the text fields with the existing data. It's a model one application that uses a presentation, transport, and data layer. The transport layer is User.java and the data layer (that interacts with the database) is UserDB.java.

Here's the code, everything is functional except the pre-filling.

UPDATE: I've edited to reflect the changes from the answers below, I also want to note that "UserDB.getUsers()" returns an ArrayList.

<%@ page language="java" contentType="text/html; charset=iso-8859-1"
pageEncoding="ISO-8859-1" import="java.util.ArrayList,beans.*,data.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
//get parameters from the request
String userName = request.getParameter("userName");

ArrayList userList = UserDB.getUsers(userName);
    User user = userList.get(0);
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" href="styles/style.css" type="text/css" />
<title>User Admin</title>

</head>
<body>


<div id="main">
  <h1>Update  User</h1>
  <h3>User Info</h3>
  <hr>
    <div id="content">
    <form action="updateUser.jsp" method="get">
      <p>User Name<br>
        <input type="text" name="userName" size="20" value="<%=userName%>"/>
      </p>
      <p>Password<br>
        <input type="text" name="password" size="20" value="<%=user.getPassword()%>"/>
      </p>
      <p>First Name<br>
        <input type="text" name="firstName" size="20" value="<%=user.getFirstName()%>"/>
      </p>
      <p>Last Name<br>
        <input type="text" name="lastName" size="20" value="<%=user.getLastName()%>"/>
      </p>
      <p>Email Address<br>
       <input type="text" name="email" size="20" value="<%=user.getEmail()%>"/>
      </p>
      <p>
        <input type="submit" value="Commit Update">
      </p>
  </form>
</div>
</div>
</body>
</html>

I know I'm doing something wrong with the "user" object, but I'm overlooking it.

you are passing the username as a string

<%
//get parameters from the request
String userName = request.getParameter("userName");

user = UserDB.getUsers("userName");
//it should be (with out the quotes
user = UserDB.getUsers(userName);

%>

The "username" should have the quotes removed. Also, where are you declaring user's type? ie.

User user =....getUser..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM