gpt4 book ai didi

java - Spring 中的表单导航困惑

转载 作者:行者123 更新时间:2023-12-01 13:39:25 26 4
gpt4 key购买 nike

我正在开发一个 Spring 项目

请求从 Controller AddForm.java 转发到 Form.jsp,然后 onsubmit 从那里返回到同一个 Controller 。

下面的代码

表单.jsp

<%@ include file="/WEB-INF/view/include.jsp" %>
<%@ include file="/WEB-INF/view/header.jsp" %>
<c:choose>
<c:when test="${action eq 'addowner'}"><c:set var="method" value="post"/></c:when>
<c:otherwise><c:set var="method" value="put"/></c:otherwise>
</c:choose>

<h2><c:if test="${action eq 'addowner'}">New </c:if>Owner:</h2>
<form:form modelAttribute="owner" method="${method}">
<table>
<tr>
<th>
First Name:
<br/>
<form:input path="firstName" size="30" maxlength="80"/>
</th>
</tr>
<tr>
<th>
Last Name:
<br/>
<form:input path="lastName" size="30" maxlength="80"/>
</th>
</tr>
<tr>
<th>
Address:
<br/>
<form:input path="address" size="30" maxlength="80"/>
</th>
</tr>
<tr>
<th>
City:
<br/>
<form:input path="city" size="30" maxlength="80"/>
</th>
</tr>
<tr>
<th>
Telephone:
<br/>
<form:input path="telephone" size="20" maxlength="20"/>
</th>
</tr>
<tr>
<td>
<c:choose>
<c:when test="${action eq 'addowner'}">
<p class="submit"><input type="submit" value="Add Owner"/></p>
</c:when>
<c:otherwise>
<p class="submit"><input type="submit" value="Update Owner"/></p>
</c:otherwise>
</c:choose>
</td>
</tr>
</table>
</form:form>

<%@ include file="/WEB-INF/view/footer.jsp" %>

AddFormController代码

    @Controller
@RequestMapping("/owners/new")
@SessionAttributes(types = Owner.class)
public class AddOwnerForm {

private final Clinic clinic;


@Autowired
public AddOwnerForm(Clinic clinic) {
this.clinic = clinic;
}

@InitBinder
public void setAllowedFields(WebDataBinder dataBinder) {
dataBinder.setDisallowedFields("id");
}

@RequestMapping(method = RequestMethod.GET)
public String setupForm(Model model) {
Owner owner = new Owner();
model.addAttribute(owner);
model.addAttribute("action", "addowner");
return "owners/form";
}

@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@ModelAttribute Owner owner, SessionStatus status) {

System.out.println(owner.toString());
System.out.println("Inside AddOwner processSubmit method");
this.clinic.storeOwner(owner);
status.setComplete();
return "redirect:/forms/owners/" + owner.getId();

}

}

问题是在 Controller 中,setupForm方法将流程转发到jsp,但在jsp中,表单标记中没有给出任何操作,但在提交时流程返回到处理提交方法。谁能告诉我为什么?

最佳答案

如果您提交form没有action属性,浏览器通常向当前 URL 发出请求。例如,如果您之前向

发出了 GET 请求
www.yourhost.com/your-app/owners/new

然后提交<form>会将请求发送到相同的 URL。

<小时/>

我不确定这是在规范中还是只是约定。

关于java - Spring 中的表单导航困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20954358/

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