你知道目前最流行的SpringMVC框架吗?如何搭建呢?

199 阅读3分钟

Spring MVC 是 Spring 家族中的一个 web 成员, 它是一种基于 Java 的实现了 Web MVC 设计思想的请求驱动类型的轻量级 Web 框架,即使用了 MVC 架构模式的思想,将 web 层进行职责解耦,基于请求驱动指的就是使用请求-响应模型,框架的目的就是帮助我们简化开发,Spring MVC 也是要简化我们日常 Web 开发的。

Spring MVC 是服务到工作者思想的实现。前端控制器是 DispatcherServlet;应用控制器拆为处理器映射器(Handler Mapping)进行处理器管理和视图解析器(View Resolver)进行视图管理;支持本地化/国际化(Locale)解析及文件上传等;提供了非常灵活的数据验证、格式化和数据绑定机制;提供了强大的约定大于配置(惯例优先原则)的契约式编程支持。

SpringMVC 搭建的方式

  1. 开发环境搭建
  2. 新建 Maven webApp
  3. Springmvc 环境 jar 包依赖
  4. 配置 web.xml (前端控制器配置)
  5. servlet-context.xml 配置
  6. 页面控制器的编写
  7. 添加视图页面
  8. 启动 jetty 服务器

案例实操

开发环境搭建

Eclipse + jdk1.7 + maven + Jetty

新建 Maven webApp

建立 springmvc01 工程并调整 web 环境。

Springmvc 环境 jar 包依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
    http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.xxx</groupId>
    <artifactId>springmvc01</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>springmvc01 Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- spring web -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
        <!-- spring mvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
        <!-- web servlet -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
        </dependency>
    </dependencies>
    <!-- jetty 插件 -->
    <build>
    <finalName>springmvc01</finalName>
    <resources>
    <resource>
    <directory>src/main/resources</directory>
    </resource>
    </resources>
    <plugins>
        <!-- 编译环境插件 -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
            <source>1.7</source>
            <target>1.7</target>
            <encoding>UTF-8</encoding>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.mortbay.jetty</groupId>
            <artifactId>maven-jetty-plugin</artifactId>
            <version>6.1.25</version>
            <configuration>
            <scanIntervalSeconds>10</scanIntervalSeconds>
            <contextPath>/springmvc01</contextPath>
            </configuration>
            </plugin>
        </plugins>
    </build>
</project>

配置 web.xml (前端控制器配置)

<?xml version="1.0" encoding="UTF-8"?> 

