温馨提示×

SpringMVC中如何实现表单提交

小亿
83
2024-04-18 15:46:12
栏目: 编程语言

在SpringMVC中实现表单提交,通常需要以下步骤:

  1. 创建一个表单页面,在表单页面中使用HTML表单元素构建需要提交的表单数据。

  2. 创建一个处理表单提交的Controller类,使用@Controller@RestController注解标识该类,并使用@RequestMapping注解指定处理请求的URL路径。

  3. 在Controller类中创建一个处理表单提交的方法,使用@PostMapping注解标识该方法,并使用@RequestParam注解获取表单提交的数据。

  4. 在处理表单提交的方法中可以使用Model对象将表单数据传递到视图页面。

  5. 在表单页面中可以使用Thymeleaf或JSP等模板引擎来展示处理后的数据。

下面是一个简单的示例:

  1. 表单页面(index.html):
<!DOCTYPE html>
<html>
<head>
    <title>Form Submit</title>
</head>
<body>
    <form action="/submitForm" method="post">
        <input type="text" name="username" placeholder="Username">
        <input type="password" name="password" placeholder="Password">
        <button type="submit">Submit</button>
    </form>
</body>
</html>
  1. Controller类(FormController.java):
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class FormController {

    @RequestMapping("/form")
    public String showForm() {
        return "index";
    }

    @PostMapping("/submitForm")
    public String submitForm(@RequestParam String username, @RequestParam String password, Model model) {
        model.addAttribute("username", username);
        model.addAttribute("password", password);
        return "result";
    }
}
  1. 结果页面(result.html):
<!DOCTYPE html>
<html>
<head>
    <title>Form Result</title>
</head>
<body>
    <h1>Form Submitted</h1>
    <p>Username: ${username}</p>
    <p>Password: ${password}</p>
</body>
</html>

在这个示例中,用户在表单页面输入用户名和密码后点击提交按钮,表单数据会被提交到/submitForm路径,FormController类中的submitForm方法会处理表单提交,并将表单数据传递到结果页面result.html中展示给用户。

0