基本结构
首先导入依赖pom
<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>org</groupId>
<artifactId>rumeng</artifactId>
<version>1.0-SNAPSHOT</version>
<!-- 这里是war包-->
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<!-- tomcat插件 -->
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<!-- 设置端口号8088 -->
<port>8088</port>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
</project>
编写controller对象
// 定义controller
// 用于返回json数据
@Controller
public class Usercontroller {
// 设置访问路径
@RequestMapping("/hellow")
// 设置返回的东西响应到外面
@ResponseBody
public String hellow(){
// 可以给这个方法写一个日志方便查看
System.out.println("日志 : "+this.getClass().getName()+" 的hellow()方法被调用");
return "hellow springMVC";
}
}
写配置类
@Configuration
@ComponentScan("org.text01.controller")
public class Springconfig {
}
配置servlet类
这里不需要写bean以及注释,spring会自己将其装置到容器中
// 设置一个servlet配置类使其继承AbstractDispatcherServletInitializer
// 在里面加载spring配置
public class SpringMVC_servlet extends AbstractDispatcherServletInitializer {
// 加载springMVC容器配置
protected WebApplicationContext createServletApplicationContext() {
// 配置AnnotationConfigWebApplicationContext类型的IOC容器
AnnotationConfigWebApplicationContext ioc = new AnnotationConfigWebApplicationContext();
// 将配置类放入
ioc.register(Springconfig.class);
return ioc;
}
// 设置MVC请求归属处理
protected String[] getServletMappings() {
// 设置那些请求路径归springMVC处理
// `/` 代表全部路径
return new String[]{"/"};
}
// 加载spring容器配置
protected WebApplicationContext createRootApplicationContext() {
return null;
}
}
运行maven工程
配置运行
运行
可以从运行框中看到访问基本路径
显示以下信息就是启动成功
打开浏览器输入controller写的路径
运行窗口可以看到写的日志证明方法被调用