java-springmvc

1、入门案例

1.1、导包

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-webmvc</artifactId>
	<version>5.3.18</version>
</dependency>
<dependency>
	<groupId>javax.servlet</groupId>
	<artifactId>javax.servlet-api</artifactId>
	<version>3.1.0</version>
	<scope>provided</scope>
</dependency>

1.2、编写配置类,初始化SpringMvc

@Configuration
@ComponentScan("cn.tjhis.controller")
public class SpringMvcConfig {
}

1.3、创建web容器启动类,初始化Servlet类,加在SpringMvc环境,并设置请求的拦截

public class ServletContainersInitConfig extends AbstractDispatcherServletInitializer {
    // 加载Spring容器的配置
    @Override
    protected WebApplicationContext createServletApplicationContext() {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(SpringMvcConfig.class);
        return context;
    }
    // 设置那些请求归SpringMvc处理
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
    // 加在Spring容器配置
    @Override
    protected WebApplicationContext createRootApplicationContext() {
        return null;
    }
}

1.4、编写controller

@RestController
public class UserController {
    @GetMapping("/save")
    public String save(){
        return "spring mvc save,欢迎您!";
    }
}
posted @ 2023-03-05 20:46  his365  阅读(11)  评论(0编辑  收藏  举报