[英]Spring MVC form input value is always null
我是Spring MVC的新手,但对Java的Web开发并不陌生。 我正在尝试创建一个简单的form-> controller示例。
我有一个表单,一个表单控制器(在下面粘贴的上下文中配置)和我的模型(一个简单的bean)。 当我提交表单时,我的文本输入的值始终为null,无论如何。 有任何想法吗?
表格控制器弹簧配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- controllers -->
<bean name="/home.html" class="atc.web.view.controller.HomeController" />
<!--bean name="/mirror.html" class="atc.web.view.controller.MirrorController" -->
<bean name="/url-cache.html" class="atc.web.view.controller.URLCacheFormController">
<property name="synchronizeOnSession" value="true" />
<!--property name="sessionForm" value="false"-->
<property name="commandName" value="urlForm"/>
<property name="commandClass" value="atc.web.view.model.URLBean"/>
<property name="validator">
<bean class="atc.web.view.validators.URLValidator"/>
</property>
<property name="formView" value="mirror"/>
<property name="successView" value="url-cache.html"/>
<property name="URLCachingService" ref="urlCachingService" />
</bean>
<!-- end controllers -->
<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>
<!-- custom beans -->
<bean id="breakcrumbInjectionFilter" class="atc.web.view.filter.BreadcrumbInjectionFilter">
<property name="contextPrefix" value="/home-web" />
</bean>
<!-- end custom beans -->
</beans>
包含我的表单的JSP如下:
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ include file="/WEB-INF/jspf/core/taglibs.jspf" %>
<html>
<head><title>Simple tools</title></head>
<style>
.error s {
color:#FF0000;
}
</style>
<body>
<%@ include file="/WEB-INF/jspf/nav/nav.jspf" %>
Errors: <form:errors path="url" cssClass="error"/>
<form:form method="post" commandName="urlForm">
<form:input path="url" />
<input type="submit" align="center" value="Execute" />
</form:form>
</body>
</html>
这是我的控制器的完整源代码:
public class URLCacheFormController extends SimpleFormController {
private URLCachingService cachingService;
private static Logger log = Logger.getLogger(URLCacheFormController.class);
public ModelAndView onSubmit(Object command) throws ServletException {
log.debug(String.format("URLCachingFormController received request with object '%s'", command));
URLBean urlBean = (URLBean) command;
try {
URL url = new URL(urlBean.getUrl());
URLCache cache = cachingService.cacheURL(url);
cache.cacheToTempFile();
} catch (IOException e) {
log.error("Invalid URL...", e);
}
return new ModelAndView(new RedirectView(getSuccessView()));
}
protected Object formBackingObject(HttpServletRequest request) throws ServletException {
log.debug("formBackingObject() ");
return new URLBean();
}
public void setURLCachingService(URLCachingService cachingService) {
this.cachingService = cachingService;
}
}
以上所有产生以下HTML:
<html>
<head></head>
<body>
<div><span><a href="home.html">Home </a></span><span> | <a href="url-cache.html">Page Mirror</a></span></div>
<div id="breadcrumb"><span>Your trail:<a href=""/></span></div>Attrs:<div/>
<form id="urlForm" method="post" action="/home-web/url-cache.html">
<input id="url" type="text" value="" name="url"/>
<input type="submit" align="center" value="Execute"/>
</form>
</body>
</html>
我现在重写
doSubmitAction(Object command)
但我仍然没有按下该方法。
表单提交,但接下来我知道我提交了空白表单(在
formBackingObject(HttpServletRequest request)
之后)。
也就是说,当我提交时,表单控制器中
验证器执行并失败(正确添加错误消息),因为它检查的值始终为null (或者正确放置,它永远不会设置) 。 但是,总是会发生对doSubmitAction
第1行的日志记录调用永远不会执行。
formBackingObject
的调用。 我的表单的请求属性(表单输入'url')始终为null。
更新:好的,所以经过serg555建议的一些严肃的调试,并删除验证,我可以确认问题似乎是将请求参数 - 例如表单中'url'的值 - 映射到我的命令/ bean; 即,永远不会在我的bean上设置URL,或者正在重新创建bean。
请帮忙?
我不知道问题出在哪里,让我告诉你我的控制器是否有效,也许你可以弄清楚出了什么问题:
public class TestController extends SimpleFormController {
public TestController () {
setFormView("testView");
setSuccessView("testView");
setCommandClass(TestCmd.class);
setCommandName("cmd");
}
protected Object formBackingObject(HttpServletRequest request)throws Exception {
Object o = super.formBackingObject(request);
TestCmd cmd = (TestCmd) o;
return cmd;
}
public ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj, BindException errors) throws Exception {
TestCmd cmd = (TestCmd) obj;
log.debug("test value = " + cmd.getTestValue());
return super.onSubmit(request, response, obj, errors);
}
}
形成:
<form method="post" action="/test.html">
<form:input path="cmd.testValue"/>
<input type="submit">
</form>
在App-servlet.xml中:
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="alwaysUseFullPath" value="true" />
<property name="mappings">
<props>
<prop key="/test.html">testController</prop>
</props>
</property>
</bean>
<bean id="testController"
class="com.sample.TestController">
<property name="synchronizeOnSession" value="true" />
<property name="validator">
<bean class="com.sample.TestValidator"/>
</property>
</bean>
验证器:
public class TestValidator implements Validator {
public boolean supports(Class clazz) {
return (TestCmd.class.equals(clazz));
}
public void validate(Object obj, Errors errors) {
TestCmd cmd = (TestCmd) obj;
if (obj == null) {
// nothing
} else {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "testValue", null, "<b>Value</b> is required");
}
}
}
命令:
public class TestCmd {
private String testValue;
public TestCmd() {
}
public String getTestValue() {
return testValue;
}
public void setTestValue(String testValue) {
this.testValue = testValue;
}
}
好的,您已经验证了控制器中的url集确实通过了JSP,这表明映射对命令bean是正确的。
还有一件事。 如果永远不会到达“onSubmit”代码,那么控制器可能会发现问题是否是表单提交。 将name属性添加到提交按钮可能会有所帮助,并覆盖“isFormSubmission”以检查该名称是否存在(即是否已单击提交按钮)。 如果是这样,isFormSubmission应该返回true。 (这不是必需的 - 默认情况下,控制器会假定任何POST请求都是表单提交 - 但如果它有助于您了解问题的更多信息,并且您将有一个解决方法,至少。)
原因是我的表单bean没有遵守Java Bean契约 - setter返回而不是void,因此无法与Spring匹配来调用。
尝试将以下代码放在aplication-context.xml中。 如果您的表单为encType = multipart / form-data,那么这可能是您的解决方案。
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10000000"/>
</bean>
还尝试从jsp页面中删除内容类型。 在我的情况下,这帮助了我...... !!
我曾经花了很多时间研究类似的问题。 最后我在Binder的初始化方法中发现了罪魁祸首:
@InitBinder
void allowFields(final WebDataBinder binder) {
binder.setAllowedFields("name");
}
此方法对允许绑定的字段设置限制。 并且所有其他字段保持未绑定,自然导致null
值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.