以下示例演示如何使用spring mvc框架编写一个简单的基于web的hello world
应用程序。首先使用eclipse ide,并按照以下步骤使用spring web framework开发一个动态web应用程序:
创建一个名为helloweb
的动态web项目,并在创建的项目中的src
文件夹下创建一个包com.h3.springmvc
。
将下面提到的spring和其他库拖放到文件夹webcontent/web-inf/lib
中。
com.h3.springmvc
包下创建一个java类hellocontroller
。webcontent/web-inf
文件夹下创建spring配置文件web.xml
和helloweb-servlet.xml
。webcontent/web-inf
文件夹下创建一个名为jsp
的子文件夹。在此子文件夹下创建视图文件hello.jsp
。创建完成后,整个工程的目录结构如下图所示 -
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";
}
}
web.xml
<web-app id="webapp_id" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
xsi:schemalocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>spring mvc application</display-name>
<servlet>
<servlet-name>helloweb</servlet-name>
<servlet-class>
org.springframework.web.servlet.dispatcherservlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>helloweb</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
helloweb-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" />
<bean class="org.springframework.web.servlet.view.internalresourceviewresolver">
<property name="prefix" value="/web-inf/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
hello.jsp
<%@ page contenttype="text/html; charset=utf-8" %>
<html>
<head>
<title>hello world</title>
</head>
<body>
<h2>hello, ${message}</h2>
</body>
</html>
最后,以下是要包括在web应用程序中的spring和其他库的列表。只需拖动这些文件并将其放在webcontent/web-inf/lib
文件夹中。
完成创建源和配置文件后,导出应用程序。右键单击您的应用程序,并使用导出> war文件选项,并将 helloweb.war
文件保存在tomcat的webapps
文件夹中。
现在启动 tomcat 服务器,并确保能够使用标准浏览器访问到 webapps
文件夹的其他网页。 现在尝试访问url => http://localhost:8080/helloweb/hello
,如果一切都没有问题,spring web应用程序,应该看到以下结果:
应该要注意,在给定的url中,helloweb
是应用程序名称,hello
是在控制器中使用@requestmapping(“/hello”)
提到的虚拟子文件夹。在使用@requestmapping(“/”)
映射到url时,可以直接使用根(“/“),在这种情况下,可以使用短url => http://localhost:8080/helloweb/
访问同一页面,但建议使用不同的文件夹。
注意:如果没有在eclipse上安装配置过tomcat服务器,在 window -> preference -> server -> runtime environments 设置。