per.mnn.controller.CategoryController.java Source code

Java tutorial

Introduction

Here is the source code for per.mnn.controller.CategoryController.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package per.mnn.controller;

import java.util.List;
import per.mnn.hibernate.HibernateUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import per.mnn.hibernate.Category;
import per.mnn.hibernate.Product;

/**
 *
 * @author myu
 */
@Controller
public class CategoryController {

    @RequestMapping(value = "/category", method = RequestMethod.GET)
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse respond) {

        ModelAndView retval = new ModelAndView();
        HttpSession httpSess = request.getSession();
        Session sess = HibernateUtil.getSessionFactory().openSession();

        try {
            Query query = sess.createQuery("FROM Category");
            retval.addObject("categories", query.list());

            String name = request.getQueryString();
            if (name != null && !name.isEmpty()) {
                for (Category item : (List<Category>) query.list()) {
                    if (item.getName().equals(name.replace("%20", " "))) {
                        httpSess.setAttribute("selectedCategory", item);
                        query = sess.createQuery("FROM Product as p WHERE p.category.id = :id");
                        query.setInteger("id", item.getId());
                        httpSess.setAttribute("categoryProducts", query.list());
                        break;
                    }
                }
            }
        } finally {
            sess.close();
        }

        retval.setViewName("category");
        return retval;
    }
}