您的位置:首页 > 编程语言 > Java开发

Spring(Spring MVC):Part one

2010-11-07 00:39 387 查看
I think read open source code is a good way tolearn 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:

[code] @Controller


@RequestMapping("home")


public class HomeController


{


@RequestMapping("/index")


public ModelAndView index()


{


return new ModelAndView("index");


}




 @RequestMapping(value="/login",method=RequestMethod.POST)


 public ModelAndView login(User user)


{


//do something


return new ModelAndView(...);


}


}

[/code]

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:

[code] <servlet>


 <servlet-name>book</servlet-name>


 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>


 <init-param>


 <param-name>contextConfigLocation</param-name>


 <param-value>


 spring-book-servlet.xml


 </param-value>


 </init-param>


</servlet>

[/code]

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~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: