首页 > 解决方案 > GET 客户请求上带有 resttemplate Whitelabel 错误页面的 SpringREST API

问题描述

大家好,目前正在使用来自 swagger 的 api,但我得到一个可白标的错误页面这是我的客户 APIservice 包服务;

    import java.net.URI;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import domains.Customers;


@Service
public class CustomersApiService {

//  define a RestTemplate object
private final RestTemplate restTemplate;


//  web service resources endpoints
private final String GET_ALL_USER = 
"https://api.predic8.de/shop/customers/";


 //  define an argument constructor, then pass in the RestTemplate object 
   and  
Autowire it
@Autowired
public CustomersApiService (RestTemplate restTemplate){
    this.restTemplate = restTemplate;
}

//  Get All Users
//  @returns a list
@SuppressWarnings("unchecked")
public List<Customers> findAllCustomers(){



   return Arrays.stream(restTemplate.getForObject
(GET_ALL_USER,Customers[].class)).collect(Collectors.toList());
}

}

这是我的客户控制器包控制器;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import services.CustomersApiService;

@Controller
public class CustomersController {

private final CustomersApiService service;

@Autowired
public CustomersController(CustomersApiService service) {
    this.service = service;
}

@GetMapping("/customers")
public String getAll(Model model){
    model.addAttribute("customers", service.findAllCustomers());
    return "customers";
}

这是我的客户 POJO 包域;

import java.util.HashMap;
import java.util.Map;

public class Customers {

private String firstname;
private String lastname;
private String customerUrl;
private Map<String, Object> additionalProperties = new HashMap<String, 
Object>();

public String getFirstname() {
return firstname;
}

public void setFirstname(String firstname) {
this.firstname = firstname;
}

public String getLastname() {
return lastname;
}

public void setLastname(String lastname) {
this.lastname = lastname;
}

public String getCustomerUrl() {
return customerUrl;
}

public void setCustomerUrl(String customerUrl) {
this.customerUrl = customerUrl;
}

public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}

}

这是客户档案

<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org/">
<head>
<meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Users</title>
 <!-- Bootstrap core CSS -->
<link href="..static/css/bootstrap.min.css" 
th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
<link href="..static/css/bootstrap-theme.min" 
th:href="@{/css/bootstrap.min.css}" rel="stylesheet">


<link href="..static/css/carousel.css" th:href="@{/css/carousel.css}" 
rel="stylesheet">
</head>
<body>
    <div class="container">
          <div class="jumbotron">
            <h1>Java SringREST API </h1> 

          </div>
    </div>

<div class="container">
    <div th:if = "${not #lists, isEmpty (customers)}">
        <h1>Users List</h1>
            <table class="table table-hover">
            <tr>
              <th>FirstName</th>
              <th>LastName</th>
              <th>CustomerUrl</th>
            </tr>
            <tr th:each="Customer : $(customers)">
              <td th:text = "${customers.firstname}"></td>
              <td th:text = "${customers.lastname}"></td>
              <td th:text = "${customers.customerUrl}"></td>
            </tr>

          </table>
     </div>
     </div>
  <!-- FOOTER -->
  <footer class="container">
    <p class="float-right"><a href="#">Back to top</a></p>
    <p>&copy; 2017-2018 Company, Inc. &middot; <a href="#">Privacy</a> 
  &middot; <a href="#">Terms</a></p>
  </footer>


<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="..static/js/jquery.min.js" th:src="@{/js/jquery.min.js}"> 
</script>
<script src="..static/js/bootstrap.min.js" th:src="@{/js/bootstrap.min.js}"> 

运行此 Spring 应用程序后,此 url http://localhost:8080/customers上出现白标错误,这是浏览器 Whitelabel Error Page 上的错误

This application has no explicit mapping for /error, so you are seeing 
this as a fallback.

Wed Sep 19 10:39:31 PDT 2018
There was an unexpected error (type=Not Found, status=404).
No message available

请我不知道为什么我在页面上出现此可白标错误,我希望它使用 API 返回客户详细信息。有什么帮助吗?

标签: javaspring-mvcswaggerthymeleafresttemplate

解决方案


首先,您需要创建一个 Customer POJO,在我的例子中,我使用 Recipe 作为 POJO 来玩 restTemplate

@Configuration
public class RestTemplateConfig {



    //Creating a restTemplate Bean 

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder)
    {
        return builder.build();
    }


}

然后创建一个实现类:

@Service
public class ImplementaionClass implements Service {
    private final RestTemplate restTemplate;
    public RecipeServiceImpl(RestTemplate restTemplate) {
        // TODO Auto-generated constructor stub
        this.restTemplate = restTemplate;
    }
    @Override
    public List<Result> getResultsByRecipe(String search,String query,int pageno) {
        // TODO Auto-generated method stub
        final List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
        final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); 
        converter.setSupportedMediaTypes(Arrays.asList(MediaType.ALL));
        messageConverters.add(converter);

//      
        this.restTemplate.setMessageConverters(messageConverters);
//
//      final Recipe recipe = this.restTemplate.getForObject("http://url.../api/?i=" + search,
//              Recipe.class);
//      
        ResponseEntity<Recipe> rateResponse = null;
//      ResponseEntity<Recipe> rateResponse = null;
//      if(pageno==0)
//          rateResponse =     restTemplate.exchange("http://url.../api/?i="+search,
//
//                    HttpMethod.GET, null, new ParameterizedTypeReference<Recipe>() {
//            });
        if(query.isEmpty())
            if(pageno==0)enter code here
                rateResponse =     restTemplate.exchange("http://url..../api/?i=" + search,
                        HttpMethod.GET, null, new ParameterizedTypeReference<Recipe>() {
                });
            else
            rateResponse =     restTemplate.exchange("http://url..../api/?i=" + search+"&q=&p="+pageno,
                                HttpMethod.GET, null, new ParameterizedTypeReference<Recipe>() {
                        });
        else
            if(pageno==0)
                rateResponse =     restTemplate.exchange("http://url.../api/?i=" + search+"&q="+query,
                        HttpMethod.GET, null, new ParameterizedTypeReference<Recipe>() {
                });
            else 
                rateResponse =     restTemplate.exchange("http://url...../api/?i=" + search+"&q="+query+"&p="+pageno,
                    HttpMethod.GET, null, new ParameterizedTypeReference<Recipe>() {
            });
final Recipe rates = rateResponse.getBody();

        System.out.println(rateResponse.getHeaders());
    return rates.getResults();
    }

这只是一个演示类,你可以如何使用 restTemplate,我希望它对你有用。


推荐阅读