手动创建springmvc项目的步骤
用到的注解符号创建一个maven-archetype-webapp项目进行项目配置项目结构
用到的注解符号
@Controller @RequestMapping @ResponseBody
创建一个maven-archetype-webapp项目
) [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xGuTHCSp-1682673668045)(assets/create-project.png)]
进行项目配置
导入依赖包 在pom.xml文件里导入依赖包的坐标,导入效果如下图
javax.servlet
javax.servlet-api
3.1.0
provided
org.springframework
spring-webmvc
5.2.10.RELEASE
定义bean 通过创建一个UserController类来实现,项目结构请参阅文章结尾
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
//2.制作Bean
//2.1 使用@Controller 定义Bean
@Controller
public class UserController {
//2.2 定义请求径
@RequestMapping("/save")
//2.3 定义返回值类型
@ResponseBody
public String save(){
System.out.println("save...");
return "{'module':'save'}";
}
}
创建springServlet容器 通过创建SpringMvcConfig类来实现
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
//3.创建spring容器
//3.1 通过@Configuration定义容器
@Configuration
//3.2 通过@ComponentScan定义容器管理范围
@ComponentScan("com.lipeng.controller")
public class SpringMvcConfig {
}
初始化web服务器,加载上边创建的springServlet容器,通过创建SpringWebInit类开实现
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;
//4 初始化SpringWeb的环境
public class SpringWebInit extends AbstractDispatcherServletInitializer {
//加载springmvc容器
protected WebApplicationContext createServletApplicationContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(SpringMvcConfig.class);
return context;
}
//定义哪些请求归springmvc处理
protected String[] getServletMappings() {
return new String[]{"/"};
}
//加载spring容器
protected WebApplicationContext createRootApplicationContext() {
return null;
}
}
项目结构
![在这里插入图片描述](https://img-blog.csdnimg.cn/c91b7888eb344d22823d5dcb06e4cca9.png#pic_center)
|