Spring Input value of MVC form is always zero

I am new to Spring MVC, but not new to Java web development. I am trying to create a simple example form-> controller.

I have a form, a form controller (configured in the XML context, inserted below) and my model (simple bean). When I submit the form, the value of my text input is always zero, regardless. Any ideas?

Spring form controller configuration:

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

The JSP containing my form is as follows:

<%@ 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>

Here is the full source of my 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;
    }
}

All of the above creates the following 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>

I am now redefining doSubmitAction(Object command), but I still haven't hit this method. The form is submitted, but the next thing I know is the empty form (after the call formBackingObject(HttpServletRequest request)).

, , 1 doSubmitAction . ( ), , , ( , ). formBackingObject . ( 'url') .

: , , serg555, , , , 'url' - / bean; .. URL- bean bean.

, ?

+3
5

, bean Java bean - , , , Spring .

+1

, , , , , , , :

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>

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

}
+2

, , URL-, , JSP, bean.

. "onSubmit" , , , . "isFormSubmission", , (, ). , isFormSubmission true. ( - , POST , , , .)

+1

aplication-context.xml. , encType = multipart/form-data.

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10000000"/>
</bean>

Also try removing the “Type” content from the jsp page. Well, in my case, it helped me ... !!

0
source

I spent a lot of time studying a similar problem. Finally, I found the culprit inside the Binder initialization method:

@InitBinder
void allowFields(final WebDataBinder binder) {
    binder.setAllowedFields("name");
}

This method sets a limit on the fields that are allowed for binding. And all other fields remain unconnected, which naturally leads to values null.

0
source

Source: https://habr.com/ru/post/1711397/


All Articles