You must implement Service Layer in the application
For example:
public interface RentalService { void addRental(Rental rental, Long userId, Long carId); }
Implementation:
@Service @Transactional class DefaultRentalService implement RentalService { @Autowired private CarDAO carDAO; @Autowired private UserDAO userDAO; @Autowired private RentalDAO rentalDAO; @Override void addRental(Rental rental, Long userId, Long carId) { User user = userDAO.getById(userId); Car car = carDAO.getById(carId); rental.setUser(user); rental.setCar(car); rentalDao.save(rental); } }
HTML:
<form:form method="POST" commandName="rental"> <form:errors path="*" cssClass="errorblock" element="div" /> <table cellspacing="10"> <tr> <td>Car</td> <td> <select name="carId" > <c:forEach items="${cars}" var="car"> <option value="${car.id}">${car.name} </c:forEach> </select> </td> </tr> <tr> <td colspan="2"><input type="submit" value="Create"></td> </tr> </table>
Controller:
@AutoWired private RentalService rentalService; // .. // .. @RequestMapping(method = RequestMethod.POST) public String processSubmit(@ModelAttribute("rental") Rental rental, @RequestParam Long carId, BindingResult result, SessionStatus status, HttpSession session) { Object userId = session.getAttribute("userId"); if (userId != null) { rentalService.add(rental, (Long)userId, carId); status.setComplete(); } // form success return "redirect:/index.htm"; }
Pau kiat wee
source share