【问题标题】:Spring MVC Controller , pass a bean between two methodSpring MVC Controller,在两个方法之间传递一个bean
【发布时间】:2015-02-20 09:37:07
【问题描述】:

我已经开始通过开发一个简单的 SPRING MVC 应用程序来学习 Spring MVC。

我创建了一个用于列出的 JSP 文件 - 像这样编辑用户列表:

当我单击“编辑”链接(来自列表项)时,表单应由项目信息填充,因此用户可以编辑信息并保存项目(请注意,此表单用于创建/编辑项目)

这是与JSP文件相关的代码:

<c:url var="addAction" value="/admin/users/add"></c:url>

<form:form action="${addAction}" commandName="user">

    <table>

        <c:if test="${!empty user.adminName}">
            <tr>
                <td><form:label path="id">
                        <spring:message text="ID" />
                    </form:label></td>
                <td><form:input path="id" readonly="true" size="8"
                        disabled="true" /> <form:hidden path="id" /></td>
            </tr>
        </c:if>

        <tr>
            <td><form:label path="adminName">
                    <spring:message text="Name" />
                </form:label></td>
            <td><form:input path="adminName" /></td>
        </tr>

        <tr>
            <td><form:label path="adminEmail">
                    <spring:message text="adminEmail" />
                </form:label></td>
            <td><form:input path="adminEmail" /></td>
        </tr>

        <tr>

            <td><form:select path="groups" items="${groupList}" /></td>
        </tr>


        <tr>
            <td colspan="2"><c:if test="${!empty user.adminName}">
                    <input type="submit" value="<spring:message text="Edit Person"/>" />
                </c:if> <c:if test="${empty user.adminName}">
                    <input type="submit" value="<spring:message text="Add Person"/>" />
                </c:if></td>
        </tr>
    </table>
</form:form>





<br>
<div class="bs-example">
    <table class="table">
        <thead>
            <tr>
                <th>Row</th>
                <th>First Name</th>
                <th>Email</th>
            </tr>
        </thead>


        <tbody>

            <c:forEach var="i" items="${users}">

                <tr>
                    <td>${i.id}</td>
                    <td>${i.firstName}</td>
                    <td>${i.adminEmail}</td>

                    <td><a href="<c:url value='/admin/users/edit/${i.id}'/>">Edit</a></td>
                    <td><a href="<c:url value='/admin/users/remove/${i.id}'/>">Delete</a></td>


                </tr>

            </c:forEach>

        </tbody>

    </table>
</div>

我的控制器方法是:

    @Controller
@RequestMapping(value = "/admin/users/")
public class UserController {

    private static final Logger LOGGER = LoggerFactory
            .getLogger(UserController.class);

    @Autowired
    UserService userService;

    @Autowired
    GroupService groupService;

    @Autowired
    LabelUtils messages;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;


    // @PreAuthorize("hasRole('STORE_ADMIN')")
    @RequestMapping(value = "list.html", method = RequestMethod.GET)
    public String displayUsers(Model model) throws Exception {

        List<User> users = userService.listUser();

        List<Group> groups = groupService.list();

        List<String> groupList = new ArrayList<String>();

        model.addAttribute("users", users);
        model.addAttribute("user", new User());

        for (Group group : groups) {

            groupList.add(group.getGroupName());

        }

        model.addAttribute("groupList", groupList);

        return "admin/userAdmin";

    }

    @RequestMapping("remove/{id}")
    public String removePerson(@PathVariable("id") int id) {

        User user = userService.getById((long) id);

        try {
            userService.delete(user);
        } catch (ServiceException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return "redirect:/admin/users/list.html";
    }

    // For add and update person both
    @RequestMapping(value = "add" , method = RequestMethod.POST)
    public String addPerson(@ModelAttribute("user") User user,
            BindingResult result) {

        if (result.hasErrors()) {
            return "error";
        }

        try {
            if (user.getId() == 0) {
                // new person, add it

                this.userService.create(user);

            } else {
                // existing person, call update
                this.userService.saveOrUpdate(user);
            }

        } catch (ServiceException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return "redirect:/admin/users/list.html";


    }

    @RequestMapping(value = "edit/{id}" )
    public String editPerson(@PathVariable("id") int id  , Model model) {



        // Prepare Groups

        List<Group> groups = groupService.list();

        List<String> groupList = new ArrayList<String>();

        for (Group group : groups) {

            groupList.add(group.getGroupName());

        }

        model.addAttribute("groupList", groupList);

        model.addAttribute("user", this.userService.getById((long) id));
        model.addAttribute("users", this.userService.list());

        return "admin/userAdmin";

    }


}

问题是当我单击编辑链接时,表单由项目信息正确填充,因此用户可以编辑检索到的数据,但对象“用户”是从控制器中“addPerson”方法中的“editPerson”方法检索到的(

代码行:model.addAttribute("user", this.userService.getById((long) id));在 editPerson 方法中) 让所有其他字段为空,所以当我合并数据时,保存操作失败。

示例:用户项有另一个字段“AdminAPassword”未在 JSP 中打印并且未更改 bu 用户,当从表单中检索数据时该字段为空。

你能帮忙吗

提前致谢

【问题讨论】:

  • 从 Get 到 Post 方法传递对象的方式是正确的根据 MVC spring 规则。谢谢

标签: spring spring-mvc


【解决方案1】:

你的问题有些不清楚,我会根据你的标题来处理。我的理解是,您希望在控制器内的方法之间共享 user bean。您可以通过使用 @SessionAttributes 注释您的控制器来实现此目的

@SessionAttributes("user")
@Controller
@RequestMapping(value = "/admin/users/")
public class UserController {

使用此设置,名称与 @SessionAttributes 中列出的名称匹配的所有模型属性将在后续请求中继续存在。你可以了解更多here

【讨论】:

  • 对象在 sessionAttributes 中成功传递,当我们通过代码检索“用户”时,我尝试了一个案例,当这个对象与另一个对象有 manyToMany 关系,比如说“组”: gerGroups ,它给出 null ,尽管最初它在传递给 session 属性时有一个组列表。非常感谢您的反馈。
猜你喜欢
  • 2012-01-12
  • 2020-11-28
  • 2011-12-23
  • 2018-02-01
  • 2014-01-02
  • 1970-01-01
  • 2017-08-17
  • 2014-01-24
  • 2020-04-28
相关资源
最近更新 更多