先创建javaee 看另一篇文章 javaee 创建web项目
添加springmvc的依赖
- 打开pom.xml
<dependency> <groupId>jakarta.servlet</groupId> <artifactId>jakarta.servlet-api</artifactId> <version>5.0.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>6.0.7</version> </dependency>
</dependencies>
- 报错红色的话 右面选中m然后刷新一下依赖
配置SpringMvc控制器用来处理请求
- 新建一个Controller文件夹,然后在下面新建一个UserController
package Controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
* @author admin
*/
@Controller
@RestController("user")
public class userController {
@RequestMapping(value = "/user")
@ResponseBody
public String getUser(){
return "hello";
}
}
添加springmvc配置类
新建包Config 配置类在此包下新建java类
package Config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* @author admin
*/
//创建Springmvc的配置类,并加载到ioc容器中,
//加载contorller对应的bean
@Configuration
@ComponentScan(basePackages = {"Controller"})
public class SpringMvcConfig {
}
初始化Springmvc环境
package Config;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;
//定义一个servlet容器启动配置类,加载到Spring配置
public class SpringMvcInitConfig extends AbstractDispatcherServletInitializer {
// 初始化Springmvc环境
@Override
protected WebApplicationContext createServletApplicationContext() {
AnnotationConfigWebApplicationContext acwac = new AnnotationConfigWebApplicationContext();
acwac.register(SpringMvcconfig.class);
return acwac;
}
//配置Mapping路径为"/",代表所有接口接收
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
//初始化spring 环境
@Override
protected WebApplicationContext createRootApplicationContext() {
return null;
}
}
最后运行接口就可以了