2020-04-29 22:44:16 +02:00
package org.hso.ecommerce.controller.shop ;
2020-04-28 22:41:29 +02:00
2020-05-14 15:43:16 +02:00
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 ;
2020-04-28 22:41:29 +02:00
import org.springframework.stereotype.Controller ;
2020-05-14 15:43:16 +02:00
import org.springframework.ui.Model ;
import org.springframework.web.bind.annotation.* ;
2020-05-15 12:23:32 +02:00
import javax.servlet.http.HttpServletRequest ;
2020-05-14 15:43:16 +02:00
import javax.servlet.http.HttpServletResponse ;
import java.util.List ;
2020-04-28 22:41:29 +02:00
@Controller
2020-05-14 15:43:16 +02:00
@RequestMapping ( " /shop/search " )
2020-05-01 10:48:12 +02:00
public class ShopSearchController {
2020-05-14 15:43:16 +02:00
@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 ,
2020-05-15 12:23:32 +02:00
Model model ,
HttpServletRequest request ,
HttpServletResponse response
2020-05-14 15:43:16 +02:00
) {
2020-05-15 12:23:32 +02:00
model . addAttribute ( " categories " , categoryRepository . getCategories ( ) ) ; //for sidebar
2020-05-14 15:43:16 +02:00
if ( term ! = null ) { //if search by Term
2020-05-17 12:59:03 +02:00
List < Article > articles = articleRepository . getArticlesByTerm ( term ) ; //search by Term
2020-05-14 15:43:16 +02:00
model . addAttribute ( " articles " , articles ) ;
} else if ( category ! = null ) { //if search by Category
2020-05-17 12:59:03 +02:00
List < Article > articles = articleRepository . getArticlesByCategory ( category ) ; //search by Category
2020-05-14 15:43:16 +02:00
model . addAttribute ( " articles " , articles ) ;
2020-05-15 12:23:32 +02:00
} else {
request . setAttribute ( " error " , " Es wurden keine Suchparameter angegeben. " ) ;
response . setStatus ( HttpServletResponse . SC_NOT_FOUND ) ;
return " error/404 " ;
2020-05-14 15:43:16 +02:00
}
return " /shop/search " ;
}
}