Spring MVC 學習(一)

Spring MVC 環境搭建

1.引入Jar包

在Eclipse中新建一個Maven Web項目,然後在Pom中加入SpringMVC包如下:

<properties>
        <!-- Web -->
        <jsp.version>2.2</jsp.version>
        <jstl.version>1.2</jstl.version>
        <servlet.version>2.5</servlet.version>
        <!-- Spring -->
        <spring-framework.version>4.1.5.RELEASE</spring-framework.version>
    </properties>
    <dependencies>
        <!-- Spring MVC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>
        <!-- Other Web dependencies -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>${servlet.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>${jsp.version}</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

2.WebApplicationContext

The WebApplicationContext is an extension of the plain ApplicationContext that has some extra features necessary for web applications. It differs from a normal ApplicationContext in that it is capable of resolving themes (see Section 17.9, “Using themes”), and that it knows which Servlet it is associated with (by having a link to the ServletContext). The WebApplicationContext is bound in the ServletContext, and by using static methods on the RequestContextUtils class you can always look up the WebApplicationContext if you need access to it.

applicationContext是Spring的核心,Context我們通常解釋爲上下文環境,但是我們常用容器來稱呼,ApplicationContext則是“應用的容器”。Spring把Bean放在這個容器中,在需要的時候,用getBean方法取出——實際使用的是一個工廠模式。
在Web應用中,我們會用到WebApplicationContext,用於存放一些Web應用的Bean。
WebApplicationContext繼承自ApplicationContext。然後Spring將其放到ServletContext當中,如果你需要它,可以通過RequestContextUtils拿出來。

RequestContextUtils.getWebApplicationContext(request);

public static WebApplicationContext getWebApplicationContext(ServletRequest request)
        throws IllegalStateException {

        return getWebApplicationContext(request, null);
    }

在Web應用中,WebAppliactionContext初始化有以下兩種方式:
1.監聽器方式(org.springframework.web.context.ContextLoaderListener)

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

2.自啓動Servlet方式(org.springframework.web.context.ContextLoaderServlet)

<servlet>
    <servlet-name>springContextLoaderServlet</servlet-name>
    <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

或者使用代碼來初始化

public class MyWebApplicationInitializer implements WebApplicationInitializer {

    public void onStartup(ServletContext container) throws ServletException {
        ...
    }
}

3.DispatcherServlet

這裏寫圖片描述
從圖中可以看出:
ContextLoaderListener初始化的上下文加載的Bean是對於整個應用程序共享的,不管是使用什麼表現層技術,一般如DAO層、Service層Bean;
DispatcherServlet初始化的上下文加載的Bean是隻對Spring Web MVC有效的Bean,如Controller、HandlerMapping、HandlerAdapter等等,該初始化上下文應該只加載Web相關組件。

配置DispatcherServlet:
Web.xml中加入:

    </context-param>
    <servlet>
        <servlet-name>example</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>example</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <listener>

或者代碼方式初始化
或者使用代碼來初始化

public class MyWebApplicationInitializer implements WebApplicationInitializer {

    public void onStartup(ServletContext container) throws ServletException {
        ServletRegistration.Dynamic registration = container.addServlet("example", new DispatcherServlet());
        registration.setLoadOnStartup(1);
        registration.addMapping("/example/*");
    }
}

4.Implementing Controllers

@Controller
public class HelloWorldController {

    @RequestMapping("/helloWorld")
    public String helloWorld(Model model) {
        model.addAttribute("message", "Hello World!");
        return "index";
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd">
    <context:component-scan base-package="org.springframework.springMVC"/>
    <!-- ... -->
</beans>

這時你啓動項目,發現啓動信息中有:

二月 24, 2015 6:09:18 下午 org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping registerHandler
信息: Mapped URL path [/helloWorld/] onto handler 'helloWorldController'

說明Controller註冊成功了!這時項目結構如下:
這裏寫圖片描述
這時你你打開瀏覽器,訪問http://localhost:8080/springMVC/helloWorld.發現出現了404頁面,去控制檯一看:

二月 24, 2015 6:14:05 下午 org.springframework.web.servlet.PageNotFound noHandlerFound
警告: No mapping found for HTTP request with URI [/springMVC/index] in DispatcherServlet with name 'example'

springMVC/index沒有配置相應的後綴名,這時在springMVC配置文件中加入:

 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />

這時,就OK了!
這裏寫圖片描述

到這裏,最基礎的環境就搭建好了,能不配置的都沒有配置。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章