Java SpringMVC模型属性在post时返回null

Java SpringMVC模型属性在post时返回null,java,spring,jsp,spring-mvc,servlets,Java,Spring,Jsp,Spring Mvc,Servlets,我当时正在开发一个SpringMVC3琐碎的应用程序,但我被困在了某个地方。本质上,GET操作中填充字段的模型属性在POST中返回NULL(即使我没有对其进行任何操作)。我在这个论坛和其他论坛上进行了检查,我得到的唯一答案是为我应该放入模型中的类实现编辑器,这是一个初始值设定项,可用于注册自定义编辑器并使其可用于应用程序(在servletname-servlet.xml文件中)。我做的所有手术,但绝对没有运气。我想知道是否有人能帮我一把。 多谢各位 以下控制器: @Controller @Req

我当时正在开发一个SpringMVC3琐碎的应用程序,但我被困在了某个地方。本质上,GET操作中填充字段的模型属性在POST中返回NULL(即使我没有对其进行任何操作)。我在这个论坛和其他论坛上进行了检查,我得到的唯一答案是为我应该放入模型中的类实现编辑器,这是一个初始值设定项,可用于注册自定义编辑器并使其可用于应用程序(在servletname-servlet.xml文件中)。我做的所有手术,但绝对没有运气。我想知道是否有人能帮我一把。 多谢各位

以下控制器:

@Controller
@RequestMapping(value="/nourish")
public class NourishController {

private PetDAO pdao = new PetDAO();
private UserDAO udao = new UserDAO();
private FeedVirtualPet feedvp = new FeedVirtualPet();

@RequestMapping(method = RequestMethod.GET)
public String nourish(Model model, HttpServletRequest request){
    NourishPetDTO npdto = new NourishPetDTO();
    PetDTO      pdto=pdao.findPetByBusinessKey((PetDTO)request.getSession().getAttribute("pet"));
    npdto.setPet(pdto);
    npdto.setAmt(0);
    model.addAttribute("npdto", npdto);
    return "nourish";
}


@RequestMapping(method = RequestMethod.POST)
public String nourishPOST(@ModelAttribute("npdto") NourishPetDTO npdto,
        //BindingResult result,
        HttpServletRequest request){

    System.out.println("*****nourishPOST.npdto.amt: "+npdto.getAmt());
    System.out.println("*****nourishPOST.npdto.pet.petname: "+npdto.getPet().getPetName());
    System.out.println("*****nourishPOST.npdto.pet.hunger:     "+npdto.getPet().getHunger());
    PetDTO pdto = feedvp.feed(npdto.getPet(), npdto.getAmt());
    request.getSession().setAttribute("user", pdto.getOwner());
    return "redirect:detailPet";
}
}
具有用于GET和POST操作的方法,并与以下jsp关联-在此视图中,所有模型信息都通过EL正确显示:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" session="true"  pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ 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>Nourish your pet!!</title>
</head>
<body>
Your stats for <h3>${npdto.pet.petName}</h3><br>
    Please note that any value you put inside will:
        <ol>
            <li>Subtract value to your current hunger level</li>
            <li>Add (value) to your current health level</li>
        </ol>
    Please note that any value you'll put will in many manners "resized":
    <ol>
        <li>It must be even. If not, a default 0 value will be  applied</li>
        <li>It can't be greater than 4. If it's greater, the maxium value  of 4 will be anyway considered.</li>
        <li>If it ain't a number, a default zero value will be passed</li>
    </ol>
<table>
    <tr><td>Health</td><td>${npdto.pet.health}</td></tr>
    <tr><td>Hunger</td><td>${npdto.pet.hunger}</td></tr>
</table>
<form action="nourish" method="post"  >
    nourishment: <input type="text" name="amt"/>
    <input type="submit" value="Nourish!"/>
</form>
</body>
</html>
因为Tomcat返回一个NullPointerException

如上所述,我一直在寻找这个问题的解决方案,我所能找到的一切就是向活页夹添加编辑器类和注册编辑器。结果还是一样

总之,这些是类:

java

