java - Spring MVC 表单输入值始终为空

标签 java spring jakarta-ee spring-mvc

我是 Spring MVC 的新手,但不是 Java 网络开发的新手。我正在尝试创建一个简单的 form->controller 示例。

我有一个表单、一个表单 Controller (在下面粘贴的上下文 XML 中配置)和我的模型(一个简单的 bean)。当我提交表单时,无论如何,我的文本输入值始终为空。有什么想法吗?

表单 Controller Spring 配置:

<?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>

这是我的 Controller 的完整源代码:

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) 之后)。

也就是说,当我提交时,表单 Controller 中 doSubmitAction 第 1 行的日志记录调用永远不会执行。 validator 执行,但失败(正确添加错误消息)因为它检查的值始终为 null (或正确放置,它从未设置)。但是,总是会调用 formBackingObject。我的表单的请求属性(表单输入“url”)始终为空。

更新: 好的,在按照 serg555 的建议进行一些认真的调试并删除验证之后,我可以确认问题似乎与映射请求参数有关 - 例如“url”的值从表单到我的命令/bean;即从未在我的 bean 上设置 URL,或者正在重新创建 bean。

请帮忙?

最佳答案

我不知道问题出在哪里,让我给你看我的 Controller ,也许你能找出问题所在:

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>

validator :

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;
    }

}

关于java - Spring MVC 表单输入值始终为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1052594/

相关文章:

java - 理解 xml 模式定位

Spring HandlerMethodArgumentResolver 未执行

java - Spring boot - 无法使用@Value注释

java - 静态 HTML 页面的 Spring View 解析器

java - 如何在等效的 Scala 中转换 Java foreach 循环?

java - 注入(inject)调用者 IP 地址和端口在 Java Jersey RESTful Web 服务中不起作用

java - 如何在 android studio 中使用我的应用程序在字符串数组中添加更多字符串

java - 如何在 Intellij 中使用 Tomcat 8?

java - JPA REQUIRES_NEW 事务到底什么时候提交

jsf - 我应该使用 URL 作为图像和其他资源的链接,还是应该使用 EL #{resource...}