文章目录
-
- 创建Maven项目
- 导入坐标
- 创建ConTroller
- 创建SpringMvcConfig
- 创建Servlet容器的启动的配置类
创建Maven项目
1.创建Maven项目,勾选webapp骨架,点击next,
导入坐标
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
添加启动tomcat服务器需要的插件:
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<path>/</path>
<port>80</port>
</configuration>
</plugin>
创建ConTroller
@Controller
public class UserController {
//设置当前操作的访问路径
@RequestMapping("/save")
//设置当前操作的返回值类型
@ResponseBody//意思是把return 返回的东西整体作为响应内容,给到前端
public String save(){
System.out.println("user save...");
return "{'module':'springmvc'}";
}
@RequestMapping("/delete")
@ResponseBody
public String delete(){
System.out.println("user delete...");
return "{'module':'springmvc delete'}";
}
}
创建SpringMvcConfig
/**
* 创建是Spring的配置文件,加载controller 对应的bean
*/
@Configuration
@ComponentScan("com.itbaima.controller")
public class SpringMvcConfig {
}
创建Servlet容器的启动的配置类
/**
* 定义一个servlet容器启动的配置类,在里面加载Spring的配置
*/
public class ServletContainersInitConfig extends AbstractDispatcherServletInitializer {
@Override
protected WebApplicationContext createServletApplicationContext() {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(SpringMvcConfig.class);
return ctx;
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
@Override
protected WebApplicationContext createRootApplicationContext() {
return null;
}
}