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了!
这里写图片描述

到这里,最基础的环境就搭建好了,能不配置的都没有配置。

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