Spring 3 MVC: is it possible to have a spring form

2020-02-29 00:09发布

My question is, Is it necessary to have a 'commandName' binding for forms and 'path' bindings for inputs?

I have a work flow which needs users to select data from a series of ajaxy select boxes. So the form doesn't exactly map to any model directly. It seems rather pointless to add another model just to accommodate this form, while everything on this form will be driven by ajax. Now I know I can always write a classic form and select tags, but I would like to take advantage of spring tags here for example:

<form:options items="${list}" itemLabel="name" itemValue="id"/>

which allows me to easily populate by form items. And plus I would like to maintain uniformity in the project and use spring tags through.

I would like to know thoughts and opinions on this topic.

Thanks!

PS: I am coming from ruby on rails background and am used to lot of syntactic sugar :P forgive me if the question sounds silly or answer obvious.

2条回答
Evening l夕情丶
2楼-- · 2020-02-29 00:34

I don't know if it's useful, but here it goes:

If you don't set a 'commandName' in the form, the default value for this property will be set as 'command'. So, if you don't set it, the bound data will have the name 'command'.

If you want, you can set it with the name of your bound data.

==========================================================================

A solution without using data binding would be:

I would add a HttpServletRequest request parameter to the controller method and get the parameter like servlets do.

@Controller 
public class SomeController {

    @RequestMapping(value = "/formAction", method = RequestMethod.POST)
    public String controllerMethod(HttpServletRequest request){  
        // this way you get value of the input you want
        String pathValue1 = request.getParameter("path1");
        String pathValue2 = request.getParameter("path2");
        return "successfulView";
    }

}

PS.: the 'path1' and 'path2' are the path names you set in the inputs. I know it seems do not use the Spring properly, but its a hack that Spring let us to use.

The form would be this way:

<form:form method="post" action="/formAction">
    <form:input path="path1" />
    <form:input path="path2" />
    <input type="submit" value="Submit"/>
</form:form>

Hope its useful.

查看更多
SAY GOODBYE
3楼-- · 2020-02-29 00:44

If we are not adding the commandName to spring form tags an exception willl be raised as
IllegalStateException: Neither BindingResult nor plain target object "command" available as request parameter...

查看更多
登录 后发表回答