model passed from spring controller to jsp, some attributes added and passed to another controller, Does Not Work

StackOverflow https://stackoverflow.com/questions/13787681

  •  06-12-2021
  •  | 
  •  

Pergunta

the process is: a list of received messages shown in a table with a reply link in front of each one. pressing reply goes to this controller:

    @RequestMapping("/createMessage")
public String createMessage(@RequestParam("receiver") String receiver, HttpSession session, Model model){
  try{  

    Message message = new Message();
    //sender, Date, and receiver are known and are added to the object      

    model.addAttribute(message);

    return "newMessage";

  } catch (Exception e){
        model.addAttribute("message", "Can't create message!");
        return "error"; 
  }

newMessage.jsp is as follow. it receives the model, because from:, To:, and Date: fields are properly filled:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"   "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Send Message</title>
</head>
<body>
<form:form modelAttribute="message" method="POST" action="sendMessage">
<table border="1">
<tr>
  <th>To: </th><td>${message.userName}</td>
</tr>
<tr>
  <th>from: </th><td>${message.fromUser}</td>
</tr>
    <tr>
  <th>Date: </th><td>${message.messageDate}</td>
</tr>
<tr>
  <th>Message</th>
  <td>
    <form:textarea path="message"/>
  </td>            

</table>
<input type="submit" value="send Message">
</form:form>  

</body>
</html>

when send button is pressed the following controller is responsible to create the object in the database (using Hibernate), but it gives the error of "fromUser column can not be null". shows that the connection to the database is working, but the object is not passed to this controller. why?

@RequestMapping("/sendMessage")
public String sendMessage(HttpSession session,@ModelAttribute("message") Message message, Model model){

    try{
    MessageDAO mDao = new MessageDAO();
    Message message2 = mDao.create(message);

    model.addAttribute("message", "Message was sent");
    return "success";

    } catch(Exception e){
        model.addAttribute("message", "Can't create message!");
        return "error";
    }


}
Foi útil?

Solução

Debug your sendMessage routine. Your form only contains a field for the message, the other fields are technically not part of the form. Either you want to store your message object to the session so the java bean survives the two requests or you can repeat userName, fromName, etc. as hidden fields, so they are mapped to the new request bean created for sendMessage.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top