当前位置: 首页> 房产> 政策 > idea 2023.2快速搭建并初始化SpringMVC框架项目

idea 2023.2快速搭建并初始化SpringMVC框架项目

时间:2025/7/14 0:24:17来源:https://blog.csdn.net/weixin_50147548/article/details/139259574 浏览次数:0次

先创建javaee 看另一篇文章 javaee 创建web项目

添加springmvc的依赖

  1. 打开pom.xml
  2.  <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>
  1. 报错红色的话 右面选中m然后刷新一下依赖

配置SpringMvc控制器用来处理请求

  1. 新建一个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")@ResponseBodypublic  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环境@Overrideprotected WebApplicationContext createServletApplicationContext() {AnnotationConfigWebApplicationContext acwac = new AnnotationConfigWebApplicationContext();acwac.register(SpringMvcconfig.class);return acwac;}
//配置Mapping路径为"/",代表所有接口接收@Overrideprotected String[] getServletMappings() {return new String[]{"/"};}//初始化spring 环境@Overrideprotected WebApplicationContext createRootApplicationContext() {return null;}
}

最后运行接口就可以了
在这里插入图片描述

关键字:idea 2023.2快速搭建并初始化SpringMVC框架项目

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: