Spring form send null model object to database

Question!

I want to send data from form to PostgreSQL. When I send data by form, hibernate save (by save() method) blank record .. I did it manually (for test) without using form and then everything is ok.

Spitter.class (entity for user)

@Entity 
@Table(name="spitter")
public class Spitter implements Serializable {  

private static final long serialVersionUID = 829803238866007413L;

@Id 
//@SequenceGenerator(name = "hibernate_sequence")
@GeneratedValue(strategy=GenerationType.AUTO) @Column(name="spitter_id")
private Long id;
@Column(unique=true) @Size(min=3, max=20) @Pattern(regexp = "^[a-zA-Z0-9]+$", message="Nie poprawna nazwa uzytkownika.")
private String username;
@Size(min=5, max=15, message="Haslo musi miec minimum 5 znakow.")
private String password;
@Size(min=3, max=25, message="Blad w imieniu i nazwisku.")
private String fullName;
@OneToMany(mappedBy="spitter")
private List<Spittle> spittles;
@Email(message="Nie poprawny adres email.")
private String email;
private boolean updateByEmail;  

public Long getId() {
    return id;
}
public void setId(Long id) {
    this.id = id;
}
public String getUsername() {
    return username;
}
public void setUsername(String username) {
    this.username = username;
}
public String getPassword() {
    return password;
}
public void setPassword(String password) {
    this.password = password;
}
public String getFullName() {
    return fullName;
}
public void setFullName(String fullName) {
    this.fullName = fullName;
}
public List<Spittle> getSpittles() {
    return spittles;
}
public void setSpittles(List<Spittle> spittles) {
    this.spittles = spittles;
}
public String getEmail() {
    return email;
}
public void setEmail(String email) {
    this.email = email;
}
public void setUpdateByEmail(boolean updateByEmail) {
    this.updateByEmail = updateByEmail;
}

public boolean isUpdateByEmail() {
    return updateByEmail;
}

@Override
public boolean equals(Object obj) {
    Spitter other = (Spitter) obj;      
    return other.fullName.equals(fullName) && other.username.equals(username) && other.password.equals(password);
}

@Override
public int hashCode() {
    // TODO Auto-generated method stub
    return super.hashCode();
}
}

SpitterController.class createSpitterProfile - shows form (edit.jsp) and sends model object (spitter) to form addSpitterFromForm - receives binding data from form and save it to database and redirects to simply user profile showSpitterProfile - there is of course null model object exception

@Controller
@RequestMapping("/spitters")
public class SpitterController {

private final SpitterService spitterService;

@Inject   //@Autowired
public SpitterController(SpitterService spitterService) {
    this.spitterService = spitterService;
}
//...
@RequestMapping(method = RequestMethod.GET, params = "new")
public String createSpitterProfile(Model model) {
    model.addAttribute("spitter", new Spitter());
    return "spitters/edit";
}

@RequestMapping(method = RequestMethod.POST)
public String addSpitterFromForm(@Valid Spitter spitter, BindingResult bindingResult) {     
    if(bindingResult.hasErrors())
        return "spitters/edit";
    spitterService.saveSpitter(spitter);
    return "redirect:/spitters/" + spitter.getUsername();
}

@RequestMapping(value="/{username}", method = RequestMethod.GET)
public String showSpitterProfile(@PathVariable String username, Model model) {
    model.addAttribute(spitterService.getSpitter(username));
    return "spitters/view";
}

edit.jsp (registration form for new user (Spitter))

<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="s" uri="http://www.springframework.org/tags"%>

<div>
<h2>New account test</h2>

<sf:form method="POST" modelAttribute="spitter" 
     enctype="multipart/form-data">         
<fieldset> 
<table>
  <tr>
     <th><sf:label path="fullName">Full name:</sf:label></th>
     <td><sf:input path="fullName" size="15" /><br/>
     <sf:errors path="fullName" cssClass="error" />
     </td>
  </tr>
  <tr>
     <th><sf:label path="username">Username:</sf:label></th>
     <td><sf:input path="username" size="15" maxlength="15" />
          <small id="username_msg">No spaces, please.</small><br/>
        <sf:errors path="username" cssClass="error" />

      </td>
  </tr>
  <tr>
     <th><sf:label path="password">Password:</sf:label></th>
     <td><sf:password path="password" size="30" 
                        showPassword="true"/> 
         <small>6 characters or more (be tricky!)</small><br/>
         <sf:errors path="password" cssClass="error" />
        </td>
  </tr>

  <tr>
     <th><sf:label path="email">Email Address:</sf:label></th>

     <td><sf:input path="email" size="30"/> 
         <small>In case you forget something</small><br/>
         <sf:errors path="email" cssClass="error" />
        </td>
  </tr>      
  <tr>
     <th></th>
     <td>
        <sf:checkbox path="updateByEmail"/>
        <sf:label path="updateByEmail">Send me email updates!</sf:label>
     </td>
  </tr>
  <tr>
     <th></th>
     <td>           
        <input name="commit" type="submit" 
                value="I accept. Create my account." />
     </td>
  </tr>
 </table>
</fieldset>
</sf:form>
</div>

and blank saved record to Postgres.. enter image description here

By : unixhead


Answers

Try adding @modelattribute in this method .It fill fetch the required model object.

@RequestMapping(method = RequestMethod.POST)
public String addSpitterFromForm(**@ModelAttribute("spitter")** @Valid Spitter spitter, BindingResult bindingResult) {     
    if(bindingResult.hasErrors())
        return "spitters/edit";
    spitterService.saveSpitter(spitter);
    return "redirect:/spitters/" + spitter.getUsername();
}

and just to check if it is getting the values from form,syso some values like syso(spitter.getUserName) to check if values are coming.

ALso, I believe that you are making a constructor and passing service to it ,so there is no need of @Inject

@Inject   //@Autowired///Why are you injecting it if it is a constructor?
public SpitterController(SpitterService spitterService) {
    this.spitterService = spitterService;
}
By : Niks


You have enctype="multipart/form-data in your FORM,

Check that you have something like that in your App-servlet.xml:

<bean id="multipartResolver" class= "org.springframework.web.multipart.commons.CommonsMultipartResolver" p:maxUploadSize="500000" />



This video can help you solving your question :)
By: admin