零配置简单搭建SpringMVC 项目

  SpringMVC是比较经常使用的JavaWeb框架,很是轻便强悍,能简化Web开发,大大提升开发效率,在各类Web程序中普遍应用。本文采用Java Config的方式搭建SpringMVC项目,并对SpringMVC启动时加载顺序作简单的说明。html

一、SpringMVC启动流程图

二、SpringMVC项目启动流程介绍

SpringMVC 是Spring 框架的重要模块,借助于Spring 的容器技术,能够很是方面的搭建Web项目。前端

SpringMVC项目启动时要完成Spring 容器的初始化和SpringMVC配置的初始化。web

2.1 Spring容器的初始化:

一、项目中须要配置ContextLoadListener监听器,它会监听项目的启动,在项目启动时调用容器初始化方法完成Spring容器的初始化spring

若是采用XML配置,一般须要在web.xml文件里面添加以下配置:apache

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

本文采用Java Config 实现,因此在配置中继承了AbstractAnnotationConfigDispatcherServletInitializer 这个抽象类,这个类的继承关系以下:数组

在父类AbstractContextLoaderInitializer中注册了ContextLoadListener监听器:浏览器

二、在须要在容器初始化时建立的类上面加上注解,就能够实现Bean的自动装配了。mvc

@Controller @Service @Bean  @Conponent等注解均可以显示代表Bean须要自动装配app

三、配置Bean初始化的范围框架

2.2 SpringMVC 的配置

 一、配置SpringMVC须要添加DispatchServlet ,DispatcherServlet主要负责前端调用URL的分发,他在Web容器初始化的时候被注册。在2.1中,咱们已经知道,本文配置中继承了DispatchServlet 的一个抽象类AbstractAnnotationConfigDispatcherServletInitializer ,此抽象类的父类在实例化的时候会注册一个DispatchServlet到容器中,方法名以下。

二、定义视图解析器

   前端访问URL,DispatchServlet 会把URL 匹配到Controller中相应的@RequstMapper的方法上去,该方法处理完请求后返回须要的业务数据模型,而后会调用本身的视图解析器把数据渲染到前端页面中,渲染以后返回给浏览器。

视图解析器定义以下:

三、其实SpringMVC 项目启动时配置的东西还有不少,HandlerException 异常处理,数据校验等,这些Spring提供的抽象类WebMvcConfigurerAdapter中已经实现好了,咱们在项目中直接继承就好了。

三、代码实现:

项目采用Maven管理:pom.xml以下:

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

<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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>lime</groupId>
  <artifactId>web</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>web Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.1.0.RELEASE</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>web</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.7.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.20.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

项目结构以下:

RootConfig类中配置了包扫描的范围:

package config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * @Author liangmy
 * @Date 2018/9/27
 */
@Configuration
@ComponentScan(basePackages = {"example"})
public class RootConfig {
}

WebConfig 中配置了视图解析器以及RequestMapper的扫描范围

package config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

/**
 * @Author liangmy
 * @Date 2018/9/27
 */
@Configuration
@EnableWebMvc
@ComponentScan("example.controller")
public class WebConfig extends WebMvcConfigurerAdapter{

    @Bean
    public ViewResolver viewResolver(){
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        resolver.setExposeContextBeansAsAttributes(true);
        return resolver;
    }


    /**
     * 启用spring mvc 的注解
     * @param configurer
     */
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}

WebAppInitializer类配置了容器初始化时须要加载的配置类

package config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

/**
 * @Author liangmy
 * @Date 2018/9/27
 */
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    // Spring Ioc 容器配置
    @Override
    protected Class<?>[] getRootConfigClasses() {
        // 能够返回Spring的Java配置文件数组
        return new Class<?>[]{
                RootConfig.class
        };
    }

    // DispatcherServlet 的URI映射关系配置
    @Override
    protected Class<?>[] getServletConfigClasses() {
        // 能够返回Spring的Java配置文件数组
        return new Class<?>[]{
                WebConfig.class
        };
    }

    // DispatcherServlet 拦截请求匹配
    @Override
    protected String[] getServletMappings() {
        return new String[]{
                "/"
        };
    }
}

TestController中定义了测试用的URL:

package example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @Author liangmy
 * @Date 2018/9/27
 */
@Controller
public class TestController {

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String test(){
        return "test";
    }
}

 

啦啦啦

相关文章
相关标签/搜索