【发布时间】:2017-09-26 14:04:51
【问题描述】:
我正在按照教程尝试在 Spring 中使用 DataTables。但是当我请求该页面时,它会以 JSON 格式返回数据,并且不会在 HTML 文件的表格中显示它们。 到目前为止,这是我的代码: 我有一个用户模型类:
@Entity
@Id
@GeneratedValue
@Column(name="id")
private long id;
@Column(name="name")
private String name;
@Column(name="last_name")
private String lastName;
@Column(name="email")
private String email;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
我创建了一个 UsersRepository 如下:
@Repository("usersRepository")
public interface UserRepository extends JpaRepository<User, Long>{}
我有服务层和具有两个功能的实现:getAllUsers 和 getUsersById()
这是html文件:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<table id="example" class="table display dt-responsive nowrap table-bordered table-striped">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Id</th>
<th>Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
</tfoot>
</table>
</html>
datatable.js 文件如下:
$(document).ready( function () {
var table = $('#example').DataTable({
"sAjaxSource": "/user/users",
"sAjaxDataProp": "",
"order": [[ 0, "asc" ]],
"aoColumns": [
{ "mData": "id"},
{ "mData": "name" },
{ "mData": "lastName" },
{ "mData": "email" }
]
})
});
这是@RestController:
@RestController
public class UserRestController {
@Autowired
private UserService userService;
@RequestMapping(path="user/users", method=RequestMethod.GET)
public List<User> getAllUsers(){
return userService.getAllUsers();
}
@RequestMapping(value = "user/users/{id}", method = RequestMethod.GET)
public User getUserById(@PathVariable("id") long id){
return userService.getUserById(id);
}
}
当我转到 localhost:8080/user/users 时,它返回数据库中的用户,而不是表中的用户。 有什么我遗漏的吗,有什么步骤吗?任何帮助将不胜感激
【问题讨论】:
-
您的代码似乎没问题,您可以检查和响应两点。谢谢
-
我得到了响应,但没有在数据表中。它不会以它所拥有的设计打开用户站点。
-
我发布的代码只有你的代码才有效。
-
你可以在stackoverflow.com/a/68456824/3793165看到我使用的方式
标签: jquery spring-boot datatable