首页 > 解决方案 > Spring boot & Java - HTTP 状态 404 错误又名白标签错误

问题描述

请在下面查看我的代码。Java 代码似乎工作得很好,但是当我尝试访问它时localhost:8080给了我错误代码。404我想localhost 8080工作。如果您需要更多信息,请告诉我。

应用

@SpringBootApplication(exclude = { ErrorMvcAutoConfiguration.class })         
// exclude part is to elimnate whitelabel error
@EnableScheduling
public class Covid19TrackerApplication {

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

控制器

@Controller
public class HomeController {
    
    CovidDataService covidDataService;
    
    @RequestMapping("/")
    public @ResponseBody String home(Model model) {
        model.addAttribute( "locationStats", covidDataService.getAllStats());
        return "home";
    } 

}

主要代码

@Service
public class CovidDataService {
    
    private static String Covid_Data_URL = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";
    private List<LocationStats> allStats = new ArrayList<>();
    
    public List<LocationStats> getAllStats() {
        return allStats;
    }


    @PostConstruct//?
    @Scheduled(cron = "* * 1 * * *")    //????
    // * sec * min *hour and so on
    
    public void fetchCovidData() throws IOException, InterruptedException {
        List<LocationStats> newStats = new ArrayList<>(); // why we are adding this? To prevent user get an error while we are working on new data.
        HttpClient  client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(Covid_Data_URL))
                .build(); // uri = uniform resource identifier
        HttpResponse<String> httpResponse   = client.send(request, HttpResponse.BodyHandlers.ofString());
        StringReader csvBodyReader = new StringReader(httpResponse.body()); //StringReader needs to be imported
        
        Iterable<CSVRecord> records = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(csvBodyReader);  // parse(in) had error, we needed a "reader" instance.
        for (CSVRecord record : records) {
            LocationStats locationStat = new LocationStats();  //create an instance
            locationStat.setState(record.get("Province/State"));
            locationStat.setCountry(record.get("Country/Region"));
            locationStat.setLatestTotalCase(Integer.parseInt(record.get(record.size()-1)));
            System.out.println(locationStat);
            newStats.add(locationStat);
            
        }
        this.allStats = newStats;
    }


}

标签: javaeclipsespring-bootmavenwhite-labelling

解决方案


问题可能来自这段代码

@RequestMapping("/")
public @ResponseBody String home(Model model) {
    model.addAttribute( "locationStats", covidDataService.getAllStats());
    return "home";
} 

它返回应该是现有视图的“主页”,通常,该视图将是一个 jsp 文件,该文件位于 WEB-INF 中的某个位置,请参阅本教程:https ://www.baeldung.com/spring-mvc-view- resolver-tutorial 在映射错误的情况下,可能会返回 404 错误


推荐阅读