认为这很简单,但不知道如何处理它。
我有这样的表格。
<c:url value="edit" var="editprofileUrl" />
<form:form class="form" id="signup" action="${editprofileUrl}" method="post" modelAttribute="editProfileForm">
<div class="formInfo">
<s:bind path="*">
<c:choose>
<c:when test="${status.error}">
<div class="text-danger">Unable to change profile. Please fix the errors below and resubmit.</div>
</c:when>
</c:choose>
</s:bind>
</div>
<div class="form-group">
<label for="firstName">First name</label>
<form:errors path="firstName" cssClass="text-danger" />
<form:input class="form-control" path="firstName" />
</div>
<div class="form-group">
<label for="lastName">Last name</label>
<form:errors path="lastName" cssClass="text-danger" />
<form:input class="form-control" id="last-name" path="lastName" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Save profile</button>
</div>
</form:form>
这样的java形式:
public class EditProfileForm {
@NotEmpty
private String firstName;
@NotEmpty
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
这样的控制器:
@Controller
@Transactional
public class EditProfileController {
@PersistenceContext
private EntityManager entityManager;
@RequestMapping(value = "/users/{username}/edit", method = RequestMethod.POST)
public String editProfile(@PathVariable String username, Principal currentUser, @Valid EditProfileForm form, BindingResult formBinding) {
if (formBinding.hasErrors()) {
return null;
}
Account user = entityManager.find(Account.class, currentUser.getName());
user.setFirstName(form.getFirstName());
user.setLastName(form.getLastName());
entityManager.persist(user);
return "home";
}
@RequestMapping(value = "/users/{username}/edit", method = RequestMethod.GET)
public ModelAndView editProfileForm(@PathVariable String username, Principal currentUser, WebRequest request, Model model) {
Account account = entityManager.find(Account.class, username);
if (account != null) {
model.addAttribute("account", account);
}
EditProfileForm form = new EditProfileForm();
form.setFirstName(account.getFirstName());
form.setLastName(account.getLastName());
return new ModelAndView("editprofile", "editProfileForm", form);
}
}
除非我在其中一个字段中填写任何内容并且它应该给出错误,否则一切都很好。
此代码段中有一些内容:
if (formBinding.hasErrors()) {
return null;
}
不是再次使用错误返回同一页面,而是查找不存在的视图:
HTTP Status 404 - /project/WEB-INF/views/users/nilsi/edit.jsp
如何使用错误再次返回相同的视图?通常,当我有@RequestMapping
之类的/signup
时,它会有效。
感谢您提供任何帮助!
答案 0 :(得分:1)
如果发生绑定错误,请再次返回表单视图的名称,以便用户可以更正错误。
if (formBinding.hasErrors()) {
return "editprofile";
}
如果返回null,Spring会尝试通过查看URL来猜测视图名称。由于您的网址以“... / edit”结尾,因此会尝试加载edit.jsp。