【问题标题】:Cannot resolve 'name'无法解析“名称”
【发布时间】:2022-07-07 16:59:08
【问题描述】:

大家好,我目前正在使用 spring mvc、hibernate 和 thymeleaf 做一个 crud 应用程序。我正在尝试创建一个新用户,但编译器抱怨它无法识别名称字段,即使我在 User 类中有这个字段。可能是什么问题?

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>New User</title>
</head>
<body>
<form th:method="POST" th:action="@{/users}" th:object="${user}">
    <input type="text" th:field="*{name}" id="name">
</form>
</body>
</html>

用户类别:

package web.model;

import org.hibernate.annotations.GenericGenerator;

import javax.persistence.*;

@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @GenericGenerator(name = "increment", strategy = "increment")
    private int id;

    @Column(name = "name", nullable = false, length = 50)
    private String name;

    public User() {}

    public User(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public long getId() {
        return id;
    }
}

用户控制器:

package web.controller;

import jdk.internal.icu.text.NormalizerBase;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import web.model.User;
import web.service.UserService;

@Controller
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping
    public String listUsers(Model model) {
        model.addAttribute("users", userService.getAllUsers());
        return "users";
    }

    @GetMapping("/{id}")
    public String show(@PathVariable("id") int id, Model model) {
        model.addAttribute("user", userService.getUserById(id));
        return "show";
    }

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

    @PostMapping()
    public String create(@ModelAttribute("user") User user) {
        userService.add(user);
        return "redirect:/users";
    }
}

可能是什么问题?

【问题讨论】:

    标签: spring spring-mvc model-view-controller thymeleaf


    【解决方案1】:

    现在界面打开了吗?show userdao?

    【讨论】:

      猜你喜欢
      • 2017-05-30
      • 2020-05-01
      • 2016-06-23
      • 1970-01-01
      • 2022-12-11
      • 2022-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多