Home > OS >  Build a button that would push objects into a list
Build a button that would push objects into a list

Time:10-11

Hi this is my first experience with back end development. My project requires me to have a Product Page with a list of products that a User/Customer can purchase. I want to be able to click on a "buy" button in my Product Page, which will direct my product into a Cart page. On my Cart Page all I want is to have a list of products that I have selected for purchase.

By clicking the following button should add the Product object as a list in my Cart

The following is my Product model:

@Entity(name = "ProductTable")
public class Product {

    // Attributes
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "productGen")
    @SequenceGenerator(name = "productGen", sequenceName = "productSeq", allocationSize = 1)
    private int id;

    @NotBlank(message = "Product name cannot be empty")
    @Size(min = 2, max = 15, message = "Product name must be between 2 - 15 characters long")
    @Column(length = 15, nullable = false)
    private String name;

    private double price;

    // Constructors
    public Product() {
    }

    public Product(String name, double price) {
        super();
        this.name = name;
        this.price = price;
    }

    // Getters and Setters
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

}

The following is my Product repository:

@Repository
public interface ProductRepository extends JpaRepository<Product, Integer> {

}

The following is my Product Service:

@Service
public class ProductService {

    private ProductRepository productRepo;

    @Autowired
    public ProductService(ProductRepository productRepo) {
        super();
        this.productRepo = productRepo;
    }

    // Save Product
    public void saveProduct(Product product) {
        this.productRepo.save(product);
    }

    // Delete Product
    public void deleteProduct(int productId) {
        this.productRepo.deleteById(productId);
    }

    // Get Product List
    //similar to findAllBooks
    public List<Product> getProductList() {
        return (List<Product>) productRepo.findAll();
    }
    
    // Update Product
    
    public Product findProductById(int id) {
        Optional<Product> result = productRepo.findById(id);
        if (result.isPresent()) {
            return result.get();
        }
        return new Product();
    }
    
    public Product updateProduct(Product product) {
        Optional<Product> result = productRepo.findById(product.getId());
        Product existing = result.get();
        existing.setName(product.getName());
        existing.setPrice(product.getPrice());
        return productRepo.save(existing);
    }
    
    

}

The following is my Product Controller:

@Controller
public class ProductController2 {

    @Autowired
    ProductService productService;

    // Done
    @GetMapping("/admin")
    public String findAll(Model model) {
        model.addAttribute("products", productService.getProductList());
        return "all-products";
    }

    // Done
    @GetMapping("/add")
    public String lunchAddProductPage(Model model) {
        model.addAttribute("product", new Product());
        return "add-product";
    }

    // Done
    @PostMapping("/addproduct")
    public String createProduct(@Valid Product product, BindingResult result) {
        if (result.hasErrors()) {
            return "add-product";
        }
        productService.saveProduct(product);
        return "redirect:/admin";

    }

    // To Do -- very different
    @GetMapping("/delete/{id}")
    public String deleteProduct(@PathVariable("id") int id) {
        productService.deleteProduct(id);
        return "redirect:/admin";
    }

    @GetMapping("/edit/{id}")
    public String lunchEditPage(Model model, @PathVariable("id") int id) {
        model.addAttribute("product", productService.findProductById(id));
        return "edit-product";

    }

    @PostMapping("/updateproduct")
    public String upadteProduct(@Valid Product product, BindingResult result) {
        if (result.hasErrors()) {
            return "edit-product";
        }
        productService.updateProduct(product);
        return "redirect:/admin";
    }
    
    //This is to get to the About page

    @GetMapping("/about")
    public String getToAboutPage() {
        return "About.html";
    }

    // this takes you to All Products page and displays all products
    @GetMapping("/AllProducts")
    public String goToAllProducts(Model model) {
        model.addAttribute("products", productService.getProductList());
        return "AllProducts";
    }
    
    
    // Get request to take us to the index page
    @GetMapping("/")
    public String index() {
        return "Index";
    }
    
