This repository has been archived on 2020-08-02. You can view files and clone it, but cannot push or open issues or pull requests.
e-commerce/web_backend/src/main/java/org/hso/ecommerce/controller/shop/ShopSearchController.java

54 lines
2.2 KiB
Java

package org.hso.ecommerce.controller.shop;
import org.hso.ecommerce.action.shop.SearchByTermAction;
import org.hso.ecommerce.entities.shop.Article;
import org.hso.ecommerce.repos.shop.ArticleRepository;
import org.hso.ecommerce.repos.shop.CategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
@Controller
@RequestMapping("/shop/search")
public class ShopSearchController {
@Autowired
private final ArticleRepository articleRepository = null;
@Autowired
private final CategoryRepository categoryRepository = null;
@GetMapping("")
public String searchArticles(@RequestParam(required = false, value = "term") String term,
@RequestParam(required = false, value = "category") String category,
Model model,
HttpServletRequest request,
HttpServletResponse response
) {
model.addAttribute("categories", categoryRepository.getCategories()); //for sidebar
if (term != null) { //if search by Term
term = term.trim();
List<Article> articles = SearchByTermAction.searchByTerm(term, articleRepository);
model.addAttribute("articles", articles);
} else if (category != null) { //if search by Category
List<Article> articles = articleRepository.getArticlesByCategory(category); //search by Category
model.addAttribute("articles", articles);
} else {
List<Article> articles = SearchByTermAction.searchByTerm("", articleRepository);
model.addAttribute("articles", articles);
}
// Show term in search box
model.addAttribute("searchterm", term != null ? term : "");
return "shop/search";
}
}