首页 > 代码库 > SpringMVC 视图和视图解析器&表单标签

SpringMVC 视图和视图解析器&表单标签

视图和视图解析器

  请求处理方法执行完成后,最终返回一个 ModelAndView 对象。对于那些返回 String,View 或 ModeMap 等类型的处理方法,Spring MVC 也会在内部将它们装配成一个ModelAndView 对象,它包含了逻辑名和模型对象的视图
  Spring MVC 借助视图解析器(ViewResolver)得到最终的视图对象(View),最终的视图可以是 JSP ,也可能是Excel、JFreeChart 等各种表现形式的视图

视图

视图的作用是渲染模型数据,将模型里的数据以某种形式呈现给客户。

视图解析器

SpringMVC 为逻辑视图名的解析提供了不同的策略,可以在 Spring WEB 上下文中配置一种或多种解析策略,并指定他们之间的先后顺序。每一种映射策略对应一个具体的视图解析器实现类。

InternalResourceViewResolver

JSP 是最常见的视图技术,可以使用InternalResourceViewResolver 作为视图解析器.

	<!-- 配置视图解析器: 如何把 handler 方法返回值解析为实际的物理视图 -->	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">		<property name="prefix" value="http://www.mamicode.com/WEB-INF/views/"></property>		<property name="suffix" value="http://www.mamicode.com/.jsp"></property>	</bean>

若项目中使用了 JSTL,则 SpringMVC 会自动把视图由InternalResourceView 转为 JstlView
若使用 JSTL 的 fmt 标签则需要在 SpringMVC 的配置文件中配置国际化资源文件

	<!-- 配置国际化资源文件 -->	<bean id="messageSource"		class="org.springframework.context.support.ResourceBundleMessageSource">		<property name="basename" value="http://www.mamicode.com/i18n"></property>		</bean>

 Excel 视图

若希望使用Excel 展示数据列表,仅需要扩展SpringMVC 提供的 AbstractExcelView 或AbstractJExcel View 即可。实现 buildExcelDocument() 方法,在方法中使用模型数据对象构建 Excel 文档就可以了。

视图对象需要配置 IOC 容器中的一个 Bean,使用 BeanNameViewResolver 作为视图解析器即可

自定义视图

技术分享
 1 @Component 2 public class HelloView implements View{ 3  4     @Override 5     public String getContentType() { 6         return "text/html"; 7     } 8  9     @Override10     public void render(Map<String, ?> model, HttpServletRequest request,11             HttpServletResponse response) throws Exception {12         response.getWriter().print("hello view, time: " + new Date());13     }14 15 }
View Code
	<!-- 配置视图  BeanNameViewResolver 解析器: 使用视图的名字来解析视图 -->	<!-- 通过 order 属性来定义视图解析器的优先级, order 值越小优先级越高 -->	<bean class="org.springframework.web.servlet.view.BeanNameViewResolver">		<property name="order" value="http://www.mamicode.com/100"></property>	</bean>
	<!-- 配置直接转发的页面 -->	<!-- 可以直接相应转发的页面, 而无需再经过 Handler 的方法.  -->	<mvc:view-controller path="/success" view-name="success"/>		<!-- 在实际开发中通常都需配置 mvc:annotation-driven 标签 -->	<mvc:annotation-driven></mvc:annotation-driven>

 关于重定向

如果返回的字符串中带 forward: 或 redirect: 前缀时,SpringMVC 会对他们进行特殊处理:将 forward: 和redirect: 当成指示符,其后的字符串作为 URL 来处理

 

SpringMVC 视图和视图解析器&表单标签