1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.mybatis.jpetstore.web.controllers;
17
18 import java.util.List;
19
20 import org.mybatis.jpetstore.domain.Category;
21 import org.mybatis.jpetstore.domain.Item;
22 import org.mybatis.jpetstore.domain.Product;
23 import org.mybatis.jpetstore.service.CatalogService;
24 import org.springframework.beans.factory.annotation.Autowired;
25 import org.springframework.stereotype.Controller;
26 import org.springframework.ui.Model;
27 import org.springframework.web.bind.annotation.GetMapping;
28 import org.springframework.web.bind.annotation.RequestMapping;
29 import org.springframework.web.bind.annotation.RequestParam;
30
31
32
33
34 @Controller
35 @RequestMapping("/catalog")
36 public class CatalogController {
37
38
39 private static final String ERROR_VIEW = "common/Error";
40
41
42 @Autowired
43 private CatalogService catalogService;
44
45
46
47
48
49
50 @GetMapping({ "", "/" })
51 public String viewMain() {
52 return "catalog/Main";
53 }
54
55
56
57
58
59
60
61
62
63
64
65 @GetMapping("/viewCategory")
66 public String viewCategory(@RequestParam(value = "categoryId", required = false) String categoryId, Model model) {
67 if (categoryId != null) {
68 List<Product> productList = catalogService.getProductListByCategory(categoryId);
69 Category category = catalogService.getCategory(categoryId);
70 model.addAttribute("productList", productList);
71 model.addAttribute("category", category);
72 }
73 return "catalog/Category";
74 }
75
76
77
78
79
80
81
82
83
84
85
86 @GetMapping("/viewProduct")
87 public String viewProduct(@RequestParam(value = "productId", required = false) String productId, Model model) {
88 if (productId != null) {
89 List<Item> itemList = catalogService.getItemListByProduct(productId);
90 Product product = catalogService.getProduct(productId);
91 model.addAttribute("itemList", itemList);
92 model.addAttribute("product", product);
93 }
94 return "catalog/Product";
95 }
96
97
98
99
100
101
102
103
104
105
106
107 @GetMapping("/viewItem")
108 public String viewItem(@RequestParam("itemId") String itemId, Model model) {
109 Item item = catalogService.getItem(itemId);
110 Product product = item.getProduct();
111 model.addAttribute("item", item);
112 model.addAttribute("product", product);
113 return "catalog/Item";
114 }
115
116
117
118
119
120
121
122
123
124
125
126 @GetMapping("/searchProducts")
127 public String searchProducts(@RequestParam(value = "keyword", required = false) String keyword, Model model) {
128 if (keyword == null || keyword.isEmpty()) {
129 model.addAttribute("message", "Please enter a keyword to search for, then press the search button.");
130 return ERROR_VIEW;
131 }
132 List<Product> productList = catalogService.searchProductList(keyword.toLowerCase());
133 model.addAttribute("productList", productList);
134 return "catalog/SearchProducts";
135 }
136
137 }