后方法后模型中的Spring MVC项目空值

时间:2019-03-14 15:31:43

标签: java html spring-mvc thymeleaf

  
    

当我启动页面并尝试将表单与post方法一起使用时,调试后,我看到所有模型字段都为空值。我在很多论坛上都读过,但是     无法解决问题

  
     

这是我的UserController类

@Controller
public class UserController {

   private UserService userService;


    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }


    @GetMapping("/add-user")
    public String addEmployeeForm(Model model) {
        model.addAttribute("user", new User());
        return "add-user";
    }

    @PostMapping("/add-user")
    public String addEmployee(@Valid @ModelAttribute (value = "user") User user, BindingResult bindingErrors) {
        if(bindingErrors.hasErrors()) {
            return "add-user";
        }
        userService.addUser(user);
        return "redirect:/add-user";
    }
  

还有我的add-user.html文件

   <!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Add Employee</title>
</head>
<body>
<form action="#" th:action="@{/add-user}" th:object="${user}" method="post">
    <ul>
        <li th:errors="*{userFirstName}" style="color: red"/>
        <li th:errors="*{userLastName}" style="color: red"/>
        <li th:errors="*{userName}" style="color: red"/>
        <li th:errors="*{userPassword}" style="color: red"/>
    </ul>
    <table>
        <tr>
            <td><label th:text="#{label.firstname}">First Name</label></td>
            <td><input type="text" th:field="*{userFirstName}"/></td>
        </tr>
        <tr>
            <td><label th:text="#{label.lastname}">Last Name</label></td>
            <td><input type="text" th:field="*{userLastName}"/></td>
        </tr><tr>
            <td><label th:text="#{label.username}">Username</label></td>
            <td><input type="text" th:field="*{userName}"/></td>
        <tr>
            <td><input type="submit" value="Save"/></td>
        </tr>
    </table>
</form>
</body>
</html>
  

这是我的存储库,具有连接到的方法“ add”   数据库,并为此存储库使用UserService

    @Override
public void add(User user) {
    try (Session session = sessionFactory.openSession()) {
        if (alreadyExists(user.getUserName())) {
            session.cancelQuery();
            throw new ResponseStatusException(HttpStatus.CONFLICT,
                    String.format("User with username %s already exists", user.getUserName()));
        }
        session.save(user);
    } catch (HibernateException he) {
        System.out.println(he.getMessage());
        throw he;
    }
}
  

您知道这是什么类型的问题吗?是否与数据库或类或html文件连接?

0 个答案:

没有答案