I'm creating a web shop in JSP for a school project.
On each product page, there's a button to add it to the cart. Originally, there is only one item added to the cart when we press the "Add" button.
I send the productId to add to the controller by adding it as parameter in the url as you can see here :
<div class="product-page">
<div class="product">
<h1>${product.title}</h1>
<img src="${product.imageUrl}"/>
<div class="price"><p>${product.price}€</p></div>
</div>
<c:url var="addLineToCart" value="/product/addLineCart">
<c:param name="productId" value="${product.id}" />
</c:url>
<a id="addToCart" type="submit" href="${addLineToCart}"><spring:message code="addCart"/></a>
What I'd like to do, is to add an input field to specify the amount of items to add in the cart. I did it here :
<div class="product-page">
<div class="product">
<h1>${product.title}</h1>
<img src="${product.imageUrl}"/>
<div class="price"><p>${product.price}€</p></div>
</div>
<input type="number" name="quantity" value="1"/>
<c:url var="addLineToCart" value="/product/addLineCart">
<c:param name="productId" value="${product.id}" />
</c:url>
<a id="addToCart" type="submit" href="${addLineToCart}"><spring:message code="addCart"/></a>
My problem is that I don't know how to pass the value from the input field in the <c:param/>
property in order to add it in the URL too.
Here is how my controller looks like assuming I get the quantity to add via the URL :
@Controller
@RequestMapping(value="/product")
@SessionAttributes({Constants.CURRENT_CART})
public class ProductController {
private ProductDAO productDAO;
@Autowired
public ProductController(ProductDAO productDAO){
this.productDAO = productDAO;
}
@ModelAttribute(Constants.CURRENT_CART)
public Cart cart()
{
return new Cart();
}
@RequestMapping (method = RequestMethod.GET)
public String home(ModelMap model, @RequestParam("product") int productId, @ModelAttribute(value=Constants.CURRENT_CART) Cart cart){
Product product = productDAO.getById(productId);
model.addAttribute("product", product);
model.addAttribute("title", "Produit");
model.addAttribute("cart", cart);
return "integrated:product";
}
@GetMapping("/addLineCart")
public String addLineCart(@ModelAttribute(value=Constants.CURRENT_CART) Cart cart, @RequestParam("productId") int productId, @RequestParam("quantity") int quantity, ProductService productService)
{
Product product = productService.searchProduct(productId,productDAO);
cart.addProduct(product, quantity);
return "redirect:/product?product=" + productId;
}
}
Thanks for your help.