springmv 后台传给前台页面数据的4种方法

时间:2022-12-13 17:07:59

前台jsp代码

     <p style="color:red;font-size:20px;">
         <c:if test="${not empty errorStr}">
             ${errorStr}
         </c:if>
     </p>

一、返回类型是String,放在Model里

@RequestMapping(value="/login",method = RequestMethod.POST)
    public String login(User user,Model model) {
        String info = loginUser(user);
        if(!"SUCC".equals(info)){
            model.addAttribute("errorStr", "用户名或密码错误");
            return "login";
        }else
            return "index";
    }

二、返回类型是String, 放在HttpServletRequest里

   @RequestMapping(value="/login",method = RequestMethod.POST)
    public String login(User user,HttpServletRequest request) {
        String info = loginUser(user);
        if(!"SUCC".equals(info)){
            request.setAttribute("errorStr", "用户名或密码错误");
            return "login";
        }else
            return "index";
    }
三、返回类型是String, 放在Map里

    @RequestMapping(value="/login",method = RequestMethod.POST)
    public String login(User user,Map map) {
        String info = loginUser(user);
        if(!"SUCC".equals(info)){  
            List<String> list = new ArrayList<String>();
            list.add("用户名或密码错误");
            map.put("errorStr", list);
            return "login";
        }else
            return "index";
    }

四、返回类型是ModelAndView, 放在ModelAndView里

    @RequestMapping(value="/login",method= RequestMethod.POST)
    public ModelAndView login(User user){
        ModelAndView mav= new ModelAndView();
        String info = loginUser(user);
        if(!"SUCC".equals(info){
            mav.setViewName("login");
            mav.addObject("errorStr","用户名或密码错误");
        }else
        mav.setViewName("index");
        return mav;
    }