简体   繁体   English

Java:Spring MVC-如何在控制器操作中访问更新的模型?

[英]Java: Spring MVC - How do I access the updated model in controller action?

I am learning Spring MVC 3 and am not a Java expert in general. 我正在学习Spring MVC 3,并且通常不是Java专家。 I have a few questions 我有几个问题

  1. From what I can tell ModelAndView is not used anymore. 据我所知,不再使用ModelAndView了。 I also see these two: 我也看到这两个:
    • org.springframework.ui.Model
    • org.springframework.ui.ModelMap

What's the difference between ModelMap and Model ? ModelMapModel什么区别? Is one of them old style like ModelAndView ? 是其中一种像ModelAndView这样的旧样式吗?

  1. How can I pass form data back to the controller? 如何将表格数据传递回控制器? Here's what I have so far: 这是我到目前为止的内容:

VIEW 视图

<form action="/KSC/users/update" method="POST" class="form-horizontal" id="fEdit">

                            <input type="hidden" id="id" name="id" value="${record.id}" />

                            <div class="control-group">
                                <label for="userName" class="control-label"></label>
                                <div class="controls">
                                    <input type="text" id="userName" name="userName" value="${record.userName}" data-validation-engine="validate[required]" />
                                </div>
                            </div>

                            <div class="control-group">
                                <label for="email" class="control-label"></label>
                                <div class="controls">
                                    <input type="text" id="email" name="email" value="${record.email}" data-validation-engine="validate[required,custom[email]]" />
                                </div>
                            </div>

                            <div class="control-group">
                                <div class="controls">
                                    <input type="submit" value="Save" class="btn btn-primary" />
                                    <a href="/KSC/users" class="btn">Cancel</a>
                                </div>
                            </div>
                        </form>

EDIT ACTION 编辑动作

Here's what I originally passed to the above View from the Edit action: 这是我最初从Edit操作传递给上述View的内容:

@RequestMapping(value = "/users/edit/{id}")
    public String edit(ModelMap model, @PathVariable("id") int userId) {
        KCSUser user = service.find(userId);
        model.addAttribute("record", user);
        return "user/edit";
    }

CONTROLLER UPDATE ACTION 控制器更新动作

@RequestMapping(value = "/users/update")
    public String update(ModelMap model) {
        //TODO
    }

I need to access the updated model data so i can save it to my DB. 我需要访问更新的模型数据,以便将其保存到数据库中。 Ideally if it could map directly to a KSCUser object that would be nice.. but if not, then a Model or ModelMap would be fine too. 理想情况下,如果它可以直接映射到一个不错的KSCUser对象,但是如果没有,那么使用ModelModelMap也可以。 How can I do this? 我怎样才能做到这一点?

How can I pass form data back to the controller? 如何将表格数据传递回控制器?

just change the signature of you update method like this: 只需更改您的update方法的签名,如下所示:

@RequestMapping(value = "/users/update")
public String update(KSCUser user, ModelMap model) {
    // ...
}

spring will create a instance of KSCUser and fill the properties based on the name attribute of the input field. spring将创建KSCUser的实例,并根据输入字段的name属性填充属性。 so if you have a input field like <input type="text" name="username" /> , spring will try to call setUsername on the instance of KSCUser. 因此,如果您有一个像<input type="text" name="username" />这样的输入字段,spring将尝试在setUsername实例上调用setUsername。

you could also change the signature of you method like this: 您也可以像这样更改方法的签名:

@RequestMapping(value = "/users/update")
public String update(@RequestParam("username") final String username) {
    // ...
}

spring then would inject the value of the input field with name username . 然后spring将注入名为username的输入字段的值。

or you could change the signature of your method like this: 或者您可以这样更改方法的签名:

@RequestMapping(value = "/users/update")
public String update(Map<String, String> params) {
    // ...
}

spring then would inject all request parameters in the params map. 然后spring会将所有请求参数注入params映射中。 you can access the username like this: params.get("username") . 您可以像这样访问用户名: params.get("username")

for the sake of completeness... you could change the signature of you method like this: 为了完整性...您可以像下面这样更改您的方法的签名:

@RequestMapping(value = "/users/update")
public String update(HttpServletRequest request) {
    // ...
}

spring then would just inject a instance of HttpServletRequest and you could access you request parameters like you would do with vanila servlet api. 春天,然后只需注入HttpServletRequest实例即可访问请求参数,就像使用vanila servlet api一样。

Ideally if it could map directly to a KSCUser object that would be nice.. but if not, then a Model or ModelMap would be fine too 理想情况下,如果它可以直接映射到一个不错的KSCUser对象,但是如果没有,那么Model或ModelMap也可以

when you inject ModelMap only (like you do in your update method), it will not contain the request parameters (except you use @SeessionAttributes ) and you will not be able to access them this way. 当仅注入ModelMap (就像在update方法中一样),它将不包含请求参数(除非您使用@SeessionAttributes ),并且您将无法以这种方式访问​​它们。

What's the difference between ModelMap and Model ModelMap和Model有什么区别

good question. 好问题。 the javadoc for ModelMap says: ModelMap的Javadoc说:

Check out the Model interface for a Java-5-based interface variant that serves the same purpose 检出Model接口,以了解基于Java-5的接口变体,该变体起着相同的作用

imho : the Model interface looks like it was intended only for adding objects to the model (not reading from model)... just like it is the case in your edit method. imhoModel接口看起来仅用于向模型添加对象(而不是从模型读取)……就像您的edit方法一样。 But then there is a asMap method, which grant you access to the content of the model. 但是,这里有一个asMap方法,该方法授予您访问模型内​​容的权限。

i have never used the Model interface myself. 我从未亲自使用过Model接口。 Always inject the ModelMap . 始终注入ModelMap

This seems to work: 这似乎可行:

@RequestMapping(value = "/users/update")
    public String update(ModelMap model, @ModelAttribute("record") KCSUser record) {

        if (record.getId() == 0) {
            service.insert(record);
        }
        else {
            KCSUser existing = service.find(record.getId());
            existing.setUserName(record.getUserName());
            existing.setEmail(record.getEmail());
            //etc...
            service.update(existing);
        }

        return index(model);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 通过Spring MVC Controller动作,如何获得对请求/响应的访问? - From a spring mvc controller action, how do I get access to request/response? AngularJs如何从Spring MVC控制器访问Model Attribute值 - AngularJs how to access Model Attribute value from Spring MVC controller Spring MVC - 如何使用控制器方法更新模型对象的属性? - Spring MVC - How do I update a model object's attributes using a controller method? 如何从 Spring MVC 中同一控制器中不同 JSP 页面上的表单访问值? - How do I access values from forms on different JSP pages in the same controller in Spring MVC? 如何使用Spring MVC 3在控制器中从模型中获取对象? - How can I get an object out of the model in the controller with Spring MVC 3? 如何使用Spring MVC从Java中的控制器而不是通过Web浏览器请求HTML视图? - How Do I Request an HTML View from a Controller in Java and not through a Web Browser using Spring MVC? Spring MVC 3:如何稳定地构造表单动作? - Spring MVC 3: How do I construct a form action restfully? 如何正确地将许多服务注入 Spring MVC 控制器? - How do I properly inject many services into Spring MVC controller? 如何在Spring MVC控制器内传递查询? - how do I pass a query within a spring mvc controller? 我如何使用Spring MVC无效控制器方法? - How do i use spring mvc void controller method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM