我正在使用Spring Boot 2.1.2 ...
我想知道在Spring Boot中是否存在现有概念或功能来为具有CrudRepository的常见实体创建通用添加或编辑页面? 我想省略一遍又一遍地编写所有样板代码,以在thymeleaf中添加或编辑页面,而改用通用页面。
所以我想做的是这样的通用形式:
<form action="#" th:action="@{/edit-$entityName}" th:object="${entity}" method="post">
<input type="hidden" th:field="*{id}" id="id"/>
<!-- iterating over each field and creating an input form element -->
<div class="form-group" th:each="field: ${fields}">
<label for="${field}" th:text="${field}"/>
<input type="text" th:value="${entity['name']}" th:attr="id=#{${field}}, placeholder=#{$field}" class="form-control">
<span th:if="${#fields.hasErrors($field)}" th:errors="*{$field}"></span>
</div>
<button type="submit" class="btn btn-default">save</button>
</form>
使用添加字段的控制器:
@Controller
public class EntityController {
@Autowired
private EntityService service;
@RequestMapping("/edit-entity/{id}")
public String editProject(Map<String, Object> model, @PathVariable("id") Integer id) {
Optional<MyEntity> byId = service.getById(id);
model.put("entity", byId.orElse(new MyEntity()));
model.put("entityName", "myEntity");
List<String> fields = new ArrayList<>();
for (Field field : MyEntity.class.getDeclaredFields()) {
if (!field.getName().equals("id"))
fields.add(field.getName());
}
model.put("fields", fields);
return "edit-page";
}
}
详细信息: 我有一个简单的实体“用户”
@Entity
@Table(name = "user_tbl")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
private String email;
private int age;
public User() {
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
要添加或编辑此用户实体,我创建了以下表单(省略了该表单的控制器代码和一些标记):
<form action="#" th:action="@{/edit-user}" th:object="${user}" method="post">
<input type="hidden" th:field="*{id}" id="id"/>
<div class="form-group">
<label for="name">Name</label>
<input type="text" th:field="*{name}" id="name" placeholder="Name" class="form-control">
<span th:if="${#fields.hasErrors('name')}" th:errors="*{name}"></span>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" th:field="*{email}" id="email" placeholder="email" class="form-control">
<span th:if="${#fields.hasErrors('email')}" th:errors="*{email}"></span>
</div>
<div class="form-group">
<label for="age">Alter</label>
<input type="text" th:field="*{age}" id="age" placeholder="age" class="form-control">
<span th:if="${#fields.hasErrors('age')}" th:errors="*{age}"></span>
</div>
<button type="submit" class="btn btn-default">save</button>
</form>
如果我要创建另一个实体anotherUser,我要复制粘贴所有这些内容,并且可能会更改某些名称或字段或其他内容,但是它们彼此完全相同...
是否有办法一次执行此操作,并将其重新用于我将定义的所有其他实体?