处理多种表单,Spring

ZZ *_*Z 5 1 java spring spring-mvc

我想问您使用不同方法处理同一页面上的多个表单的最佳方法是什么(如果可能的话)?让我解释一下:我有一个包含三种表单的页面。将请求映射路径设置为“foo”并发布方法后,它们将全部由一种方法处理。有没有办法用method1处理form1,用method2处理form2等等?

m4r*_*tin 5

您可能知道,HTML 表单被提交到由 action 属性指定的 URL,因此您可以轻松地将不同的处理程序方法分配给不同的 URL,以便每个方法都可以处理特定的表单。例子 :

您的视图(从您的 /foo URL 访问):

<html>
<head>
    <!-- bla bla bla -->
</head>

<body>

    <form>
        <!-- without any action specified, forms are submitted to the same URL -->
    </form>

    <form action="?bar2">
        <!-- 2nd form to be handled by method2 -->
    </form>

    <form action="?bar3">
        <!-- 3rd form to be handled by method3 -->
    </form>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

您的控制器:

@Controller
@RequestMapping("/foo")
public class MyController {

    @RequestMapping
    public void method1(/* anything you want Spring MVC to get for you like form1 backing bean for example */) {
        // handling form1 submission
    }

    // form action attribute must have a "bar2" query param somewhere
    @RequestMapping(params = "bar2") 
    public void method2(/* anything regarding form2 this time */) {
        // handling form2 submission
    }

    @RequestMapping(params = "bar3") 
    public void method3(/* anything regarding form3 this time */) {
        // handling form3 submission
    }
}
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,问题是使用一个区分因素,无论它是什么(这里我使用了一个查询参数),让 Spring 知道应该在哪里处理表单提交。如果 2 个处理程序方法映射到同一个 URL,Spring 将引发异常(在运行时),因此您必须使用一个异常(理想情况下是一个有意义的方法,但有时它的存在只是为了从同一根 URL 处理多个表单,这里是“/foo”)。