使用 - Spring Boot、Thymeleaf
我在控制器類下有以下代碼:
public class HotelController {
private HotelService hotelService;
private HotelRepository hotelRepository;
@Autowired
public HotelController(HotelService hotelService,HotelRepository hotelRepository) {
this.hotelService = hotelService;
this.hotelRepository = hotelRepository;
}
@GetMapping("/index")
public String searchHotel(Model model) {
Hotel hotel = new Hotel();
model.addAttribute("searchObject",hotel);
model.addAttribute("cityList", hotelRepository.findListOfCities());
model.addAttribute("hotelList", hotelRepository.findListOfHotels());
return "search_hotel";
}
@PostMapping("/availabilityResult")
public String afterClickingSearch(@ModelAttribute("searchObject") Hotel hotel,Model model) {
if(hotelService.searchHotelResult(hotel)==null)
return "failure_page";
else {
model.addAttribute("hotelRoom_TypePriceGST",hotelService.findHotelPriceandRoomType(hotel.getCity(),hotel.getHotel()).split(","));
model.addAttribute("total", hotelService.findTotal(hotel.getCity(), hotel.getHotel()));
return "booking_confirmation";
}
}
@GetMapping("/navUserRegisterPage")
public String userRegisterPage(Model model){
User user = new User();
model.addAttribute("userObj", user);
return "user_registerForm";
}
@PostMapping("/reserveUser")
public String reserveUserHandler(@ModelAttribute("userObj") User user,@ModelAttribute("searchObject") Hotel hotel,Model model) {
System.out.println(hotel.getHotel());
System.out.println(user.getGuest_name());
model.addAttribute("hotelName", hotel.getHotel());
model.addAttribute("userName", user.getGuest_name());
return "confirmation_page";
}
}
我可以在處理程式方法下找到酒店價值(usig hotel.getHotel()) - public String afterClickingSearch()
但是當我嘗試在處理程式方法 -reserveUserHandler(); 下找到酒店價值(使用hotel.getHotel())時;我得到 null 作為值。
請幫助我如何在 ReserveUserHandler() 方法下檢索酒店價值。
uj5u.com熱心網友回復:
看起來好像您在“search_hotel”頁面上有一個酒店支持的表單,并且操作轉到afterClickingSearch()。您可以訪問 Hotel 模型屬性,afterClickingSearch()因為您正在表單中提交酒店的屬性。當您轉換到“booking_confirmation”和其他頁面時,您傳遞酒店的 id 來維護狀態并不明顯。
你有幾個選擇,有些比其他的更優雅。您可以通過請求引數傳遞酒店的 id。第二種選擇是在所有reserveUserHandler()可訪問的表單中包含一個隱藏的酒店 id ,確保每個表單都使用 id 進行初始化,并通過 id 中的 id 查找酒店reserveUserHandler()。我不推薦的第三個選項是將 Hotel 或 Hotel id 設為會話屬性。請參閱此有關會話屬性的更多資訊。當您使用會話屬性時,您需要警惕多個瀏覽器選項卡以及如何在每個選項卡上維護唯一狀態。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/345450.html
上一篇:FormUrlEncodedPOST請求,我需要使用SpringBoot和Jackson將snakecase值轉換為camelCase