    //Get to the cart page


}

The following codes are my html pages.

First of all, I built a all-products.html page. This page allows me to act as the Admin and add any products of my choice into my H2 database. I can also use this page to edit or delete my products.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>All Products</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
    href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
    integrity="sha384-ggOyR0iXCbMQv3Xipma34MD dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
    crossorigin="anonymous">
<link rel="stylesheet"
    href="https://use.fontawesome.com/releases/v5.4.1/css/all.css">
</head>

<body>

    <div >
        <h1>Welcome to Our Website (QRK)</h1>
        <p>Browse all our awesome products</p>
    </div>
    
    <div th:insert="navigation :: header"></div>

    <div >
        <div >
            <div >
                <div th:switch="${products}" >
                    <p >
                        <a href="/add" > <i
                            > Add a Product </i></a>
                    </p>
                    <div >
                        <h2 th:case="null">No record found !!</h2>
                        <div th:case="*">
                            <table >
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Product Name</th>
                                        <th>Price (£)</th>
                                        <th>Edit</th>
                                        <th>Delete</th>

                                    </tr>
                                </thead>
                                <tbody>
                                    <tr th:each="product : ${products}">
                                        <td th:text="${product.id}"></td>
                                        <td th:text="${product.name}"></td>
                                        <td th:text="${product.price}"></td>
                                        <td><a th:href="@{/edit/{id}(id=${product.id})}"
                                            > <i ></i>
                                        </a></td>
                                        <td><a th:href="@{/delete/{id}(id=${product.id})}"
                                            > <i
                                                ></i>
                                        </a></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div th:insert="footer :: footer"></div>
    
</body>

</html>

My following page is called AllProducts.html and it is built for a Customer. This page uses the previously mentioned "all-products.html". This page only shows the products that are built by the Admin. This page allows Customer to only "buy" a product. For now I want to be able to press the "Buy" button, which would produce a list of Products object in a separate html file.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>All Products</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
    href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
    integrity="sha384-ggOyR0iXCbMQv3Xipma34MD dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
    crossorigin="anonymous">
<link rel="stylesheet"
    href="https://use.fontawesome.com/releases/v5.4.1/css/all.css">
</head>

<body>

    <div >
        <h1>Welcome to Our Website (QRK)</h1>
        <p>Browse all our awesome products</p>
    </div>
    
    <div th:insert="navigation :: header"></div>

    <div >
        <div >
            <div >
                <div th:switch="${products}" >
                    <p >
                        <a href="/add" > <i
                            > Add a Product </i></a>
                    </p>
                    <div >
                        <h2 th:case="null">No record found !!</h2>
                        <div th:case="*">
                            <table >
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Product Name</th>
                                        <th>Price (£)</th>
                                        <th>Edit</th>
                                        <th>Delete</th>

                                    </tr>
                                </thead>
                                <tbody>
                                    <tr th:each="product : ${products}">
                                        <td th:text="${product.id}"></td>
                                        <td th:text="${product.name}"></td>
                                        <td th:text="${product.price}"></td>
                                        <td><a th:href="@{/edit/{id}(id=${product.id})}"
                                            > <i ></i>
                                        </a></td>
                                        <td><a th:href="@{/delete/{id}(id=${product.id})}"
                                            > <i
                                                ></i>
                                        </a></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div th:insert="footer :: footer"></div>
    
</body>

</html>

I would be glad if someone guided me on how to make the button "buy" in my AllProduct.html page so that it can keep adding the selected Product Object to a list in a separate html. Do I need to build @Postmapping or @Getmapping with a method in my ProductService? If so, how do I do it?

CodePudding user response:

can you write like this

enter code here

https://codepen.io/justinklemm/pen/kyMjjv

enter code here

for your project and then edit it

CodePudding user response:

and if you need more education see this

https://morioh.com/p/f31798fb4cd7

  • Related