<web-app id="WebApp_ID" version="3.0" 

    xmlns="http://java.sun.com/xml/ns/javaee"  

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 

    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  

    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">  

    <!-- 表示容器启动时 加载上下文配置 这里指定 spring 相关配置 --> 

    <context-param> 

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

        <param-value>classpath:*.xml</param-value> 

    </context-param> 


    <!-- 启用 spring 容器环境上下文监听 --> 

    <listener> 

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

    </listener> 

    <!-- 编码过滤 utf-8 --> 

    <filter> 

        <description>char encoding filter</description> 

        <filter-name>encodingFilter</filter-name> 

        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 

        <init-param> 

            <param-name>encoding</param-name> 

            <param-value>UTF-8</param-value> 

        </init-param> 

    </filter> 

    <filter-mapping> 

        <filter-name>encodingFilter</filter-name> 

        <url-pattern>/*</url-pattern> 

    </filter-mapping> 

    <!-- servlet 请求分发器 -->  

    <servlet> 

        <servlet-name>springMvc</servlet-name> 

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

        <init-param> 

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

            <param-value>classpath:servlet-context.xml</param-value> 

        </init-param> 

        <!-- 表示启动容器时初始化该 Servlet --> 

        <load-on-startup>1</load-on-startup> 

    </servlet> 

    <servlet-mapping> 

        <servlet-name>springMvc</servlet-name> 

        <!-- 这是拦截请求, /代表拦截所有请求,拦截所有.do 请求 --> 

        <url-pattern>/</url-pattern> 

    </servlet-mapping> 

</web-app>  

要想启动我们的 springMvc 环境,目前对于 mvc 框架的配置还未进行。以上在 web.xml 中引用了 servlet-context.xml 文件。

servlet-context.xml 配置

<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:aop="http://www.springframework.org/schema/aop"  
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xsi:schemaLocation="  
        http://www.springframework.org/schema/mvc  
        http://www.springframework.org/schema/mvc/spring-mvc.xsd  
        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 
        http://www.springframework.org/schema/aop  
        http://www.springframework.org/schema/aop/spring-aop.xsd 
        http://www.springframework.org/schema/tx  
        http://www.springframework.org/schema/tx/spring-tx.xsd">  

    <!-- 扫描 com.xxx.controller 下包 --> 

    <context:component-scan base-package="com.xxx.controller" />  

    <!-- mvc 请求映射 处理器与适配器配置--> 

    <mvc:annotation-driven/>  

    <!--配置视图解析器 默认的视图解析器- --> 

    <bean id="defaultViewResolver" 

        class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 

        <property name="viewClass"  

        value="org.springframework.web.servlet.view.JstlView" /> 

        <property name="contentType" value="text/html" /> 

        <property name="prefix" value="/WEB-INF/jsp/" /> 

        <property name="suffix" value=".jsp" /> 

    </bean> 

</beans> 

如果返回乱码:配置消息转换器

<!-- 消息转换器 --> 

<mvc:message-converters register-defaults="true"> 

    <bean class="org.springframework.http.converter.StringHttpMessageConverter"> 

   	 	<property name="supportedMediaTypes" value="text/html;charset=UTF-8"/> 

    </bean> 

</mvc:message-converters> 

页面控制器的编写

/** 

* 采用注解扫描形式 

*/ 

@Controller 

public class HelloController { 

    /** 

    * 请求映射地址 /hello

    * @return 

    */ 

    @RequestMapping("/hello") 

    public ModelAndView hello(){ 

        ModelAndView mv=new ModelAndView();  

        mv.addObject("hello", "hello spring mvc"); 

        mv.setViewName("hello"); 

        return mv;  

    } 

} 

添加视图页面

在 WEB-INF 下新建 jsp 文件夹 ,并在文件加下新建 hello.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 

<% 
String path = request.getContextPath(); 
String basePath =  
request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 
%> 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 

<html> 

    <head> 

        <base href="<%=basePath%>"> 

        <title>My JSP 'hello.jsp' starting page</title> 

        <meta http-equiv="pragma" content="no-cache">

        <meta http-equiv="cache-control" content="no-cache">

        <meta http-equiv="expires" content="0">

        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

        <meta http-equiv="description" content="This is my page">

    </head>  

    <body> 

    <!-- el 表达式接收参数值 --> 

    	${hello} 

    </body> 

</html> 

启动 jetty 服务器

选中项目右键 → run as → maven build → goals 输入框中输入 jetty:run 即可启动服务器。

如果这里启动成功,浏览器(最好用强大的 chrome 或者火狐浏览器,程序员的最爱!!!)访问地址 http://localhost:8080/springmvc01/hello

最终效果如下:

至此,springmvc 环境搭建完毕。

扩展

Spring MVC 能帮我们做什么

  1. 让我们能非常简单的设计出干净的 Web 层;

  2. 进行更简洁的 Web 层的开发;

  3. 天生与 Spring 框架集成(如 IoC 容器、AOP 等);

  4. 提供强大的约定大于配置的契约式编程支持;

  5. 能简单的进行 Web 层的单元测试;

  6. 支持灵活的 URL 到页面控制器的映射;

  7. 非常容易与其他视图技术集成,如 Velocity、FreeMarker 等等,因为模型 数据不放在特定的 API 里,而是放在一个 Model 里(Map 数据结构实现,因此很容易被其他框架使用);

  8. 非常灵活的数据验证、格式化和数据绑定机制,能使用任何对象进行数据绑定,不必实现特定框架的 API;

  9. 支持灵活的本地化等解析;

  10. 更加简单的异常处理;

  11. 对静态资源的支持;

  12. 支持 Restful 风格。