【问题标题】:Spring boot Datatable returns data in JSON format but doesn't show them in the tableSpring boot Datatable 以 JSON 格式返回数据,但不显示在表中
【发布时间】: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


【解决方案1】:

检查两件事 1:您在 Datatable 中调用 /employees ,检查 Datatable 调用部分是否位于 HTML 底部的 body 标记之前。在运行测试代码下方。

在 src/main/webapp 中的 test.html

<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"
                      xmlns:th="http://www.thymeleaf.org">
<head>

    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
    <script type="text/javascript" language="javascript" src="//code.jquery.com/jquery-1.12.4.js">
    </script>
    <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>


</head>
<body>

<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>
<script>
    /*$(document).ready(function() {
        $('#example').DataTable();
    } );*/

    $(document).ready( function () {
        var table = $('#example').DataTable({
            "sAjaxSource": "/user/users",
            "sAjaxDataProp": "",
            "order": [[ 0, "asc" ]],
            "aoColumns": [
                { "mData": "id"},
                { "mData": "name" },
                { "mData": "lastName" },
                { "mData": "email" }

            ]
        })
    });

</script>
</body>
</html>

用户休息控制器

package com.vaibs.controller;

import com.vaibs.jpaExample.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created by polo on 26-09-2017.
 */
@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);
    }
}

用户服务[模拟]:

package com.vaibs.controller;


import com.vaibs.jpaExample.entity.User;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by polo on 26-09-2017.
 */

@Component
public class UserService {

    ArrayList<User> userList = new ArrayList<User> () {{
        User u1 = new User ();
        u1.setId (1L);
        u1.setName ("Vaibhav");
        u1.setLastName ("Khatke");
        u1.setEmail ("vaibs@outlook.com");
        User u2 = new User ();
        u2.setId (2L);
        u2.setName ("Saurabh");
        u2.setLastName ("Nakhe");
        u2.setEmail ("saurabh@outlook.com");
        User u3 = new User ();
        u3.setId (3L);
        u3.setName ("Mandar@outlook.com");
        u3.setLastName ("Jain");
        u3.setEmail ("mandar@outlook.com");


        add (u1);
        add (u2);
        add (u3);
    }};

    public List<User> getAllUsers () {
        return userList;
    }


    public User getUserById (long id) {
        for (User user : userList) {
            if (user.getId () == id) {
                return user;
            }
        }
        return null;
    }
}

用户: 包 com.vaibs.jpaExample.entity;

import javax.persistence.Entity;
import javax.persistence.Id;

/**
 * Created by polo on 26-09-2017.
 */
@Entity
public class User {

    @Id
    private long id;
    private String name;
    private String lastName;
    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;
    }
}

上面的代码示例可以是 Spring-boot/JPA 与 REST/Jquery/Datatable 的一个很好的例子

如果您的问题得到解决,请回复。

【讨论】:

  • 谢谢,但没有。我仍然得到这样的结果: {"id":1,"name":"Sarah","lastName":"User","email":"user@user.com"},{"id":2 ,"name":"User2","lastName":"User3","email":"user@user.com"] 它不会在数据表中显示它们。
  • 我实际上收到了关于请求的警告:资源解释为文档,但使用 MIME 类型应用程序/json 传输
  • 你需要在ajax部分指定然后你发送json
猜你喜欢
  • 2021-01-23
  • 2019-08-11
  • 1970-01-01
  • 2017-10-13
  • 2018-11-11
  • 1970-01-01
  • 2021-11-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多