在SpringMVC中,将对象从HTML页面移动到JSP可以通过以下步骤实现:
具体步骤如下:
<form action="/submitForm" method="post">
<input type="text" name="name" placeholder="Name">
<input type="text" name="email" placeholder="Email">
<input type="submit" value="Submit">
</form>
@Controller
public class UserController {
@PostMapping("/submitForm")
public ModelAndView submitForm(@RequestParam("name") String name, @RequestParam("email") String email) {
User user = new User(name, email);
ModelAndView modelAndView = new ModelAndView("userDetails");
modelAndView.addObject("user", user);
return modelAndView;
}
}
或者使用@ModelAttribute注解:
@Controller
public class UserController {
@PostMapping("/submitForm")
public ModelAndView submitForm(@ModelAttribute("user") User user) {
ModelAndView modelAndView = new ModelAndView("userDetails");
modelAndView.addObject("user", user);
return modelAndView;
}
}
@Controller
public class UserController {
@PostMapping("/submitForm")
public ModelAndView submitForm(@ModelAttribute("user") User user) {
ModelAndView modelAndView = new ModelAndView("userDetails");
modelAndView.addObject("user", user);
return modelAndView;
}
}
<!DOCTYPE html>
<html>
<head>
<title>User Details</title>
</head>
<body>
<h1>User Details</h1>
<p>Name: ${user.name}</p>
<p>Email: ${user.email}</p>
</body>
</html>
这样,当用户提交表单后,后端控制器会将用户输入的数据封装到一个Java对象中,并将该对象传递给JSP页面进行展示。
推荐的腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云