【Spring】—Getting Started with Spring MVC

Getting Started with Spring MVC

1. Overview of Spring MVC

Spring MVC is a lightweight web framework provided by Spring, which implements the Web MVC design pattern. Spring MVC is more excellent than another framework Struts2 in terms of usage and performance.

Spring MVC has the following characteristics.

  • It is part of the Spring framework and can easily take advantage of other functions provided by Spring.
  • Flexible and easy to integrate with other frameworks.
  • A front controller DispatcherServlet is provided, so that developers do not need to develop additional controller objects.
  • User input can be automatically bound and data types can be converted correctly.
  • Common validators are built in to validate user input. If the validation fails, it will reset to the input form.
  • Supports internationalization, and can display multiple languages ​​according to the user's region.
  • Support a variety of view technologies, such as JSP, Velocity and FreeMarker and other view technologies.
  • With XML-based configuration files, there is no need to recompile the application after editing.

2. Case - the first Spring MVC application

1. Create a project and import the JAR package

Create a Web project named chapter11, add the JAR package required to run the Spring MVC program in the lib directory of the project, and publish it to the class path.

insert image description here

Four core JAR packages, commons-logging JAR packages, and two Web-related JAR packages are added to the project. These two Web-related JAR packages are the JAR packages required by the Spring MVC framework.

2. Configure the front controller

Configure Spring MVC's front controller DispatcherServlet in web.xml.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
         http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         id="WebApp_ID" version="3.0">
    <servlet>
    <!--配置前端过滤器-->
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--初始化时加载配置文件-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-config.xml</param-value>
        </init-param>
            <!--表示容器在启动时立即加载Servlet -->
    <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
 </web-app>

Mainly configures <servlet>and elements. <servlet- mapping>The Spring MVC front-end controller DispatcherServlet is configured in , and the location of the Spring MVC configuration file is configured <servlet>through its sub-elements. 1 in the element means that the container loads the Servlet immediately when it starts; All URLs are handled by DispatcherServlet.<init-param><load-on-startup><servlet-mapping><url-pattern>

3. Create the Controller class

Create a com.ssm.controller package in the src directory, and create a controller class ControllerTest in the package, which needs to implement the Controller interface.

package com.ssm.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class ControllerTest implements Controller {
    
    
    @Override
    public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1)throws Exception{
    
    
        //创建ModelAndView对象
        ModelAndView m = new ModelAndView();
        //向模型对象中添加一个名称为msg的字符串对象
        m.addObject("msg","第一个spring MVC程序");
        //设置返回的视图路径
        m.setViewName("/WEB-INF/jsp/welcome.jsp");
        return m;
    }
}

handleRequest() is the implementation method of the Controller interface. The ControllerTest class will call this method to process the request and return a ModelAndview object containing the view name or the view name and model. In this case, a string object named msg is added to the model object, and the returned view path is set to WEB-INF/jsp/welcome.jsp, so that the request will be forwarded to the welcome.jsp page.

4. Create a Spring MVC configuration file and configure the controller mapping information

Create the configuration file springmvc-config.xml in the src directory, and configure the controller information in the file.

springmvc-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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">
    <!--  配置处理器Handle,映射"controllerTest"请求  -->
    <bean name="/controllerTest" class="com.ssm.controller.ControllerTest" />
    <!--  处理器映射,将处理器Handle的name作为url进行查找  -->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
    <!--  处理器适配器,配置对处理器HandleRequest()方法的调用  -->
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />
    <!--  视图解析器  -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" />
</beans>

First, a Bean named "/ControllerTest" is defined, which maps the controller class ControllerTest to the "/ControllerTest" request; then the processor mapper BeanNameUrlHandlerMapping and the processor adapter SimpleControllerHandlerAdapter are configured, where the processor mapper is used for The name (ie url) in the processor bean is searched for the processor, and the processor adapter is used to complete the call to the handleRequest() method in the ControllerTest processor; finally, the view resolver InternalResourceViewResolver is configured to resolve the result view, and the The results are presented to the user.

Notice

In older versions of Spring, handler mappers, handler adapters, and view resolvers had to be configured in the configuration file. But after Spring 4.0, if the processor mapper, processor adapter and view resolver are not configured, the default configuration inside Spring will be used to complete the corresponding work. The configuration processor mapper, processor adapter and view shown here The parser is to allow readers to understand the workflow of Spring MVC more clearly.

5. Create a View page

Create a JSP folder under the WEB-INF directory, and create a page file welcome.jsp in the folder, and use EL expressions in this page to obtain the information in msg.

<%@ page contentType="text/html; charset=UTF-8" language="java"
    pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”
    "http:www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type"content="text/html; charset=UTF-8">
    <title>入门程序</title>
</head>
<body>
    ${
    
    msg}
</body>
</html>

6. Start the project and test the application

Publish the chapter11 project to the Tomcat server and start the server. Access http://localhost:8080/chapter11/controllerTest in the browser, and the displayed page effect is as shown in the figure. It can be seen that the string information in the model object has been displayed in the browser, which means that the first Spring MVC program is executed successfully.

insert image description here

Through the study of introductory cases, you can summarize the execution process of the Spring MVC program.

(1) The user sends a request to the server through the browser, and the request will be intercepted by Spring MVC's front-end controller DispatcherServlet.

(2) After the DispatcherServlet intercepts the request, it will call the HandlerMapping processor mapper.

(3) The processor mapper finds the specific processor according to the request URL, generates the processor object and the processor interceptor (if there is one), and returns it to the DispatcherServlet.

(4) DispatcherServlet will select the appropriate HandlerAdapter (processor adapter) by returning information.

(5) HandlerAdapter will call and execute Handler (processor), where the processor is the Controller class written in the program, also known as the back-end controller.

(6) After the Controller is executed, it will return a ModelAndView object, which contains the view name or the model and view name.

(7) HandlerAdapter returns the ModelAndView object to DispatcherServlet.

(8) DispatcherServlet will select an appropriate ViewResolver (view resolver) according to the ModelAndView object.

(9) After ViewResolver resolves, it will return a specific View (view) to DispatcherServlet.

(10) DispatcherServlet renders the View (that is, fills the model data into the view).

(11) The view rendering result will be returned to the client browser for display.

In the above execution process, the work of DispatcherServlet, HandlerMapping, HandlerAdapter and ViewResolver objects is executed inside the framework. Developers do not need to care about the internal implementation process of these objects. They only need to configure the front controller (DispatcherServlet) to complete the tasks in the Controller. Business processing, and display the corresponding information in the view (View).

Guess you like

Origin blog.csdn.net/weixin_45627039/article/details/131233755