package com.lovecoding.mvc;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;

@Controller
public class RequestController {

    /**
     * 如果我们使用 ModelAndView 作为共享数据
     * 我们控制器 返回类型必须是  ModelAndView
     * ModelAndView 视图必须填写正确
     * @param req
     * @return
     */
    @GetMapping("/requestDemo")
    public ModelAndView requestDemo(HttpServletRequest req){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/requestDemo.jsp");
        modelAndView.addObject("name", req.getParameter("name"));
        return modelAndView;
    }

    /**
     * 演示Session 共享数据
     * Session 数据共享
     * Session 生命周期 特别长
     */
    @GetMapping("/sessionDemo")
    public String sessionDemo(HttpSession httpSession, String name){
        httpSession.setAttribute("name", name);
        return "/sessionDemo.jsp";
    }

    @GetMapping("/modelAndViewDemo")
    public ModelAndView modelAndViewDemo( ModelAndView modelAndView ){
        modelAndView.addObject("msg",
                "我是ModelAndView Bean对象");
        modelAndView.setViewName("/modelAndViewDemo.jsp");
        return modelAndView;
    }


    @GetMapping("/mapDemo")
    public String mapDemo(HashMap<String, Object> map){
        map.put("msg", "我是mapDemo的Object数据");
        return "/mapDemo.jsp";
    }

    @GetMapping("modelDemo")
    public String modelDemo(Model model){
        model.addAttribute("msg", "我是 Model 存储的数据");
        return  "/modelDemo.jsp";
    }

    @GetMapping("modelMapDemo")
    public String modelMapDemo(ModelMap modelMap){
        modelMap.addAttribute("msg", "我是ModelMap对象！");
        return "modelMapDemo.jsp";
    }

}
