springMVC Controller层中的方法返回值配置

Controller层中的方法返回值配置

  1. ModelAndView,字符串,无返回值(void)

1.1) 返回ModelAndView 要求方法中创建ModelAndView对象,可以调用addObject方法用于向页面传值,调用setViewName方法用于设置跳转页面路径。

mv.addObject("uname",uname);
mv.setViewName("/success.jsp");

1.2)返回字符串

return "/success.jsp";

返回字符串时数据传递: 利用HttpServletRequest对象:

@RequestMapping("lg2")
public String login2(String uname, String upwd, HttpServletRequest request){
          
   
    //方法的参数用于接收数据
    System.out.println("uname:" + uname);
    System.out.println("upwd:" + upwd);
    System.out.println("hello springmvc");
    request.setAttribute("uname",uname);
    return "/success.jsp";
}

利用Model对象:

@RequestMapping("lg3")
public String login3(String uname, String upwd, Model model){
          
   
    //方法的参数用于接收数据
    System.out.println("uname:" + uname);
    System.out.println("upwd:" + upwd);
    System.out.println("hello springmvc");
    model.addAttribute("uname",uname);
    return "/success.jsp";
}

利用session传值:

@RequestMapping("lg4")
public String login4(String uname, String upwd, HttpSession session){
          
   
    //方法的参数用于接收数据
    System.out.println("uname:" + uname);
    System.out.println("upwd:" + upwd);
    System.out.println("hello springmvc");
    session.setAttribute("uname",uname);
    return "/success.jsp";
}

1.2)无返回值 无返回值时,使用servlet技术完成页面跳转。

@RequestMapping("lg5")
public void login5(String uname, String upwd, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          
   
    //方法的参数用于接收数据
    System.out.println("uname:" + uname);
    System.out.println("upwd:" + upwd);
    System.out.println("hello springmvc");
    request.setAttribute("uname",uname);
    request.getRequestDispatcher("success.jsp").forward(request,response);
}
经验分享 程序员 微信小程序 职场和发展