public class NourishPetEditor extends PropertyEditorSupport {

private PetEditor pedit;

public PetEditor getPedit() {
    return pedit;
}


public NourishPetEditor() {
    // TODO Auto-generated constructor stub
    pedit =  new PetEditor();
}

@Override 
public String getAsText(){
    NourishPetDTO npdto= (NourishPetDTO)getValue();
    return super.getAsText()+","+npdto.getAmt();
}

public NourishPetDTO makeNourishPetDTOInstance(String [] parts){

    NourishPetDTO npdto = new NourishPetDTO(); 
    npdto.setPet(pedit.makePetDTOInstance(parts));
    npdto.setAmt(Integer.parseInt(parts[9]));
    return npdto;

}


public void setAsText(String key){
    String []parts = key.split(",");
    NourishPetDTO npdto = makeNourishPetDTOInstance(parts);
    setValue(npdto);
}
}
package com.virtualpet.dtoeditors;
import java.beans.PropertyEditorSupport;

import com.virtualpet.virtualpet_daos.PetDAO;  
import com.virtualpet.virtualpet_dtos.PetDTO;
import com.virtualpet.virtualpet_dtos.UserDTO;
public class PetEditor extends PropertyEditorSupport{

private PetDAO pdao;

public PetEditor() {
    // TODO Auto-generated constructor stub
}

public PetEditor(PetDAO pdao) {
    // TODO Auto-generated constructor stub
    this.pdao = pdao;

}


public String getAsText(){
    PetDTO pdto = (PetDTO) this.getValue();

    return pdto.getClass().getName()+","+ //0
    pdto.getPetName()+","+ //1
    pdto.getHealth()+","+  //2
    pdto.getHunger()+","+  //3
    pdto.getMood()+","+","+ //4
    pdto.getOwner().getClass().getName()+","+ //5
    pdto.getOwner().getUsername()+","+ //6
    pdto.getOwner().getEmail()+","+pdto.getOwner().getPassword(); //7,8

}

public void setAsText(String key) throws IllegalArgumentException {
    String []parts = key.split(",");
    PetDTO pdto = makePetDTOInstance(parts);
    setValue(pdto);
}


public UserDTO makeUserDTOInstance(String[] parts)
        throws InstantiationException, IllegalAccessException,
        ClassNotFoundException {

            UserDTO udto = (UserDTO)Class.forName(parts[5]).newInstance();
            udto.setUsername(parts[6]);
            udto.setEmail(parts[7]);
            udto.setPassword(parts[8]);
            return udto;
}


public PetDTO makePetDTOInstance(String[]parts){
    try{
        PetDTO pdto = (PetDTO) Class.forName(parts[0]).newInstance();
        pdto.setPetName(parts[1]);
        pdto.setHealth(Integer.parseInt(parts[2]));
        pdto.setHunger(Integer.parseInt(parts[3]));
        pdto.setMood(Integer.parseInt(parts[4]));

        UserDTO udto = makeUserDTOInstance(parts);

        pdto.setOwner(udto);
        return pdto;
    }
    catch (Exception e){
        throw new IllegalArgumentException();
    }
}
}
PetEditor.java

public class NourishPetEditor extends PropertyEditorSupport {

private PetEditor pedit;

public PetEditor getPedit() {
    return pedit;
}


public NourishPetEditor() {
    // TODO Auto-generated constructor stub
    pedit =  new PetEditor();
}

@Override 
public String getAsText(){
    NourishPetDTO npdto= (NourishPetDTO)getValue();
    return super.getAsText()+","+npdto.getAmt();
}

public NourishPetDTO makeNourishPetDTOInstance(String [] parts){

    NourishPetDTO npdto = new NourishPetDTO(); 
    npdto.setPet(pedit.makePetDTOInstance(parts));
    npdto.setAmt(Integer.parseInt(parts[9]));
    return npdto;

}


public void setAsText(String key){
    String []parts = key.split(",");
    NourishPetDTO npdto = makeNourishPetDTOInstance(parts);
    setValue(npdto);
}
}
package com.virtualpet.dtoeditors;
import java.beans.PropertyEditorSupport;

