Search code examples
javajspspring-mvccontrollermodelattribute

Getting a list of the repeated last form data when trying to fetch the list of objects from database


My first jsp is email.jsp and from there it is directed to template.jsp but when I try to get the list of EmailMessages object, I get repeated entries of the last form submitted data when I must be getting all the objects the database. Can anyone please help me through this?

@RequestMapping(value = "/email", method = RequestMethod.GET)
public String addEmail() {
    return "email";
}

@RequestMapping(value = "/template", method = RequestMethod.POST)
public String getTemplateEmail(@ModelAttribute EmailMessage emailMessage, ModelMap model) {
    emailService.insertTemplate(emailMessage);
    List<EmailMessage> emailMessageList = new ArrayList<EmailMessage>();
    emailMessageList = emailService.fetchTemplate();
    model.addAttribute("emailMessageList", emailMessageList);
    return "template";
}

email.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Email body</title>
</head>
<body>
<form action="/TemplateEmail/template" method="POST">
<table>
    <tr>
        <td><b>Category </b>: </td>
        <td><select name="category">
            <option value=""> </option>
            <option value="normal">Normal</option>
            <option value="urgent">Urgent</option>
        </select></td>
        <td>
        <button type="button" style="width: 25px;height: 25px;border: solid 1px #000;border-radius: 25px" onclick="addCategory()">+</button>
        <script>
            function addCategory() {
                var category = prompt("Add new category", "");
            }
        </script>
        </td>
    </tr>
    <tr>
        <td><b>Subject </b>: </td>
        <td><input type="text" name="subject"/></td>
    </tr>
    <tr>
        <td><b>Body </b>: </td>
        <td><textarea name="body" rows="10" columns="50"></textarea>     </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
        <input type="submit" value=" SAVE "/>
        </td>
    </tr>
</table>
</form>
</body>
</html>

EmailMessage.java

package com.qburst.templateemail.entity;

public class EmailMessage {

private String category;
private String subject;
private String body;
private Long id;

public String getCategory() {
    return category;
}

public void setCategory(String category) {
    this.category = category;
}

public String getSubject() {
    return subject;
}

public void setSubject(String subject) {
    this.subject = subject;
}

public String getBody() {
    return body;
}

public void setBody(String body) {
    this.body = body;
}

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

}

template.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Template Webpage</title>
</head>
<body>
<center>
    <table border="1">
      <tr>
        <th>select</th>
        <th>Category</th>
        <th>Subject</th>
        <th>Body</th>
      </tr>
      <c:forEach var="emailMessage" items="${emailMessageList}">
          <tr>
            <td><label for="${emailMessage.id}"></label><input type="radio" name="emailMsg" id="${emailMessage.id}"/></td>
            <td>${emailMessage.category}</td>
            <td>${emailMessage.subject}</td>
            <td>${emailMessage.body}</td>
          </tr>
      </c:forEach>
    </table><br>
    <input type="button" onclick="location.href='/TemplateEmail/email'" value="Add More" />
    <br><br><br>
    <input type="button" onclick="location.href='/TemplateEmail/send_email'" value="Send To" />
    </center>
  </body>
</html>

EmailDao.java This is the code for fetching the list from database.

public List<EmailMessage> fetchTemplate() {
    String query = "select * from email_message";
    Connection connection = null;
    List<EmailMessage> emailMessageList = new ArrayList<EmailMessage>();
    try {
        EmailMessage emailMessage = new EmailMessage();
        connection = dataSource.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(query);
        ResultSet resultSet = preparedStatement.executeQuery(query);
        while (resultSet.next()) {
            emailMessage.setCategory(resultSet.getString("category"));
            emailMessage.setSubject(resultSet.getString("subject"));
            emailMessage.setBody(resultSet.getString("body"));
            emailMessageList.add(emailMessage);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    return emailMessageList;
}

Solution

  • Ok, try to create always new object at the loop:

    EmailMessage emailMessage;
    while (resultSet.next()) {
           emailMessage = new EmailMessage();
           emailMessage.setCategory(resultSet.getString("category"));
           emailMessage.setSubject(resultSet.getString("subject"));
           emailMessage.setBody(resultSet.getString("body"));
           emailMessageList.add(emailMessage);
    }
    

    You are added repeated link at object to list. You always change values at the all members of list, because it link to one object.