我使用的是MyEclipse6.5,新建一个Web Project,添加Spring 2.5 Core Libraries,Spring 2.5 Web Libraries.
修改web.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/dispatcherServlet-servlet.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
这样web启动的时候就会自动加载dispatcherServlet类,读取dispatcherServlet-servlet.xml文件的配置信息,并且扩展名为do的文件都会通过配置信息,执行相关流程。
然后我们建立dispatcherServlet-servlet.xml文件,文件内容为:浏览/helloWorld.do,输出内容为:Hello Word
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="helloWorld.do">helloWorldAction</prop>
</props>
</property>
</bean>
<bean id="helloWorldAction" class="cn.HelloWorldAction">
<property name="hello">
<value>Hello World!</value>
</property>
</bean>
</beans>
这样就建立了一个映射关系,如果访问helloWorld.do,就会执行bean的id为helloWorldAction的类cn.HelloWorldAction
然后我再来写HelloWorldAction类:
package cn;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
public class HelloWorldAction implements Controller {
private String hello;
public ModelAndView handleRequest(HttpServletRequest arg0,
HttpServletResponse arg1) throws Exception {
Map model =new HashMap();
model.put("msg", this.getHello());
return new ModelAndView("/jsp/hello.jsp",model);
}
public String getHello() {
return hello;
}
public void setHello(String hello) {
this.hello = hello;
}
}
这个类实现了接口Controller,并且把页面返回到页面/jsp/hello.jsp
最后就是页面/jsp/hello.jsp了:
<%@ page contentType="text/html;charset=GB2312" %>
<html>
<body>
<%=request.getAttribute("msg")%>
</body>
</html>
HelloWorldAction类中的hello,是通过dispatcherServlet-servlet.xml文件注入的
/jsp/hello.jsp页面中的msg,是通过Map传到页面的request中
到此,第一段Spring MVC的代码就完成了。