import com.virtualpet.virtualpet_daos.PetDAO;  
import com.virtualpet.virtualpet_dtos.PetDTO;
import com.virtualpet.virtualpet_dtos.UserDTO;
public class PetEditor extends PropertyEditorSupport{

private PetDAO pdao;

public PetEditor() {
    // TODO Auto-generated constructor stub
}

public PetEditor(PetDAO pdao) {
    // TODO Auto-generated constructor stub
    this.pdao = pdao;

}


public String getAsText(){
    PetDTO pdto = (PetDTO) this.getValue();

    return pdto.getClass().getName()+","+ //0
    pdto.getPetName()+","+ //1
    pdto.getHealth()+","+  //2
    pdto.getHunger()+","+  //3
    pdto.getMood()+","+","+ //4
    pdto.getOwner().getClass().getName()+","+ //5
    pdto.getOwner().getUsername()+","+ //6
    pdto.getOwner().getEmail()+","+pdto.getOwner().getPassword(); //7,8

}

public void setAsText(String key) throws IllegalArgumentException {
    String []parts = key.split(",");
    PetDTO pdto = makePetDTOInstance(parts);
    setValue(pdto);
}


public UserDTO makeUserDTOInstance(String[] parts)
        throws InstantiationException, IllegalAccessException,
        ClassNotFoundException {

            UserDTO udto = (UserDTO)Class.forName(parts[5]).newInstance();
            udto.setUsername(parts[6]);
            udto.setEmail(parts[7]);
            udto.setPassword(parts[8]);
            return udto;
}


public PetDTO makePetDTOInstance(String[]parts){
    try{
        PetDTO pdto = (PetDTO) Class.forName(parts[0]).newInstance();
        pdto.setPetName(parts[1]);
        pdto.setHealth(Integer.parseInt(parts[2]));
        pdto.setHunger(Integer.parseInt(parts[3]));
        pdto.setMood(Integer.parseInt(parts[4]));

        UserDTO udto = makeUserDTOInstance(parts);

        pdto.setOwner(udto);
        return pdto;
    }
    catch (Exception e){
        throw new IllegalArgumentException();
    }
}
}
我将不使用UserEditor,因为它与PetEditor非常相似。 最后,使用初始值设定项绑定自定义编辑器&模型类

VirtualPetDTOInitializer.java

package com.virtualpet.dtoeditors;

import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.WebRequest;

import com.virtualpet.virtualpet_dtos.NourishPetDTO;
import com.virtualpet.virtualpet_dtos.PetDTO;
import com.virtualpet.virtualpet_dtos.UserDTO;

public class VirtualPetDTOInitializer implements WebBindingInitializer {

public void initBinder(WebDataBinder binder, WebRequest arg1) {
    // TODO Auto-generated method stub
        binder.registerCustomEditor(UserDTO.class, new UserEditor( ));
        binder.registerCustomEditor(PetDTO.class, new PetEditor( ));
        binder.registerCustomEditor(NourishPetDTO.class, new NourishPetEditor());
}
}
此类在dispatcher-servlet.xml中定义属性值:

<?xml version="1.0" encoding="UTF-8"?>
<beans ...>
<bean id="userDao"
    class="com.virtualpet.virtualpet_daos.UserDAO"/>
<bean id="petDao"
    class="com.virtualpet.virtualpet_daos.PetDAO" />
<bean    class="org.springframwork.web.servlet.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="webBindingInitializer">
        <bean class="com.virtualpet.dtoeditors.VirtualPetDTOInitializer"/>
    </property>
</bean>
</beans>

作为SpringMVC的新手,我必须告诉你们,这个错误是我在实现这些类之前就遇到的。所以,看起来它们不是一个因素,然而,它们的实现是我所能找到的关于模型属性的一切,在POST之后返回null。
有人能帮忙吗?提前谢谢

您需要执行以下操作之一:

  • npdto
    的值存储在隐藏表单字段中

  • 在会话中存储
    npdto

  • 从post处理程序中的数据库重新读取
    npdto

  • 您可能需要#2,在这种情况下,在控制器的顶部添加
    @SessionAttributes(“npdto”)

    您还应该向post处理程序添加一个
    SessionStatus
    参数,并在不再需要该项目时调用
    SessionStatus.complete()
    从会话中清除该项目


    有关参考答案,请参阅

    如果要从
    POST
    重定向到
    /detailPet
    中,请确保您有
    /detailPet
    的映射,在名为DetailPetController的控制器中,为了可读性,我已经没有发布该映射(而且,我对该控制器没有问题)。非常感谢您抽出时间,谢谢!这正是我所缺少的。然而,有些事情让我困惑……如果我必须将变量/模型添加到SessionAttribute中,那么将变量或对象添加到模型中又有什么好处呢?我正在学习一本Spring配方手册,如果你想学习“动手”也没关系,但很多事情都没有说出来,这就是其中之一……无论如何,我至少可以继续学习。@Luigiaderosa模型正是视图当前响应所需的数据。它不关心下一个请求。这就是课程的目的。不过,模型对于保持视图和数据的分离很有用。