gpt4 book ai didi

java - Spring MVC表单提交: view to controller pass not put form attribute

转载 作者:行者123 更新时间:2023-11-30 08:06:18 25 4
gpt4 key购买 nike

我有一个 portlet,它能够显示表单,然后允许将用户设置的内容传递到对象中的 Controller 。而且效果很好。我只是希望应用程序能够从 jsp 设置附加属性,但不能从表单的输入中设置附加属性。

模型

public class Person {
String firstName;
String middleName;
String attributeSetStatically;

// Setters and getters

public void setAttributeSetStatically(String attributeFromJsp)
{
System.out.println("Call setAttributeSetStatically "+attributeFromJsp);
this.attributeSetStatically=attributeFromJsp;
}
}

Controller

@Controller(value = "MyFirstSpringMVCPortlet")
@RequestMapping("VIEW")
public class MyFirstSpringMVCPortlet {

@RenderMapping
public ModelAndView handleRenderRequest() {
ModelAndView modelAndView = new ModelAndView("welcome");
modelAndView.addObject("person", new Person());
modelAndView.addObject("msg", "Hello Spring MVC");
return modelAndView;
}


@ActionMapping(value = "handleSubmitPerson")
public void submitPerson(@ModelAttribute("person") Person person,ActionRequest actionRequest, ActionResponse actionResponse,Model model) {
System.out.println("FirstName= "+person.getFirstName());
System.out.println("MiddleName= "+person.getMiddleName());
System.out.println("attributeSetStatically= "+person.getAttributeSetStatically());
}

}

查看(welcome.jsp)

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<h1>${msg}</h1>
<portlet:defineObjects />
<portlet:actionURL var="submitFormURL" name="handleSubmitPerson"/>
<form:form name="person" method="post" modelAttribute="person" action="<%=submitFormURL.toString() %>">
${person.setAttributeSetStatically('attributeSetStatically of person')}
<br/>
<table style="margin-left:80px">
<tbody>
<tr>
<td><form:label path="firstName">First Name</form:label></td>
<td><form:input path="firstName"></form:input></td>
</tr>
<tr>
<td><form:label path="middleName">Middle Name</form:label></td>
<td><form:input path="middleName"></form:input></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit Form">
</td>
</tr>
</tbody>
</table>
</form:form>

我在控制台中得到的输出是:

FirstName= Kallel
MiddleName= Omar
attributeSetStatically= null
Call setAttributeSetStatically attributeSetStatically of person

所以这个 ${person.setAttributeSetStatically('attributeSetStatically of person')} 在提交后被调用。为什么?有没有办法做我想做的事?

最佳答案

attributeSetStatically 可以在表单内的隐藏输入中设置:

<form:input type="hidden" name="attributeSetStatically" value="attributeSetStatically of person">

关于java - Spring MVC表单提交: view to controller pass not put form attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31046665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com