新彩天欢迎您!
幻海优品

Spring MVC - 资源包视图解析器示例

ResourceBundleViewResolver 用于使用属性文件中定义的视图bean来解析视图名称.以下示例显示如何使用Spring Web MVC框架使用ResourceBundleViewResolver.

TestWeb-servlet.xml

<bean class = "org.springframework.web.servlet.view.ResourceBundleViewResolver">   <property name = "basename" value = "views" /></bean>

这里, basename 是指资源包的名称,它包含视图.资源包的默认名称是 views.properties ,可以使用basename属性覆盖它.

views.properties

hello.(class) = org.springframework.web.servlet.view.JstlViewhello.url = /WEB-INF/jsp/hello.jsp

例如,使用上面的配置,如果URI :

  • /hello,DispatcherServlet会将请求转发到views.properties中bean hello定义的hello.jsp.

  • 此处,"你好"是要匹配的视图名称.然而,是指视图类型,URL是视图的位置.

首先,让我们有一个可用的Eclipse IDE,并考虑以下步骤使用Spring Web Framework开发基于动态表单的Web应用程序.

Step描述
1在Spring MVC  -  Hello World章节中解释,在com.it1352包下创建一个名为TestWeb的项目.
2在下面创建一个Java类HelloController com.it1352包.
3创建jsp子文件夹下的视图文件hello.jsp.
4在src文件夹下创建一个属性文件views.properties.
5下载JSTL库 jstl.jar .把它放在你的CLASSPATH中.
6最后一步是创建源文件和配置文件的内容并导出应用程序,如下所述.

HelloController. java

package com.it1352; import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.ui.ModelMap;@Controller@RequestMapping("/hello")public class HelloController{    @RequestMapping(method = RequestMethod.GET)   public String printHello(ModelMap model) {      model.addAttribute("message", "Hello Spring MVC Framework!");      return "hello";   }}

TestWeb-servlet.xml

<beans xmlns = "http://www.springframework.org/schema/beans"   xmlns:context = "http://www.springframework.org/schema/context"   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"   xsi:schemaLocation = "   http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   http://www.springframework.org/schema/context    http://www.springframework.org/schema/context/spring-context-3.0.xsd">   <context:component-scan base-package = "com.IT屋" />   <bean class = "org.springframework.web.servlet.view.ResourceBundleViewResolver">      <property name = "basename" value = "views" />   </bean></beans>

views.properties

hello.(class) = org.springframework.web.servlet.view.JstlViewhello.url = /WEB-INF/jsp/hello.jsp

hello.jsp

<%@ page contentType="text/html; charset=UTF-8" %><html>   <head>      <title>Hello World</title>   </head>   <body>      <h2>${message}</h2>   </body></html>

完成创建源文件和配置文件后,导出应用程序.右键单击您的应用程序,使用 Export →  WAR文件选项并将您的HelloWeb.war文件保存在Tomcat的webapps文件夹中.

现在,启动Tomcat服务器并确保您能够从webapps文件夹访问其他网页使用标准浏览器.尝试访问URL :   http://localhost:8080/HelloWeb/hello 如果Spring Web Application一切正常,我们将看到以下屏幕.

Spring内部资源视图解析器

免责声明:以上内容(如有图片或视频亦包括在内)有转载其他网站资源,如有侵权请联系删除