SpringMVC执行流程

1. 视图阶段(JSP)

1.1 执行流程

Spring MVC是Spring框架中用于构建Web应用程序的一部分。其执行流程主要包括以下步骤:
SpringMVC执行流程_第1张图片

SpringMVC执行流程_第2张图片

1.2 代码演示

在一个简单的Spring MVC应用中,你可以创建一个Controller类以及一个简单的JSP页面,然后演示整个请求-响应流程。

首先是Controller类:

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController {

    @RequestMapping("/hello")
    public String hello(Model model) {
        model.addAttribute("message", "Hello, Spring MVC!");
        return "hello"; // 返回视图名称
    }
}

然后创建一个简单的 JSP 页面(hello.jsp):

<!DOCTYPE html>
<html>
<head>
    <title>Hello Page</title>
</head>
<body>
    <h1>${message}</h1>
</body>
</html>

在web.xml中配置DispatcherServlet:

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

最后,创建dispatcher-servlet.xml配置文件:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/mvc
           http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="com.yourpackage" />

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <mvc:annotation-driven />
</beans>

这个例子演示了一个非常基本的Spring MVC应用程序。当用户访问应用的 /hello 路径时,DispatcherServlet接收到请求,根据Controller映射找到 HelloController 类,调用 hello 方法。hello 方法添加了一个名为 “message” 的属性到Model中,然后返回 “hello” 字符串。这个字符串被视图解析器解析为 hello.jsp,并呈现给用户。

这个演示展示了Spring MVC的基本执行流程:请求进入DispatcherServlet,通过Controller处理,返回到指定视图,并最终呈现给用户。

2. 前后端分离

SpringMVC执行流程_第3张图片

你可能感兴趣的:(Spring,SpringMVC,框架,Web)