Spring的MVC模型运行序列分析

类别:Java 点击:0 评论:0 推荐:

1)假定你的请求为http://localhost:8080/springapp/index.jsp
2)为安全考虑,在index.jsp中将请求redirect到WEB-INF目录下:
  <c:redirect url="/hello.htm"/>
3)在web.xml中,对*.htm的请求都发到
org.springframework.web.servlet.DispatcherServlet进行处理:

  <servlet>
    <servlet-name>springapp</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>springapp</servlet-name>
    <url-pattern>*.htm</url-pattern>
  </servlet-mapping>
4)org.springframework.web.servlet.DispatcherServlet会获取当前应用名称apringapp,
并自动到WEB-INF目录下寻找并解析springapp-servlet.xml文件.
5)在springapp-servlet.xml文件中,将/hello.htm转发到springappController
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="/hello.htm">springappController</prop>
            </props>
        </property>
</bean>
6)在springapp-servlet.xml文件中,配置springappController对应的类文件
<bean id="springappController" class="web.SpringappController">
        <property name="productManager">
            <ref bean="prodMan"/>
        </property>
</bean>
7)实现你自己的控制器类web.SpringappController,举例如下:
package web;

import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import bus.Product;
import bus.ProductManager;

public class SpringappController implements Controller {

    /** Logger for this class and subclasses */
    protected final Log logger = LogFactory.getLog(getClass());

    private ProductManager prodMan;

    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String now = (new java.util.Date()).toString();
        logger.info("returning hello view with " + now);

        Map myModel = new HashMap();
        myModel.put("now", now);
        myModel.put("products", getProductManager().getProducts());

        return new ModelAndView("hello", "model", myModel);
    }

    public void setProductManager(ProductManager pm) {
        prodMan = pm;
    }

    public ProductManager getProductManager() {
        return prodMan;
    }
}
注意,控制器中采用了IOC模式的type2方式.
8)你返回的ModelAndView有三个参数,第一个是下个view的名称,
第二个是Model Object的别名,第三个是Model Object对象,后两个参数
将在下个VIEW中使用.

本文地址:http://com.8s8s.com/it/it15332.htm