简体   繁体   English

Spring:将带有数据的对象从控制器传递到jsp,并从Spring Form Submit取回预先保存的数据

[英]Spring: pass object with data from controller to jsp and get the pre-saved data back from Spring Form submit

I am sorry if the title sounds confusing, I am a Spring newbie. 如果标题听起来令人困惑,对不起,我是Spring新手。

I have a controller class called AdController and I pass an Ad object to jsp in ModelAndView: 我有一个称为AdController的控制器类,并将Ad对象传递给ModelAndView中的jsp:

    ModelAndView laView = new ModelAndView("/ad/adAdd3");
    Ad laAd = new Ad();
    laAd.setPrice(100);
    model.put("ad", laAd);

In my adCreate.jsp, I allow user to add more info about this Ad except the price. 在我的adCreate.jsp文件中,我允许用户添加有关此广告的更多信息(价格除外)。 And use a to submit the Ad object to the backend, my Controller class: 并使用将Ad对象提交到后端,即我的Controller类:

 <form:form modelAttribute="ad" method="post" class="form-horizontal" id="add-ad-form">

The problem is that on the back end, I received everything that's added by the user except price. 问题是在后端,我收到了除价格之外用户添加的所有内容。 Should I be getting the price data from the form submit? 我应该从表单提交中获取价格数据吗? Am I missing anything? 我有什么想念的吗?

Thanks! 谢谢!

Spring MVC is stateless, so in your controller you get only what is sent from the client. Spring MVC是无状态的,因此在您的控制器中,您只会获得从客户端发送的内容。 You need to include the price in the form for it to be sent to the server (you can make the field hidden to prevent the user from changing it). 您需要在price中包含price以将其发送到服务器(您可以隐藏该字段以防止用户更改价格)。 However, this will not prevent someone from manually sending the price with all other data (one just needs to change html code a little), so you need to handle this on the server side as well. 但是,这不会阻止某人手动将价格与所有其他数据一起发送(一个人只需要稍微更改html代码),因此您也需要在服务器端进行处理。

Spring MVC creates a new instance of your Ad object based upon the parameters in the request. Spring MVC根据请求中的参数创建广告对象的新实例。 So if the price value doesn't have a HTML input in the generated form then the value won't be populated in this new instance. 因此,如果价格值在生成的表单中没有HTML输入,则该值不会在此新实例中填充。

You can use the <form:hidden path="price"/> tag to pass the value back from the form. 您可以使用<form:hidden path="price"/>标记将值从表单传回。

If you look at the source of the HTML page you should see that this adds <input type="hidden" name="price" value="100"/> to the page. 如果查看HTML页面的源代码,应该会看到这会在页面上添加<input type="hidden" name="price" value="100"/>

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM