以下示例演示如何使用Spring MVC Framework编写基于Web的简单应用程序,该框架可以借助< mvc:resources> 标记访问静态页面和动态页面.
首先,让我们使用一个有效的Eclipse IDE,并遵循以下步骤,使用Spring Web Framework开发基于动态表单的Web应用程序.
Step | Description |
---|---|
1 | 创建一个名为HelloWeb的项目一个包com.it1352,如Spring MVC - Hello World章节中所述. |
2 | 在com.it1352包下创建一个Java类WebController. |
3 | 在jsp子文件夹下创建一个静态文件 final.htm . |
4 | |
5 | 最后一步是创建源文件和配置文件的内容并导出应用程序,如下所述. |
package com.it1352; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class WebController { @RequestMapping(value = "/index", method = RequestMethod.GET) public String index() { return "index"; } @RequestMapping(value = "/staticPage", method = RequestMethod.GET) public String redirect() { return "redirect:/pages/final.htm"; } }
<?xml version = "1.0" encoding = "UTF-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = " http://www.w3.org/2001/XMLSchema-instance" xmlns:context = "http://www.springframework.org/schema/context" xmlns:mvc = "http://www.springframework.org/schema/mvc" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-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 id = "viewResolver" class = "org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name = "prefix" value = "/WEB-INF/jsp/" /> <property name = "suffix" value = ".jsp" /> </bean> <mvc:resources mapping = "/pages/**" location = "/WEB-INF/pages/" /> <mvc:annotation-driven/> </beans>
此处,< mvc:resources ..../> 标记用于映射静态页面. mapping属性必须是 Ant模式,它指定http请求的URL模式. location属性必须指定一个或多个有效资源目录位置,其中包含静态页面,包括图像,样式表,JavaScript和其他静态内容.可以使用以逗号分隔的值列表来指定多个资源位置.
以下是Spring视图文件的内容 WEB-INF/jsp/index.jsp .这将是一个登陆页面;此页面将发送访问 staticPage服务方法的请求,该方法将此请求重定向到WEB-INF/pages文件夹中可用的静态页面.
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%> <html> <head> <title>Spring Landing Page</title> </head> <body> <h2>Spring Landing Pag</h2> <p>Click below button to get a simple HTML page</p> <form:form method = "GET" action = "/HelloWeb/staticPage"> <table> <tr> <td> <input type = "submit" value = "Get HTML Page"/> </td> </tr> </table> </form:form> </body> </html>
<html> <head> <title>Spring Static Page</title> </head> <body> <h2>A simple HTML page</h2> </body> </html>
完成创建源文件和配置文件后,导出应用程序.右键单击您的应用程序,使用Export → WAR文件选项并将您的HelloWeb.war文件保存在Tomcat的webapps文件夹中.
现在,启动Tomcat服务器并确保您能够使用标准浏览器从webapps文件夹访问其他网页.现在尝试访问URL - http://localhost:8080/HelloWeb/index.如果使用Spring Web Application一切正常,我们将看到以下屏幕.
单击"获取HTML页面"按钮以访问staticPage服务方法中提到的静态页面.如果您的Spring Web应用程序一切正常,我们将看到以下屏幕.