出于某种原因,我似乎无法解决这个问题,即使在这里查看了多个示例。
我正在尝试使用 Spring 3 MVC 处理表单,但出现以下错误:
Neither BindingResult nor plain target object for bean name 'reverseString' available as request attribute
所以我有点明白这里的问题是什么,但我没能解决它。这是我的方法
扩展 SimpleFormController 的 ReverseController 类:
protected ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
ReverseString revString = (ReverseString) command;
ModelAndView mav = new ModelAndView();
ModelMap map = new ModelMap();
map.addAttribute("reverseString", revString);
mav.addAllObjects(map);
return mav;
}
我的 app-servlet.xml 将控制器定义如下:
<bean name="/reverse.app" class="ReverseController">
<property name="commandName" value="reverseString"></property>
<property name="commandClass" value="ReverseString" />
<property name="successView" value="reverseResult" />
<property name="formView" value="reverse" />
</bean>
这是我的 reverse.jsp 中的表单:
<form:form method="POST" modelAttribute="reverseString" action="handleForm">
<form:errors path="*" cssClass="errorblock" element="div" />
<table>
<tr>
<td>String to be reversed:</td>
<td><form:input path="stringToReverse" />
</td>
<td><form:errors path="stringToReverse" cssClass="error" />
</td>
</tr>
<tr>
<td colspan="3"><input type="submit" /></td>
</tr>
</table>
</form:form>
这就是我的 web.xml 中定义的内容:
<web-app>
<display-name>Spring Reverse String</display-name>
<welcome-file-list>
<welcome-file>reverse.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>app</servlet-name>
<servlet-class>Dispatcher</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>*.app</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/app-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
最后,这是我的 ReverseString 对象:
public class ReverseString {
public String stringToReverse;
public String reversedString;
public ReverseString(String rawString) {
this.reversedString = reverseString(stringToReverse);
}
public String getStringToReverse() {
return stringToReverse;
}
public void setStringToReverse(String stringToReverse) {
this.stringToReverse = stringToReverse;
}
public String reverseString(String rawString) {
if(rawString == null || rawString.length() <= 1) return rawString;
return reverseString(rawString.substring(1)) + rawString.charAt(0);
}
}