【JAVA】Spring MVC 详解

Spring MVC 基本概念

1. Spring MVC 概述

Spring MVC 是 Spring 框架中的一个模块,专注于为 Web 应用程序提供 Model-View-Controller (MVC) 架构。它帮助开发者构建可扩展、可维护的 Web 应用,并且能够轻松集成到 Spring 生态系统中。

2. DispatcherServlet

DispatcherServlet 是 Spring MVC 的核心组件,负责接收 HTTP 请求,并将请求分发给相应的处理器(Controller)。它起到了中央控制器的作用。
示例:

@Configuration
public class WebAppInitializer implements WebApplicationInitializer {
   

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
   
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(AppConfig.class);
        
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(context));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
    }
}

在这个例子中,DispatcherServlet 被注册到 ServletContext 中,并映射到根路径。

3. Controller

Controller 是 Spring MVC 中的一个组件,负责处理用户请求,并返回一个 ModelAndView 对象。它将用户的输入与应用程序的业务逻辑连接起来。
示例:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HomeController {
   

    @GetMapping("/")
    public ModelAndView home() {
   
        ModelAndView mav = new ModelAndView("home");
        mav.addObject("message", "Welcome to Spring MVC");
        return mav;
    }
}

在这个例子中,HomeController 处理根路径的 GET 请求,并返回一个包含消息的视图。

4. ModelAndView

ModelAndView 是 Spring MVC 中的一个类,包含了视图名称和模型数据。它将控制器的处理结果传递给视图层。
示例:

ModelAndView mav = new ModelAndView("home");
mav.addObject("message", "Welcome to Spring MVC");

在这个例子中,ModelAndView 对象包含视图名称 “home” 和模型数据 “message”。

5. @RequestMapping

@RequestMapping 是 Spring MVC 中的一个注解,用于映射 HTTP 请求到控制器的方法。它支持多种 HTTP 方法(GET、POST 等),还可以指定路径和参数。
示例:

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.

你可能感兴趣的:(JAVA复习,java,spring,mvc)