Получаю ошибку белой страницы, не могу найти мою проблему в REST API?

#java #rest #api #spring-boot

#java #rest #API #весенняя загрузка

Вопрос:

Я создаю REST API для доступа к базе данных и испытываю проблемы / постоянно получаю ошибку белой страницы. Бегаю по кругу, пытаясь найти мою ошибку и / или мою ошибку в потоке или логике программы.

Вот мое приложение:

 package com.skilldistillery.myRest;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication
@ComponentScan(basePackages= {"com.skilldistillery.edgemarketing"})
@EntityScan("com.skilldistillery.edgemarketing")
@EnableJpaRepositories("com.skilldistillery.myRest.repositories")
public class MyRestApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(MyRestApplication.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(MyRestApplication.class, args);
    }

}
  

Мой контроллер:

 package com.skilldistillery.myRest.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.skilldistillery.edgemarketing.entities.House;
import com.skilldistillery.myRest.services.HouseService;

@RestController
@RequestMapping("api") 
@CrossOrigin({ "*", "http://localhost:4200" })
public class HouseController {

    @Autowired 
    HouseService houseServ; 

    @GetMapping("index/{id}")
    public House show(@PathVariable("id") Integer id) {
        return houseServ.show(id); 
    }

}
  

Мой репозиторий:

 package com.skilldistillery.myRest.repositories;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.skilldistillery.edgemarketing.entities.House;

@Repository
public interface HouseRepo extends JpaRepository<House, Integer>  {


}
  

Мой сервис:

 package com.skilldistillery.myRest.services;

import java.util.List;

import org.springframework.stereotype.Service;

import com.skilldistillery.edgemarketing.entities.House;

@Service
public interface HouseService {

    List<House> index(); 

    House show(Integer id); 
}
  

И мой ServiceImpl:

 package com.skilldistillery.myRest.services;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.skilldistillery.edgemarketing.entities.House;
import com.skilldistillery.myRest.repositories.HouseRepo;

@Service
public class HouseServiceImpl {
    @Autowired
    HouseRepo hRepo; 

    public House show(Integer id) {
        Optional<House> opt = hRepo.findById(id); 
        House house = null;
        if (opt.isPresent()) {
            house = opt.get();
        }
        return house;
    }

}
  

Он компилируется и запускается, но через postman и браузер я получаю ошибки белой страницы. Я просматривал Интернет, пытаясь понять, где я ошибаюсь, но не нашел этого. Пожалуйста, сообщите.

Комментарии:

1. можете ли вы поделиться HTTP-запросом от postman / browser? Я также вижу, что вы добавили аннотацию CrossOrigin, какова цель этого?

2. Спасибо @ Adi-Ohana. Вот что postman выдает мне в ответ на этот запрос: localhost: 8084 / api /index /245034 {«отметка времени»:»2019-04-01T17:22:39.178 0000″, «статус»: 404, «ошибка»: «Не найдено», «сообщение»: «Сообщение недоступно», «путь»: «/ api / index / 245034»} Я полагаю, что (d) причина перекрестное происхождение состояло в том, чтобы устранить ошибку перекрестного происхождения. Пример, который я ранее изучал, использовал его; Я открыт для критики / обучения.

3. В CrossOrigin нет ничего плохого. Это означает только то, что ваш ресурс может быть использован любым клиентом.

Ответ №1:

Вы можете использовать следующее решение. Измените свой основной класс на следующий код

 @SpringBootApplication
public class MyrestapplicationApplication  {
    public static void main(String[] args) {
        SpringApplication.run(MyrestapplicationApplication.class, args);
    }

}
  

Затем создайте отдельный класс для своих конфигураций.А также отказ от тесно связанной архитектуры.

 @Configuration
@EntityScan("com.skilldistillery.edgemarketing.entities")
@EnableJpaRepositories("com.skilldistillery.myRest.repositories")
public class BusinessConfig {

    @Bean
    public HouseService houseService(final HouseRepo houseRepo){
        return new HouseServiceImpl(houseRepo);
    }   
}
  

Затем ваш контроллер изменится на следующий.Использование внедрения зависимостей

 @RestController
@RequestMapping("api") 
@CrossOrigin({ "*", "http://localhost:4200" })
public class HouseController {

   private   HouseService houseServ;

    public HouseController(HouseService houseServ) {
        this.houseServ = houseServ;
    }

    @GetMapping(value = "index/{id}",produces = MediaType.APPLICATION_JSON_VALUE,consumes = MediaType.APPLICATION_JSON_VALUE)
    public House show(@PathVariable("id") Integer id) {
        return houseServ.show(id); 
    }
}
  

HouseServiceImpl также должен реализовать HouseService

 public class HouseServiceImpl implements HouseService{
  private  HouseRepo hRepo;

    public HouseServiceImpl(HouseRepo hRepo) {
        this.hRepo = hRepo;
    }

    @Override
    public List<House> index() {
        return null;
    }

    public House show(Integer id) {
        Optional<House> opt = hRepo.findById(id); 
        House house = new House();
        if (opt.isPresent()) {
            house = opt.get();
        }
        return house;
    }

}
  

* ПРИМЕЧАНИЕ — не забудьте удалить следующие конфигурации, @Autowired,@Repository поскольку они теперь обрабатываются в BusinessConfig классе.В BusinessConfig классе могут быть определены дополнительные компоненты

Комментарии:

1. Спасибо! Это сделало это. Я очень ценю вашу помощь. Я собираюсь проанализировать, ПОЧЕМУ это сработало, и сравнить это с проделанной мной работой. Еще раз, спасибо.