1.简介
本文记录Spring MVC基本项目拉起配置步骤。
2.步骤
在pom.xml中导入依赖:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>6.0.6</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>jakarta.platform</groupId>
<artifactId>jakarta.jakartaee-web-api</artifactId>
<version>9.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>6.0.6</version>
</dependency>
<dependency>
<groupId>org.eclipse</groupId>
<artifactId>yasson</artifactId>
<version>3.0.0</version>
</dependency>
添加配置类:
@Configuration
@ComponentScan("com.jojo.controller")
public class MvcConfig {
@Bean
public RequestMappingHandlerMapping handlerMapping() {
return new RequestMappingHandlerMapping();//加入ioc
}
@Bean
public RequestMappingHandlerAdapter handlerAdapter() {
return new RequestMappingHandlerAdapter();//加入ioc
}
}
添加初始化类:
public class SpringMvcInit extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[0];
}
//设置项目的配置类
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{MvcConfig.class};
}
//配置springmvc内部自动serverlet的访问地址
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
添加业务类:
@Controller
//@RequestMapping("/user")表示类下所有方法路径都加/user前缀
public class TestController {
@RequestMapping("test")//对外访问地址为/test,//其中如有*代表一层通配符,**代表多层通配符
//@RequestMapping(value = "test", method = {RequestMethod.GET,RequestMethod.POST}),另一种写法,并指定请求类型
//@PostMapping=@RequestMapping+RequestMethod.POST
//@GetMapping=@RequestMapping+RequestMethod.GET
//@PutMapping=@RequestMapping+RequestMethod.PUT
//@DeleteMapping=@RequestMapping+RequestMethod.DELETE
@ResponseBody //直接返回字符串给前端。
public String Test(){
System.out.println("good");
return "good!";
}
}
Tomcat配置:
在浏览器中访问: