Spring(Spring MVC):Part one
2010-11-07 00:39 横刀天笑 阅读(1099) 评论(0) 编辑 收藏 举报I think read open source code is a good way to learn programming skill.DI is very important in OO programming,and Spring is a very power IoC container in Java world.So I choose Spring to learn.
If you want to read a software’s code,you should start with it’s entry point.I think may be Spring MVC is a entry point for Spring.So we can start with Spring MVC,and then go into Spring internal.
Spring MVC is a MVC framework,and it’s base on Spring IoC container,so it’s very flexible.You can write like this to create a controller:
1: @Controller
2: @RequestMapping("home")
3: public class HomeController
4: {
5: @RequestMapping("/index")
6: public ModelAndView index()
7: {
8: return new ModelAndView("index");
9: }
10:
11: @RequestMapping(value="/login",method=RequestMethod.POST)
12: public ModelAndView login(User user)
13: {
14: //do something
15: return new ModelAndView(...);
16: }
17: }
That’s very clear,just some annotations from Spring,not introduce any additional classes,you don’t need extend any base class.You can reuse this code anywhere if you want.
As early mentioned,we should find a entry point when we read code.In Spring MVC,the org.springframework.web.servlet.DispatcherServlet is the entry point,so we read it first.
If you develop a Spring MVC application,you must config the DispatcherServlet in the web.xml like this:
1: <servlet>
2: <servlet-name>book</servlet-name>
3: <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
4: <init-param>
5: <param-name>contextConfigLocation</param-name>
6: <param-value>
7: spring-book-servlet.xml
8: </param-value>
9: </init-param>
10: </servlet>
DispatcherServlet is a standard HttpServlet.DispatcherServlet inherit from FrameworkServlet,FrameworkServlet inherit from HttpServletBean,and HttpServletBean inherit from HttpServlet.
You can find a init() method in HttpServletBean,this is the java HttpSerlvet initlization method.This method will call two virtual methods,these two methods will be implemented by FrameworkServlet.FrameworkSevlet will initlization WebApplicationContext(Spring context),and delegate doGet,doPost,doPut,doDelete,doOptions to doService.doService is an abstract method,so FrameworkServlet’s subclass must implement this method.
In the FrameworkServlet’s initServletBean method(override method),call initWebApplicationContext method and iniFrameworkServlet method.initWebApplicationContext will call onRefresh method.onRefresh is a virtual method,it will be implemented by DispatcherServlet.
I will introduce the DispatcherServlet in next article detail.
Thanks~