我正在使用Spring data JPA將一個物體持久化到H2資料庫中,get/post請求總是回傳404狀態的錯誤 "Not Found",但我在post請求中發送的資料卻到達了資料庫并被保存了!
我嘗試了什么?
我嘗試了什么? 確保我的控制器和主方法是在同一個包里。
我的application.properties:
span class="hljs-attr">spring.datasource.url=jdbc:h2:./data/myBudget
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=update
控制器:
package com.example.budgetwithjpa.control;
import com.example.badgetwithjpa.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(expendRepo.findAll())。
return expenseRepo.findAll();
}
@PostMapping[/span
public String addExpense(@RequestBody Expense expense) {
expenseRepo.save(expense)。
return "ok。"。
}
在上面的代碼中,System.out里面的viewAll方法將列印資料庫的內容到控制臺
資源庫:
import com.example.badgetwithjpa.entity.Expense;
import org.springframework.data.repository.CrudRepository;
public interface ExpenseRepository extends CrudRepository<Expense, Long> {
}
我正在向http://localhost:8080/budget/view 發送獲取請求。 并得到
{<
"timestamp": "2021-08-26T11:10:50.956 00:00",
"status": 404,
"錯誤": "未找到",
"message": "No message available",
"path": "/budget/view"/span>
}
下面是我的專案檔案結構和依賴關系的螢屏:
專案檔案結構。
你可以通過以下方式獲得應用程式:
你可以從這個github repo獲得應用程式,如果你想復制這個問題
uj5u.com熱心網友回復:
你缺少@ResponseBody注釋:
@ResponseBody。
@GetMapping("/view"/span>)
public Iterable<Expense> viewAll(Model model) {
System.out.println(expendRepo.findAll())。
return expenseRepo.findAll()。
另外,你可以用@RestController代替@Controller。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/313476.html
標籤:
