> 文章列表 > 《Spring MVC》 第四章 域对象、视图、转发和重定向

《Spring MVC》 第四章 域对象、视图、转发和重定向

《Spring MVC》 第四章 域对象、视图、转发和重定向

前言

介绍Spring MVC的域对象、视图、转发和重定向

1、域对象共享数据

Spring MVC 提供了多种域对象共享数据的方式,其中最常用的方式如下:

1.1、使用 Servlet API 向 request 域对象中共享数据

服务端代码:

@RequestMapping("toLogin")
public String toLogin(HttpServletRequest request){request.setAttribute("welcome","hello tiger!");return "login";
}

前端代码:

<h1 th:text="${welcome}"></h1>

1.2、使用 ModelAndView 向 request 域对象中共享数据

服务端代码:

@RequestMapping("toLogin")
public ModelAndView toLogin(){ModelAndView modelAndView = new ModelAndView();modelAndView.addObject("welcome","hello tiger!");modelAndView.setViewName("login");return modelAndView;
}

前端代码:

<h1 th:text="${welcome}"></h1>

1.3、使用 Model 向 request 域对象中共享数据

@RequestMapping("toLogin")
public String toLogin(Model model){model.addAttribute("welcome","hello tiger!");return "login";
}

1.4、使用 Map 向 request 域对象中共享数据

@RequestMapping("toLogin")
public String toLogin(Map<String,Object> map){map.put("welcome","hello tiger!");return "login";
}

1.5、使用 ModelMap 向 request 域对象中共享数据

@RequestMapping("toLogin")
public String toLogin(ModelMap modelMap){modelMap.addAttribute("welcome","hello tiger!");return "login";
}

1.6、使用 Servlet API 向 session 域中共享数据

@RequestMapping("toLogin")
public String toLogin(HttpSession session){session.setAttribute("welcome","hello tiger!");return "login";
}
<h1 th:text="${session.welcome}"></h1>

1.7、使用 Servlet API 向 application 域中共享数据

@RequestMapping("toLogin")
public String toLogin(HttpSession session){ServletContext application = session.getServletContext();application.setAttribute("welcome","hello tiger!");return "login";
}
<h1 th:text="${application.welcome}"></h1>

1.8、thymeleaf集合遍历

<tr th:each="e:${userList}">
<td th:text="${e.userName}"/>
<td th:text="${e.gender}"/>
</tr>

2、视图

在 Spring MVC 中,视图扮演着十分重要的角色,它主要负责整合 Web 资源、对模型数据进行渲染,并最终将 Model 中的数据以特定的形式展示给用户。

实现类 说明
ThymeleafView Thymeleaf 视图。当项目中使用的视图技术为 Thymeleaf 时,就需要使用该视图类。
InternalResourceView 转发视图,通过它可以实现请求的转发跳转。与此同时,它也是 JSP 视图。RedirectView重定向视图,通过它可以实现请求的重定向跳转。
FreeMarkerView FreeMarker 视图.
MappingJackson2JsonView JSON 视图。
AbstractPdfView PDF 视图 。

视图划分为两大类:逻辑视图和非逻辑视图

2.1、逻辑视图

逻辑视图最大的特点就是,其控制器方法返回的 ModelAndView 中的 view 可以不是一个真正的视图对象,而是一个字符串类型的逻辑视图名

  • 直接在控制器方法中返回字符串类型的逻辑视图名
  • 在控制器方法中通过 ModelAndView 提供的 setViewName() 方法设置逻辑视图名

2.2、非逻辑视图

非逻辑视图,则与逻辑视图完全相反,其控制方法返回的是一个真正的视图对象

@RequestMapping("toLogin")
public ModelAndView toLogin(HttpSession session){ModelAndView modelAndView = new ModelAndView();UserInfo userInfo = new UserInfo();userInfo.setUserName("tiger");userInfo.setGender("man");modelAndView.addObject(userInfo);modelAndView.setView(new MappingJackson2JsonView());return modelAndView;
}

导入以下json解析关联的包
《Spring MVC》 第四章 域对象、视图、转发和重定向

3、转发和重定向

3.1、转发

return "forward:/login"
modelAndView.setViewName("forward:/login");

3.2、重定向

return "redirect:/login"
modelAndView.setViewName("redirect:/login");