How to pass a hidden value in a form in Spring MVC 3.0?

假如想象 提交于 2019-12-08 15:27:46

问题


How to pass a hidden value in a form in Spring MVC 3.0

I am not able to assign a value to a hidden field using <form:hidden path="test" />. How can I set the value of the test field and access it on the server side.

thanks


回答1:


<form:hidden path="test"  style="display:none"/>



回答2:


It is oblibiuos that besides a hidden tag you also have a form like this:

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<form:form action="/someAction" commandName="formBeanName" method="post">]
    <%--
        there you set needed properties
     --%>
    <form:hidden path="test" />
</form:form>

Notice that the "formBeanName" is attribute name of java class, that was stored in HttpServletRequest, so you can simple use it as a bean! Also do not forget to add setter and getter to your secret property.

<%--Set you secret property there--%>   
<jsp:setProperty name="formBeanName" property="test" value="sercret"/>

<form:form action="/someAction" commandName="formBeanName" method="post">]
    <%--
        there you set needed properties
     --%>
    <form:hidden path="test" />
</form:form>

public class FormBean {

    //other fileds

    private String test;

    public String getTest(){
        return this.test;
    }

    public String setTest(Strign test){
        return this.test = test;
    }
}

P.S. I tested this with Spring 3.1

UPDATED: This example works unstable. I do know why, but sometimes it set property, somewhere no. If you have two spring forms in one jsp this approach can set property for first and not set for second or vice versa. May be because jsp:setProperty work after spring forms tag, may be not.




回答3:


Often people wrongly pass some values as hidden to form, because they cannot otherwise set those fields in update to previous values. E.g If I don't pass some values while updating to the form, those fields become null. However this is wrong way to update values. There is

@SessionAttributes("Rules")

to do that. After you update, you can set the session to complete using (SessionStatus status) parameter and status.setComplete() after the update is done. If you want to get some values that is not in model you can always use request.getParameter("yourinputname"); You can use

input type="hidden"

to set some values if you want to use in some parts like javascript (if using

${somevalueIdontwanttoshow}

does not work).

And if you really want to access the hidden filed try using

request.getParameter("yourfiedl")

before looking at binding errors.



来源:https://stackoverflow.com/questions/5338469/how-to-pass-a-hidden-value-in-a-form-in-spring-mvc-3-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!