Home > Net >  Get and Post request result in "error": "Not Found" on my spring boot api
Get and Post request result in "error": "Not Found" on my spring boot api

Time:09-17

I am using Spring data JPA to persist an entity to an H2 database, the get/ post requests always return error "Not Found" with status 404, but the data that I send in post request is reaching the database and is saved!

what I tried: making sure that my controller and the main method are under the same package.

my application.properties:

spring.datasource.url=jdbc:h2:./data/myBudget
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=update

the controller:

package com.example.budgetwithjpa.control;

import com.example.budgetwithjpa.data.ExpenseRepository;
import com.example.budgetwithjpa.entity.Expense;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/budget")
public class ExpenseController {
    ExpenseRepository expenseRepo;

    @Autowired
    public ExpenseController(ExpenseRepository expenseRepo) {
        this.expenseRepo = expenseRepo;
    }

    @GetMapping("/view")
    public Iterable<Expense> viewAll(Model model) {
        System.out.println(expenseRepo.findAll());
        return expenseRepo.findAll();
    }

    @PostMapping
    public String addExpense(@RequestBody Expense expense) {
        expenseRepo.save(expense);
        return "ok.";
    }
}

in the above code, the System.out inside the viewAll method will print the contents of the database to console

the repository:

import com.example.budgetwithjpa.entity.Expense;
import org.springframework.data.repository.CrudRepository;

public interface ExpenseRepository extends CrudRepository<Expense, Long> {
}

I am sending get request to http://localhost:8080/budget/view and getting

{
    "timestamp": "2021-08-26T11:10:50.956 00:00",
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/budget/view"
}

below are screens of my project file structure and dependencies:

the project file structure: project file structure

project dependencies: dependencies

you can get the application from this github repo if you want to replicate the issue

CodePudding user response:

You are missing the @ResponseBody annotation:

@ResponseBody
@GetMapping("/view")
public Iterable<Expense> viewAll(Model model) {
    System.out.println(expenseRepo.findAll());
    return expenseRepo.findAll();
}

Alternatively you could use @RestController instead of @Controller.

  • Related