SpringMVC 专题
您的位置:java > SpringMVC专题 > Spring MVC Xml视图解析器
Spring MVC Xml视图解析器
作者:--    发布时间:2019-11-19

xmlviewresolver用于在xml文件中定义的视图bean来解析视图名称。以下示例演示如何在spring web mvc框架使用xmlviewresolver

xmlviewresolver-servlet.xml 配置如下所示 -

<bean class="org.springframework.web.servlet.view.xmlviewresolver">
   <property name="location">
      <value>/web-inf/views.xml</value>
   </property>
</bean>

views.xml 配置如下所示 -

<bean id="hello"
   class="org.springframework.web.servlet.view.jstlview">
   <property name="url" value="/web-inf/jsp/hello.jsp" />
</bean>

例如,使用上面的配置,如果uri

  • 对于/hello请求,dispatcherservlet会将请求转发到由view.xml中定义的hello对应的 hello.jsp

首先,让我们使用eclipse ide,并按照以下步骤使用spring web framework开发基于动态表单的web应用程序:

  1. 创建一个名称为 xmlviewresolver 的动态web项目。
  2. com.h3.springmvc 包下创建一个java类hellocontroller
  3. jsp子文件夹下创建一个视图文件:hello.jsp
  4. 下载jstl库jstl.jar。 把它放在 classpath 中。
  5. 最后一步是创建所有源和配置文件的内容并运行应用程序,详细如下所述。

完整的项目文件目录结构如下所示 -

hellocontroller.java 的代码如下所示 -

package com.h3.springmvc;
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";
   }

}

xmlviewresolver-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.h3.springmvc" />

   <bean class="org.springframework.web.servlet.view.xmlviewresolver">
      <property name="location">
         <value>/web-inf/views.xml</value>
      </property>
   </bean>
</beans>

views.xml 配置如下所示 -

<bean id="hello"
   class="org.springframework.web.servlet.view.jstlview">
   <property name="url" value="/web-inf/jsp/hello.jsp" />
</bean>

hello.jsp 的代码如下所示 -

<%@ page contenttype="text/html; charset=utf-8" %>
<html>
<head>
<title>hello world</title>
</head>
<body>
   <h2>${message}</h2>
</body>
</html>

完成创建源和配置文件后,发布应用程序到tomcat服务器。

现在启动tomcat服务器,当访问url => http://localhost:8080/xmlviewresolver/hello , 如果spring web应用程序没有问题,应该看到以下结果:


网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册