作为参考,我一直在使用这个: http://www.mkyong.com/spring-mvc/spring-mvc-form-handling-example/
基本上,我有一个名为EJournalValidator.java的课程:
package com.blah.blah.validator;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.blah.blah.EJournalForm;
public class EJournalValidator implements Validator{
public boolean supports(Class clazz) {
return EJournalForm.class.isAssignableFrom(clazz);
}
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "strStartDate",
"ejournal.strStartDate", "Field name is required.");
}
}
它映射到我的servlet.xml中的控制器,其中包含我的spring 2.5 beans列表中的一些重要方面:
<bean name="/app/eJournal.html" class="com.blah.blah.EJournalController">
<property name="formView" value="/app/eJournal"/>
<property name="validator">
<bean class="com.blah.blah.EJournalValidator" />
</property>
</bean>
<bean name="/app/eJournalResult.html" class="com.blah.blah.EJournalResultController"></bean>
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>/WEB-INF/messages/message</value>
</list>
</property>
</bean>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
它验证了我的表单中的搜索条件,由我们的模型.java文件和用于表单加载和提交的控制器(对于我们showForm()和handleRequest())表示。麻烦的是,我的观点似乎没有更新我的标签在我的.jsp中的位置:
<td><form:input id="strStartDate" path="strStartDate"/></td>
<td><form:errors path="strStartDate" cssClass="error" /></td>
不幸的是,即使我知道,当我通过EJournalValidator.java文件中的断点为此字段提交null时,错误也会被正确标记,错误未在视图中更新。知道为什么会这样吗?有人说如果你使用类似的东西重定向:
return "redirect:/spring/person/list";
那么这可能导致类似这样的事情,但这似乎并非如此。
在调试中,如果我在EJournalValidator.java的验证方法中设置断点并在我尝试在字段中提交空白时检查了错误变量,则会发现这些错误:
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult:1个错误 对象&#39; ej&#39;中的字段错误on field&#39; strStartDate&#39 ;:拒绝值[]; 代码 [ejournal.strStartDate.ej.strStartDate,ejournal.strStartDate.strStartDate,ejournal.strStartDate.java.lang.String,ejournal.strStartDate]; 参数[];默认消息[需要字段名称。]
调试时发现错误的原因是什么?用户不会看到?
编辑:添加Controller handleRequest方法,以防需要知道。
protected ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
EJournalForm form = (EJournalForm) command;
form.setUser(getUser());
form.load(request, false);
HttpSession session = request.getSession(false);
session.setAttribute(LBIBOConstants.SESSION_VAR_TAB_ALERT_MSG, null);
return new ModelAndView(getFormView(), getCommandName(), form);
}
编辑2 :从SimpleFormController添加片段,这似乎是它所坚持的内容。它永远不会访问我的Controller的handleRequest()方法,除非它检查时没有错误:
protected ModelAndView processFormSubmission(
HttpServletRequest request, HttpServletResponse response, Object command, BindException errors)
throws Exception {
if (errors.hasErrors()) {
if (logger.isDebugEnabled()) {
logger.debug("Data binding errors: " + errors.getErrorCount());
}
return showForm(request, response, errors);
}
else if (isFormChangeRequest(request, command)) {
logger.debug("Detected form change request -> routing request to onFormChange");
onFormChange(request, response, command, errors);
return showForm(request, response, errors);
}
else {
logger.debug("No errors -> processing submit");
return onSubmit(request, response, command, errors);
}
}
我注意到了更多...因为这个我将覆盖我的Controller方法,但意识到我正在扩展SessionSimpleFormController而不是SimpleFormController。现在考虑一下,为什么一个人会扩展其中一个,因为我基于其他人的工作,然后在上面显示的链接中注意到他们使用的是SimpleFormController。
答案 0 :(得分:1)
如果验证期间发生错误,请更改handleRequest方法以返回现有表单/模型对象。当您返回新的ModelAndView时,它会清除错误,因此您不会在视图中看到它们。尝试使用RedirectView重定向到同一视图,而不会丢失绑定到表单/模型的错误:
protected ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
EJournalForm form = (EJournalForm) command;
form.setUser(getUser());
form.load(request, false);
HttpSession session = request.getSession(false);
session.setAttribute(LBIBOConstants.SESSION_VAR_TAB_ALERT_MSG, null);
if(errors.hasErrors()){
return new ModelAndView(new RedirectView(getFormView()));
}else{
return new ModelAndView("anotherView", "commandName", form);
}
}
从Spring 3+开始,不推荐使用getFormView()和getCommandName()。
答案 1 :(得分:0)
我确实解决了这个问题,最后我开始使用SimpleFormController而不是SessionSimpleFormController,并改变了一些事情。
最后,它看起来像这样......但也许还有办法让它与Session控制器一起工作。
public class EJournalController extends SimpleFormController {
public EJournalController() {
setCommandClass(EJournalForm.class);
setCommandName("ej");
}
@Override
protected ModelAndView showForm (HttpServletRequest request,
HttpServletResponse response, BindException errors) throws Exception {
Calendar cal = Calendar.getInstance();
Calendar calMidnight= Calendar.getInstance();
calMidnight.set(Calendar.HOUR_OF_DAY, 0);
calMidnight.set(Calendar.MINUTE, 0);
calMidnight.set(Calendar.SECOND, 0);
HttpSession session = request.getSession(true);
ModelAndView view = null;
LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
localeResolver.setLocale(request, response, LocaleUtilities.getUsersLocale(session));
EJournalForm form = new EJournalForm();
view = new ModelAndView(getFormView(), getCommandName(), form);
form.setStrStartDate(form.getSdfDate().format(cal.getTime()).toString());
form.setStrEndDate(form.getSdfDate().format(cal.getTime()).toString());
form.setStrStartTime(form.getSdfTime().format(calMidnight.getTime()).toString());
form.setStrEndTime(form.getSdfTime().format(cal.getTime()).toString());
return view;
}
protected ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
EJournalForm form = (EJournalForm) command;
if(errors.hasErrors()){
return onSubmit(request, response, command, errors);
}
else{
form.load(request, false);
HttpSession session = request.getSession(false);
session.setAttribute(LBIBOConstants.SESSION_VAR_TAB_ALERT_MSG, null);
return new ModelAndView("app/eJournal", "ej", form);
}
}
@Override
protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {
return handleRequest(request, response, command, errors);
}
}