SpringMVC注解开发入门案例

本文阅读 1 分钟
首页 代码,Java 正文

img

🍁博客主页:👉不会压弯的小飞侠
✨欢迎关注:👉点赞👍收藏⭐留言✒
✨系列专栏:👉SpringMVC注解开发
✨如果觉得博主的文章还不错的话,请三连支持一下博主。
🔥欢迎大佬指正,一起 学习!一起加油!

img

1.导入SpringMVC坐标与servlet坐标

<dependencies>
   <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-webmvc</artifactId>
     <version>5.2.22.RELEASE</version>
   </dependency>
   <dependency>
     <groupId>javax.servlet</groupId>
     <artifactId>javax.servlet-api</artifactId>
     <version>4.0.1</version>
     <scope>provided</scope>
   </dependency>
 </dependencies>

2.创建SpringMVC控制器(相当于servlet功能)

package com.study.controller;

import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller //定义Bean
public class UserController { 
    @RequestMapping("/save")
    @ResponseBody  //设置当前操作的返回值类型
    public String save(){ 
        System.out.println("user save....");
        return "{'module':'SpringMVC'}";
    }

}

3.创建SpringMVC的配置文件

package com.study.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.study.controller")
public class SpringMvcConfig { 
}

4.定义一个Servlet容器启动的配置类加载Spring的配置

package com.study.config;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;

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

运行结果: img

本文为互联网自动采集或经作者授权后发布,本文观点不代表立场,若侵权下架请联系我们删帖处理!文章出自:https://blog.csdn.net/qq_43514330/article/details/125574665
-- 展开阅读全文 --
安全面试之XSS(跨站脚本攻击)
« 上一篇 07-24

发表评论

成为第一个评论的人

热门文章

标签TAG

最近回复