Spring MVC中请求之间的数据传输

时间:2014-03-02 23:53:42

标签: java spring-mvc

我有一个简单的向导控制器。当我尝试从上一次读取数据时,我的用户属性消失了。任何想法为什么会发生,我该如何解决?

这是我的控制器

@Controller
public class WizardController {
    @RequestMapping(method = RequestMethod.GET)
    public String userForm(User user) {
        return "form/userForm";
    }   

    @RequestMapping(value = "/user", method = RequestMethod.POST)
    public String processedForm(User user, BindingResult result, ModelMap model) {
        if (result.hasErrors()) {return "form/userForm";}
        ArrayList<String> p = new ArrayList<String>();
        p.add("add_user");
        p.add("delete_user");
        model.addAttribute("permissions", p);
        model.addAttribute("user", user);
        return "form/permissionForm";
    }

    @RequestMapping(value = "/show", method = RequestMethod.POST)
    public String show(@ModelAttribute("user") User user, BindingResult result) {
        if (result.hasErrors()) {
            System.out.println("Error");
            return "show";
        } else {
            System.out.println(user);
            return "show";
        }
    }
}

我的POJO

public class User implements Serializable {
    private String name;
    private String email;
    private String password;
    private Integer age;
    private List<String> permissions;
    ...
}

userForm.jsp

<form:form action="/user" method="post" modelAttribute="user">
    <form:errors path="*" cssClass="errorblock" element="div"/>
    <p><form:input path="name" placeholder="Name"/></p>
    <p><form:input path="age" placeholder="Age"/></p>
    <p><form:input path="email" placeholder="Email"/></p>
    <p><form:input path="password" placeholder="Password"/></p>
    <input type="submit"></p>
</form:form>

permissionForm.jsp

<form:form action="/show" method="post" modelAttribute="user">
    <form:errors path="*" cssClass="errorblock" element="div"/>
    <p>
        <form:select path="permissions">
            <form:options items="${permissions}"/>
        </form:select>
    </p>
    <p><input type="submit" value="Add"/></p>
</form:form>

和show.jsp

${user}

1 个答案:

答案 0 :(得分:0)

查看为同一目的而构建的RedirectAttributes,即保留请求之间的值。

http://docs.spring.io/spring/docs/3.1.x/javadoc-api/org/springframework/web/servlet/mvc/support/RedirectAttributes.html