在SpringMVC中实现表单提交,通常需要以下步骤:
创建一个表单页面,在表单页面中使用HTML表单元素构建需要提交的表单数据。
创建一个处理表单提交的Controller类,使用@Controller或@RestController注解标识该类,并使用@RequestMapping注解指定处理请求的URL路径。
在Controller类中创建一个处理表单提交的方法,使用@PostMapping注解标识该方法,并使用@RequestParam注解获取表单提交的数据。
在处理表单提交的方法中可以使用Model对象将表单数据传递到视图页面。
在表单页面中可以使用Thymeleaf或JSP等模板引擎来展示处理后的数据。
下面是一个简单的示例:
表单页面(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>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;@Controllerpublic 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"; }}结果页面(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中展示给用户。




