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

发布于:2024-06-01 ⋅ 阅读:(234) ⋅ 点赞:(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")
 @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;
    }
}

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


网站公告

今日签到

点亮在社区的每一天
去签到