Extracting data from a database into a text field or text area in Java

Akshay picture Akshay · Nov 23, 2010 · Viewed 12.4k times · Source

I know that we can retrieve text from a text box or text area and then insert the data into a table. How can we do the opposite? That is, how to place all the data back into specific text fields or areas from a database based on some condition?


Update:

I have to do a mini-project. Its a HR Information System project. I must be able to update the details of an employee based on his ID. The way I have designed and envisioned it so far is as follows: There is a dropdown list of IDs. I select one and click OK using a form handler. It then forwards to a servlet that displays the form that I had made while adding an employee. Only, instead of being blank, these text fields consist of the data that I had inserted when adding the abovementioned employee. So, now, how do I extract these column values and put it back into text fields. I have experimented with setting the field values as column attribute names, but all that gets displayed is the name, and not the value. For example, when I set value=firstname (as specified in my database), the data in the textfield is "firstname" and not what the employee's first name actually is. Maybe I'm going about it the wrong way. Can someone please tell me exactly how to retrieve these values?

Answer

BalusC picture BalusC · Nov 24, 2010

Use servlet's doGet() method to preprocess the request (you should call the URL of this servlet in browser).

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Employee employee = getItSomehow();
    request.setAttribute("employee", employee);
    request.getRequestDispatcher("/WEB-INF/edit.jsp").forward(request, response);
}

Use JSP EL to display it in HTML input field's value attribute.

<input name="firstname" value="${employee.firstname}" />

However, this sets doors open to XSS attacks. Use JSTL fn:escapeXml() to prevent it.

<%@taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
...
<input name="firstname" value="${fn:escapeXml(employee.firstname)}" />

See also: