Spring webmvc框架真是一柄利器,让web应用的开发变得如此简单美妙。
如何使用MVC框架,其内部原理又是怎样的呢?
下面首先写个最简单的小例子,周末小玩具,玩具小巧却能小跑;)
1. New Java Project named MVC.
2. Web.xml的配置
<?xmlversion="1.0"encoding="UTF-8"?>
<web-appversion="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">
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>www.root</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:spring-*.xml,
classpath*:/spring/*.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app
3. Spring-servlet.xml
<?xmlversion="1.0"encoding="utf-8"?>
<beansxmlns="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"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"
default-autowire="byName">
<context:component-scanbase-package="com.exercise"/>
<beanid="viewResolver"class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<propertyname="prefix"value="/"/>
<propertyname="suffix"value=".jsp"/>
</bean>
</beans>
4. Pom.xml:
<projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>exercise</groupId>
<artifactId>exercise-wwwmvc-webapp</artifactId>
<packaging>war</packaging>
<version>2.0.0</version>
<name>spring-wwwmvc-webapp</name>
<url>http://maven.apache.org</url>
<properties>
<org.springframework.version>3.0.3.RELEASE</org.springframework.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.4</version>
</dependency>
</dependencies>
<build>
<finalName>webmvc</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<version>6.1.26</version>
<configuration>
<webApp>${basedir}/target/www</webApp>
<contextPath>/</contextPath>
<scanIntervalSeconds>0</scanIntervalSeconds>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
</resource>
</resources>
</build>
</project>
5. Nick1.jsp(src/main/webapp)
<%@ page isELIgnored="false"%>
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglibprefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglibprefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<div>
<form method="post" action="/nickOperate">
<input name="nick" type="text" value="${nick}">
<button type="submit" style="width:90px;height:25px;">提交</button>
</br>
</form>
</div>
6. NickController
package com.exercise.mvc;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Controller
public classNickController {
@RequestMapping("/nickOperate")
publicString processNick(HttpServletRequest request, HttpServletResponse response)throws Exception {
String nick = request.getParameter("nick");
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
request.setAttribute("time", df.format(new Date()));
request.setAttribute("nick", nick);
return "hello2";
}
}
7. Hello2.jsp
<%@ page isELIgnored="false"%>
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglibprefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglibprefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<div>
<span>hello</span>${nick}<span>, now time is ${time}</span>
</div>
8. 启动jetty服务器
9. 浏览器直接输入http://127.0.0.1/nick1.jsp
然后再输入框中写上昵称,点击提交,就会跳转到问好页面:
下面要剖开现象看下本质啦,来看看我们引入的DispatcherServlet类中到底都做了什么?
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
DispatcherServlet这个servlet的doService()方法:
1. 往request中放入WebApplicationContext、localeResolver、themeResolver、themeSource
2. 多重检查入参
3. 从HandlerMapping中根据入参request获取对应的handler后(如果没有对应的handler则返回404错误),获取handler的interceptors。首先对每个拦截器执行预处理,然后取得handler对应的HandlerAdapter,执行其handle方法,返回执行结果ModelAndView。(如果ModelAndView为null则根据request返回默认的ModelAndView),最后执行每个拦截器的后处理方法。
4. 根据ModelAndView进行render跳转。
就是说spring webmvc框架已经帮我们做了如下工作:http请求一进来就被DispatcherServlet拦截下来,根据请求参数依次从DefaultAnnotationHandlerMapping、SimpleUrlHandlerMapping、或者默认Handler中获取控制器,取到控制器相应的拦截器HandlerInterceptor,来依据规则分发到目标Controller(相当于Action)来处理,再下来就是Controller调配ModelAndView了。