1、创建javassm的maven项目
创建一个普通的Maven工程(不用加任何脚手架或者web)。
2、添加依赖
添加SpringMVC依赖和servlet-api依赖:
<!--war包部署-->
<packaging>war</packaging>
<dependencies>
<!--添加webmvc依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<!--添加servlet依赖-->
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
3、添加Spring配置
SpringConfig.java:
package com.cs.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;
import java.lang.annotation.Annotation;
/**
* @ClassName SpringConfig
* @Description TODO
* @Author chengshan
* @Date 2020/6/13 22:59
* @Version 1.0
**/
@Configuration
@ComponentScan(basePackages = "com.cs",useDefaultFilters = true,
excludeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION,classes = Controller.class)})
public class SpringConfig {
}
- @Configuration注解表示这是一个配置类,这个配置的作用类似于applicationContext.xml
- @ComponentScan注解表示配置包扫描,里面的属性和xml配置中的属性是一一对应的。useDefaultFileters表示使用默认的过滤器,然后又除去了Controller注解,即在Spring容器中扫描除去了Controller之外的其他所有Bean。
4、添加SpringMVC配置
SpringMVCConfig.java:
package com.cs.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;
/**
* @ClassName SpringMvcConfig
* @Description TODO
* @Author chengshan
* @Date 2020/6/13 23:00
* @Version 1.0
**/
@Configuration
@ComponentScan(basePackages = "com.cs",useDefaultFilters = false,
includeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION,classes = Controller.class)})
public class SpringMVCConfig {
}
注意:如果不需要在SpringMVC中添加其他额外的配置的话,这样就可以了,即视图解析器、JSON解析、文件上传…等等,如果都不需要配置的话,这样就可以了。
5、配置web.xml
我们不用web.xml,使用Java代码去代替web.xml文件,这里会用到WebApplicationInitializer。
WebInit.java:
package com.cs.config;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
/**
* @ClassName WebInit
* @Description TODO
* @Author chengshan
* @Date 2020/6/13 23:07
* @Version 1.0
**/
public class WebInit implements WebApplicationInitializer {
/*
* @Author chengshan
* @Description 启动加载
* @Date 2020/6/13 23:07
* @Param [servletContext]
* @return void
**/
public void onStartup(ServletContext servletContext) throws ServletException {
//首先加载SpringMVC的配置文件
AnnotationConfigWebApplicationContext context =