SpringMVC入门案例

坐标

        <!--Spring坐标-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.5.RELEASE</version>
        </dependency>

        <!--SpringMVC坐标-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.0.5.RELEASE</version>
        </dependency>

        <!--Servlet坐标-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>

        <!--Jsp坐标-->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
        </dependency>

Controller:该包负责请求转发,接受页面过来的参数,传给Service处理,接到返回值,再传给页面

UserController:控制器类

package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
//Controler负责请求转发,接受页面过来的参数,传给Service处理,接到返回值,再传给页面。
@Controller//SpringMVC的Bean配置
public class UserController {
    @RequestMapping("/save")//设置当前的访问路径
    @ResponseBody//设置当前操作的返回值类型
    public String save(){
        System.out.println("use save...");
        return "{'module':'springmvc'}";
    }
}

配置类

SpringMVCconfig
package com.example.demo.config;

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

@Configuration//定义配置类
@ComponentScan("com.example.demo.controller")
public class SpringMVCconfig {

}
ServletConfig
package com.example.demo.config;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;

//定义一个servlet的配置类,加载spring的配置类
public class ServletConfig extends AbstractDispatcherServletInitializer {
//     加载mvc的配置
    @Override
    protected WebApplicationContext createServletApplicationContext() {
        AnnotationConfigWebApplicationContext ctx=new AnnotationConfigWebApplicationContext();//初始化web容器
        ctx.register(SpringMVCconfig.class);//加载配置
        return ctx;
    }
//设置哪些请求是mvc处理的
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
//加载spring的配置
    @Override
    protected WebApplicationContext createRootApplicationContext() {
        return null;
    }
}

 

posted @   唐柒墨  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· 单线程的Redis速度为什么快?
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
点击右上角即可分享
微信分享提示

目录导航