Springmvc concepts and simple cases

springmvc concept

The JavaEE architecture includes four layers, from top to bottom are the application layer, Web layer, business layer, and persistence layer. Struts and SpringMVC are the frameworks of the Web layer, Spring is the framework of the business layer, and Hibernate and MyBatis are the frameworks of the persistence layer.

SpringMVC is a lightweight, MVC-based Web layer application framework, which is part of the Spring framework. To put it bluntly, SpringMVC encapsulates Servlet for everyone to use.

Features of springmvc

The problem with many applications is that there is a tight coupling between the objects that process the business data and the views that display the business data. Often, commands to update the business objects are initiated from the views themselves, making the views highly sensitive to any business object changes . Also, there is no flexibility when multiple views depend on the same business object.

SpringMVC is a lightweight web framework based on Java that implements the Web MVC design pattern and request-driven type. It uses the idea of the MVC architecture pattern to decouple the responsibilities of the Web layer. Based on request-driven refers to the use of request-response model, the purpose of the framework is to help us simplify development, SpringMVC is also to simplify our daily Web development.

Features:

  • Natively integrated with Spring
  • Support Restful style development
  • Easy to integrate with other view technologies, such as theamleaf, freemarker, etc.
  • powerful exception handling
  • Support for static resources

spring component

Component Function
DispatcherServlet (is a front controller , provided by the framework) Unified processing of requests and responses. In addition, it is the center of the entire process control. DispatcherServlet calls other components to process user requests
HandlerMapping (processor mapper, provided by the framework) Find the specific Handler (generally speaking, Controller) according to the requested url, method and other information
Handler (generally speaking, Controller) Under the control of DispatcherServlet, Handler processes specific user requests
HandlerAdapter (processor adapter, provided by the framework) According to the mapping Processor Handler information found by the processor, according to specific rules to execute the relevant processor Handler.
ViewResolver (view resolver, provided by the framework) ViewResolver is responsible for generating the View view from the processing result. ViewResolver first parses the logical view name into a physical map name, that is, the specific page address, then generates a View view object, and finally renders the View to display the processing results to the user through the page.
View (view, developed by engineers themselves) The responsibility of the View interface is to receive model objects, Request objects, and Response objects, and render the output results to Response object.

summary:

Handler is a tool for doing work;

HandlerMapping is used to find the corresponding tool according to the work that needs to be done;

HandlerAdapter is the one who does the work with tools. For a detailed explanation, please see this blog (115 messages) SpringMVC Processor Adapter Detailed Explanation_aFa Attack and Defense Lab’s Blog-CSDN Blog_Processor Adapter

springmvc process

The following is a brief description of the request processing flow based on Spring MVC:

  1. The user initiates an HttpRequest request to the front controller (DispatcherServlet) through the browser.
  2. DispatcherServlet sends user requests to the processor mapper (HandlerMapping).
  3. The handler mapper (HandlerMapping) will find the handler (handler) responsible for processing the request according to the request, and encapsulate it as a handler execution chain and return (HandlerExecutionChain) to DispatcherServlet
  4. DispatcherServlet will find the processor adapter (HandlerAdaptor) that can execute the processor according to the processor in the processor execution chain — Note, there are multiple processor adapters
  5. The handler adapter (HandlerAdaptoer) will call the corresponding specific Controller
  6. Controller encapsulates the processing result and the view to be jumped into an object ModelAndView and returns it to the processor adapter (HandlerAdaptor)
  7. HandlerAdaptor directly hands ModelAndView to DispatcherServlet, so far, the business processing is completed
  8. After the business is processed, we need to display the processing results to the user. So DisptcherServlet calls ViewResolver to encapsulate the view name in ModelAndView into a view object
  9. ViewResolver returns the encapsulated View object to DIspatcherServlet
  10. DispatcherServlet calls the view object to render itself (View) (fill the model data into the view) to form a response object (HttpResponse)
  11. The front controller (DispatcherServlet) responds (HttpResponse) to the browser and displays it on the page.

img

Simple case of springmvc

controller:

package com.xsh.controller;

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

@Controller
public class LoginController {<!-- -->

    @GetMapping("/login")
    public String showLoginForm() {<!-- -->
        return "login";
    }

    @PostMapping("/login")
    public ModelAndView processLogin(@RequestParam("username") String username, @RequestParam("password") String password) {<!-- -->
        ModelAndView modelAndView = new ModelAndView();

        // Assuming the username is "admin" and the password is "password" to log in successfully
        if (username.equals("admin") & amp; & amp; password.equals("password")) {<!-- -->
            modelAndView.setViewName("success");
            modelAndView.addObject("username", username);
        } else {<!-- -->
            modelAndView.setViewName("failure");
        }

        return modelAndView;
    }
}

