我正在創建Spring MVC Web應用程序以進行在線航班預訂。這是一個初學者項目,我的問題可能太長。我刪除了無用代碼。在這裏我創建了一個包含航班信息的jsp頁面。在Spring Web應用程序中登錄後自動提交
flightInfos.jsp
頁
<table>
<thead>
<tr>
<th>Flight No</th>
<th>Flight destination</th>
<th>Flight origin</th>
<th>Book now</th>
</tr>
</thead>
<tbody>
<form:form action='/flight-demo/flight-reservation.html'>
<c:forEach items="${flightInfos}" var="flightInfo">
<tr>
<td>${flightInfo.flightNo}</td>
<td>${flightInfo.destination}</td>
<td>${flightInfo.origin}</td>
<td><input type="submit" value="Book now"></td>
</tr>
</c:forEach>
</form:form>
</tbody>
</table>
一旦我點擊預訂按鈕,它會檢查用戶是否登錄或不使用Spring的安全性。這是我的代碼。
security.xml
<http use-expressions="true">
<intercept-url pattern="/users**" access="hasRole('ROLE_ADMIN')" />
<intercept-url pattern="https://stackoverflow.com/users/**" access="hasRole('ROLE_ADMIN')" />
<intercept-url pattern="/account**" access="hasRole('ROLE_USER')" />
<intercept-url pattern="/flight-reservation**" access="hasRole('ROLE_USER')" />
<form-login login-page="/login.html"/>
<csrf disabled="true"/>
<logout logout-url="/logout" />
</http>
<!--Authentication manager-->
</beans:beans>
然後用戶後,登錄到系統,將用戶重定向到flight-reservation.jsp
頁。
flight-reservation.jsp
<form:form modelAttribute="reservation">
<c:if test="${param.ok eq true}">
<div class="alert alert-success" role="alert">Registration successful.</div>
</c:if>
<label for="customerName"> Name </label>
<form:input path="customerName"/>
<label for="flightInfo"> Flight No </label>
<form:input path="flightInfo" />
<input type="submit" value="Save" />
</form:form>
這裏是我的flight-reservation controller
控制的保留。
@Controller
public class FlightResController {
@Autowired
private FlightReservationService reservationService;
@ModelAttribute("reservation")
public FlightReservation construct(){
return new FlightReservation();
}
@RequestMapping(value="/flight-reservation", method=RequestMethod.POST)
public String doReservation(@ModelAttribute("reservation") FlightReservation reservation){
reservationService.save(reservation);
return "redirect://flight-reservation.html?ok=true";
}
}
我的問題是,當我點擊Book now按鈕時,它會檢查用戶是否被記錄;如果記錄,應該顯示flight-reservation
頁面。但是,當我單擊立即預訂按鈕時,會發生什麼情況,並且會自動顯示將空值插入到我的數據庫的航班預定表中。我如何避免這種情況?我只是初學者,想要通過Spring MVC
。我非常感謝你的幫助。
是的,我定義了它。過濾和映射。 – RYJ
你爲什麼使用modelAttribute? @ModelAttribute(「保留」)它始終在每個請求之前執行。 – Simone
我爲用戶註冊做了同樣的事情。它運作良好。在不使用'@ modelAttribute'的情況下,如何保存該預留?我無法理解這一點。 @Simone – RYJ