gpt4 book ai didi

java - 处理多种表单,Spring

转载 作者:行者123 更新时间:2023-12-01 17:06:39 25 4
gpt4 key购买 nike

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

最佳答案

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

您的 View (从您的/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>

您的 Controller :

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

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

关于java - 处理多种表单,Spring,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25268000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com