零配置简单搭建SpringMVC 项目

  SpringMVC是比较常用的JavaWeb框架,非常轻便强悍,能简化Web开发,大大提高开发效率,在各种Web程序中广泛应用。本文采用Java Config的方式搭建SpringMVC项目,并对SpringMVC启动时加载顺序做简单的说明。

1、SpringMVC启动流程图

2、SpringMVC项目启动流程介绍

SpringMVC 是Spring 框架的重要模块,借助于Spring 的容器技术,可以非常方面的搭建Web项目。

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

2.1 Spring容器的初始化:

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

如果采用XML配置,通常需要在web.xml文件里面添加如下配置:

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

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

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

2、在需要在容器初始化时创建的类上面加上注解,就可以实现Bean的自动装配了。

@Controller @Service @Bean  @Conponent等注解都可以显示表明Bean需要自动装配

3、配置Bean初始化的范围

2.2 SpringMVC 的配置

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

2、定义视图解析器

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

视图解析器定义如下:

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

3、代码实现:

项目采用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";
    }
}

啦啦啦

原文地址:https://www.cnblogs.com/ClassNotFoundException/p/9715259.html

时间: 2024-08-03 14:34:12

零配置简单搭建SpringMVC 项目的相关文章

maven -- 实现在Eclipse用maven搭建springmvc项目(附构建步骤和详细实现代码)

Learn from:http://www.cnblogs.com/fangjins/archive/2012/05/06/2485459.html,感谢楼主的分享,才有下面的这篇学习小结 一.环境准备 (1)装有Maven插件的eclipse,http://www.cnblogs.com/lmei/p/4782882.html maven的setting.xml配置说明 http://www.cnblogs.com/lmei/p/4788377.html 之前在配置过程中遇到了几个问题: 问题

Maven搭建SpringMVC项目详解

前言 上一次复习搭建了SpringMVC+Mybatis,这次搭建一下SpringMVC,采用的是SpringJDBC,没有采用任何其他的ORM框架,SpringMVC提供了一整套的WEB框架,所以如果想搭建纯的SpringMVC的话,而且不必映入别的任何框架,SpringMVC都给我们提供了,下面试Spring + SpringMVC的详细搭建过程. 项目包含:数据库mysql(其实那个数据库都无所谓),连接池采用的是c3p0. 1.创建数据表 数据表很简单,user_info 2.搭建Mav

项目搭建系列之一:使用Maven搭建SpringMVC项目

约定电脑都安装了eclipse,且已配置好Maven以及eclipse插件. 1.Eclipse 2.maven 3.Eclipse 需要安装maven插件.url:maven - http://download.eclipse.org/technology/m2e/releases . 1.新建一个Maven Project 2.选择工作空间 3.搭建Web工程,我们选择maven-archetype-webapp类型 4.填写项目参数,如图 5.以上步骤完成时的工程结构目录 6.可以查看或修

使用VSCode配置简单的vue项目

由于最近要使用的项目框架为前后端分离的,采用的是vue.js+webAPI的形式进行开发的.因为之前我没有接触过vue.js,也只是通过视频文档做了一些简单的练习.今天技术主管说让大家熟悉下VSCode开发vue,所以自己摸索了好久,才算是把简单的项目配置成功了.后续还得自己多了解这方面的知识.想着怕时间长了自己会忘记,所以写下来也供有需要的人一起学习. 一.配置环境 1.1 下载VSCode,官网直接下载就行. 1.2 汉化VSCode Ctrl+Shift+P 输入 "configure d

基于XML搭建SpringMVC项目

*如果你需要将应用部署到不支持Servlet3.0容器中 或者 你只是对web.xml情有独钟,那我们只能按照传统的方式,通过web.xml来配置SpringMVC. *搭建SpringMVC需要在web.xml中注册DispatcherServlet和ContextLoaderListener,同时他们两个之间会分别通过上下文参数contextConfigLocation指定一个XML文件地址来加载Spring应用上下文,而我更倾向于使用Java配置类来加载Spring应用上下文(本文也是如此

用Spring Boot零配置快速创建web项目(1)

一.Spring Boot简介 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置.通过这种方式,Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者. 本文是一个springboot入门级的helloworld程序. 二.maven安装与配置 下载地址:http://maven.apache

使用maven简单搭建springmvc

介绍 Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面.Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块.使用 Spring 可插入的 MVC 架构,从而在使用Spring进行WEB开发时,可以选择使用Spring的Spring MVC框架或集成其他MVC开发框架,如Struts1(现在一般不用),Struts 2(一般老项目使用)等. 优点 Lifecycle for overriding binding, va

快速搭建 springmvc 项目

1. Jar 包 <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.

用java 配置方式 搭建springmvc + spring data jpg + mysql

主要记录下java config 的方式配置项目 pom.xml <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency