【问题标题】:Spring Boot RESTful application errorSpring Boot RESTful 应用程序错误
【发布时间】:2017-03-17 22:28:29
【问题描述】:

我正在开发一个简单的 Spring Boot RESTful 应用程序,除了列出所有客户(从 Mongodb 中检索所有客户)之外,一切都很好。使用我当前的代码,我应该能够检索所有客户。

每次我在浏览器中输入http://localhost:8080/customers 时都会出错。

来自我的 Java 类 CustomerRestController:

@CrossOrigin
    @GetMapping("/customers")
    public ArrayList<Customer> getCustomers()
    {
        customerDAO = new CustomerDAO();
        return customerDAO.getCustomers();
    }

function showAll()
            {
                $("#persons").html("");

                $.getJSON("http://localhost:8080/customers/",  function(data)
                {
                    for (var i in data) {
                        $('#persons').append("<p>ID: " + data[i].id + "</p>")
                        $('#persons').append("<p>First name: " + data[i].firstName + "</p>")
                        $('#persons').append("<p>Last name: " + data[i].lastName + "</p><br>")
                    }
                });
            }

我班级 CustomerDAO 的一部分:

public class CustomerDAO 
{
    private ArrayList<Customer> customers;

    public CustomerDAO()
    {
        customers = new ArrayList();

    }

    public ArrayList<Customer> getCustomers()
    {
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        MongoDatabase database = mongoClient.getDatabase("testdb");

        MongoCollection<Document> col = database.getCollection("customers");

        MongoCursor<Document> cur = col.find().iterator();

        while(cur.hasNext())
        {
            Document doc = cur.next();
            List list = new ArrayList(doc.values());

            customers.add(new Customer((int) Float.parseFloat(list.get(1).toString()), list.get(2).toString(), list.get(3).toString()));   
        }

        mongoClient.close();

        return customers;
    }}

我收到此错误:

Whitelabel Error Page
    This application has no explicit mapping for /error, so you are seeing this as a fallback.
    Fri Mar 17 23:48:40 EET 2017
    There was an unexpected error (type=Internal Server Error, status=500).
    For input string: "com.myproject.model.Customer"

【问题讨论】:

  • 您能分享一下您的 CustomerDAO 课程吗?
  • 看起来list.get(1).toString() 返回字符串com.myproject.model.Customer,而不是浮点数。也许您错过了 List 索引是从零开始的,实际上意味着 Float.parseFloat(list.get(0).toString())
  • 我不认为这是一个索引问题。我试过你的建议,下面的答案都没有解决这个问题:(

标签: java spring mongodb spring-mvc


【解决方案1】:

您的代码略有错误。更新以下行:

$.getJSON("http://localhost:8080/customers/",  function(data)

到以下:

$.getJSON("http://localhost:8080/customers",  function(data)

ReST 端点中的 url http://localhost:8080/customershttp://localhost:8080/customers/ 之间存在差异。

【讨论】:

  • 我尝试了你的建议。不幸的是它没有修复错误:) ?
猜你喜欢
  • 2017-05-10
  • 2020-09-12
  • 2018-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多