Spring表单将null模型对象发送到数据库

时间:2013-09-11 13:53:32

标签: java spring hibernate postgresql spring-mvc

我想将数据从表单发送到PostgreSQL。当我通过表单发送数据时,hibernate保存(通过save()方法)空白记录..我手动完成(测试)而不使用表单然后一切正常。

Spitter.class (用户实体)

@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 - 显示表单(edit.jsp)并将模型对象(spitter)发送到表单   addSpitterFromForm - 从表单接收绑定数据并将其保存到数据库并重定向到用户配置文件   showSpitterProfile - 当然有空模型对象异常

@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 (新用户的注册表单(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>

并将保存的记录留空到Postgres .. enter image description here

2 个答案:

答案 0 :(得分:1)

尝试在此方法中添加@modelattribute。填充获取所需的模型对象。

@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();
}

并且只是为了检查它是否从表单获取值,syso一些值如syso(spitter.getUserName)来检查值是否会到来。

另外,我相信你正在构建一个构造函数并将服务传递给它,因此不需要@Inject

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

答案 1 :(得分:1)

您的表单中有enctype="multipart/form-data

检查App-servlet.xml中是否有类似内容:

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