@Controller: This annotation identifies the LoginController class as a controller component and tells Spring MVC that this class is responsible for handling requests. as handler

@GetMapping("/login"): This annotation specifies the processing of GET requests and maps to the “/login” path. The showLoginForm() method returns the string “login”, indicating that the view named “login” should be displayed.

@PostMapping("/login"): This annotation specifies the processing of POST requests and maps to the “/login” path. The processLogin() method processes the data submitted by the login form and returns a ModelAndView object.

@RequestParam("username") and @RequestParam("password"): These annotations bind request parameters to method parameters. In the processLogin() method, the username and password parameters are bound to the request named “username” and “password\ ” parameter value.

ModelAndView: ModelAndView is a component in Spring MVC, which is used to set the view name and model data in the controller method. ModelAndView is a class used to encapsulate the view name and model data, which allows the controller method to set the view name and pass data to the view at the same time. It is created in the controller method and passes the view name and model data to the DispatcherServlet by returning a ModelAndView object.

? In the controller method, you can use the setViewName() method of ModelAndView to set the view name, and set the logical name of the view (such as “success”, “failure”, etc. ) specified as a string parameter. Then, you can use the addObject() method to add model data to the ModelAndView object for use by the view. Model data can be any Java object, such as strings, lists, maps, etc.
? Finally, the controller method should return the ModelAndView object, making it the result of request processing. DispatcherServlet will parse the actual view object according to the view name in ModelAndView, and pass the model data to the view to render the final response.
? In short, ModelAndView is a component used to set the view name and model data in Spring MVC. It is created in the controller method and passes the view name and model data to the DispatcherServlet by returning a ModelAndView object.

According to the above code, when accessing the “/login” path, the showLoginForm() method will be executed, and “login” will be returned as the view name, indicating that the login page will be displayed. When the login form is submitted, the processLogin() method will be executed, and different view names (“success” or “failure”) and model data will be set according to the verification results of the username and password.

springmvc-servlet.xml:

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

    <!-- Enable Spring MVC annotation driver -->
    <mvc:annotation-driven/>

    <!-- Scan Controller class -->
    <context:component-scan base-package="com.xsh.controller"/>

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

</beans>

: This configuration enables Spring MVC’s annotation-driven functionality, allowing annotations to be used in controllers to process requests.

: This configuration specifies the base package path to scan for annotated components. In this example, it scans for controller classes located under the “com.xsh.controller” package.

  • : This configuration defines a view resolver named InternalResourceViewResolver.
  • class="org.springframework.web.servlet.view.InternalResourceViewResolver": This configuration specifies the class name of the view resolver, namely InternalResourceViewResolver, which is Spring MVC Provides an internal resource view resolver.
  • : This configuration sets the properties of the view resolver.
    • name="prefix": Set the prefix attribute, specifying the path prefix of the view file. In this example, the view files should be located in the “/WEB-INF/views/” directory.
    • name="suffix": set the suffix attribute, and specify the suffix name of the view file. In this example, view files should use “.jsp” as the suffix.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         id="WebApp_ID" version="3.1">

  <display-name>SpringMVCDemo</display-name>

  <!-- Spring MVC configuration -->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/springmvc-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

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

</web-app>

  • : Define a Servlet.
  • : Specify the name of the Servlet, here named “springmvc”.
  • : Specify the Servlet class, here use Spring MVC’s DispatcherServlet.
  • : Define the initialization parameters of the Servlet.
    • : Specifies the name of the initialization parameter.
    • : Specify the value of the initialization parameter, here is the path of the Spring MVC configuration file /WEB-INF/springmvc-servlet.xml.
  • : Specifies the loading order of the Servlet, here is set to 1, which means that it is loaded immediately when the Web application starts.
  • : Map Servlet to URL path.
  • : Specify the name of the Servlet, consistent with the Servlet name defined above.
  • : Specifies the URL path, here is set to “/”, which means that all requests will be handed over to the Servlet for processing.

login.jsp

<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
</head>
<body>

<h1>Login</h1>
<form action="/login" method="post">
    <label for="username">Username:</label>
    <input type="text" id="username" name="username" required><br><br>

    <label for="password">Password:</label>
    <input type="password" id="password" name="password" required><br><br>

    <input type="submit" value="Login">
</form>
</body>
</html>

success.jsp

<!DOCTYPE html>
<html>
<head>
    <title>Success</title>
</head>
<body>
<h1>Login Successful</h1>
<p>Welcome, ${username}!</p>
</body>
</html>

failure.jsp

<!DOCTYPE html>
<html>
<head>
    <title>Failure</title>
</head>
<body>
<h1>Login Failed</h1>
<p>Invalid username or password.</p>
</body>
</html>