Spring-mvc

What is for SpringMvc

SpringMvc is a java-based request-driven lightweight Web framework that implements Mvc design pattern. It is the follow-up product of Spring Framework and has been integrated into Spring Web Flow. SpringMvc has become one of the most mainstream Mvc frameworks at present. And with the release of Spring3.0, it has completely surpassed Struts2 and become the best MVC framework. With a set of annotations, it makes a simple Java class a controller to handle requests without implementing any interfaces, and it also supports RESTful programming style requests

Introduction to the Mvc design pattern

MVC: Model (module) View (View) Controller (Controller) is a design mode, is a kind of business logic, data and interface display separated method to organize the code, the integration of many business logic into a component, in the need to improve and customize the interface and user interaction at the same time, There is no need to rewrite business logic to reduce coding time and improve code reuse.

Module Layer (Model)

The code that encapsulates the data and processes the data is where the actual data is processed and interacts with the database

View layer

Responsible for presenting the application to the user and displaying the status of the model

Control Layer (Controller)

F is responsible for the interaction between the view and the model, and controls the response to user input, response mode and process. He is mainly responsible for two aspects: one is to send user requests to the corresponding model; the other is to reflect model changes to the view in time

V stands for View: The interface that the user sees and interacts with. For example, a web page interface consisting of HTML elements, or a software client interface. One of the nice things about MVC is that it can handle many different views for your application. There’s no real processing going on in the view, it’s just a way to output data and allow the user to manipulate it.

M stands for Model model: The model represents the business rules. Of the three parts of MVC, the model has the most processing tasks. The data returned by the model is neutral and the model is independent of the data format, so that a model can provide data for multiple views, reducing code duplication because code applied to the model can be written once and reused by multiple views.

C stands for Controller controller: the controller accepts the user’s input and calls the model and view to fulfill the user’s requirements. The controller itself does not output anything or do anything. It simply receives the request, decides which model artifact to call to process the request, and then determines which view to use to display the returned data.

Image resolution

The most typical MVC is JSP + Servlet + Javabean pattern.

Javabeans, as models, can encapsulate business data as data models and contain business operations of applications as business logic models. The data model is used to store or transfer business data, and the business logic model performs specific business logic processing after receiving the model update request from the controller, and then returns the corresponding execution result.

The JSP, as the view layer, is responsible for providing the page to present the data to the user, providing the corresponding Form for the user’s request, and issuing the request to the controller when appropriate (button click) to request the model to be updated.

Serlvet is a controller that receives requests submitted by users, retrieves the data in the request, converts it to the data model required by the business model, and then invokes the corresponding business method of the business model to update it, while selecting the view to return based on the business execution results.

Basic flow chart

Let’s use an example to demonstrate JSP + Servlet + Javabean

Step 1 Import SpringMVC coordinates. 2. Configure SpringMVC core controller DispathcerServlet 3. Create the Controller class and view page 4. Use annotations to configure the mapping address of the business method in the Controller class 5. Configure the SpringMVC core file spring-mvC.xml 6. The client initiates a request test

1. Import SpringMVC coordinates

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.04..RELEASE</version>
        </dependency>
Copy the code

2. Configure SpringMVC core controller DispathcerServlet

 <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <! Code for loading configuration files --> <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param> <! Load it when the server startsservlet-->
        <load-on-startup< / a > 1load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name> <! -- Always go when accessing any resourceservlet-->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
Copy the code

3. Create the Controller class and view page

Write a simple Controller class that jumps to a success.jsp page and uses annotations to configure the mapping address of the business method in the Controller class

package com.pjh.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class controller {
    @RequestMapping("/quick")
    public String save(a){
        System.out.println("Controller save running!!);
        return "success.jsp"; }}Copy the code

Index.jsp page code

<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<H1>Success</H1>
</body>
</html>
Copy the code

4. Configure the SpringMVC core file, spring-mVC.xml. This is just a simple scanner

<? xml version="1.0" encoding="UTF-8"? > <beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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/context http://www.springframework.org/schema/context/spring-context.xsd "> <! <context:component-scan base- - configures the scanner, which is a configuration file for the Controller layerpackage="com.pjh.controller"/>
</beans>
Copy the code

The results of

Flow chart analysis

SpringMVC execution flowchart

1. The user sends a request to the DispatcherServlet of the front-end controller. 2. When DispatcherServlet receives a request, it invokes the HandlerMapping processor. 3. The processor mapper finds the specific processor (which can be found based on XML configuration, annotations), generates the processor object and a processor interceptor (if any) and returns it to the 4.DispatcherServlet. 5.DispatcherServlet calls the HandlerAdapter processor adapter. 6. The HandlerAdapter ADAPTS to invoke specific processors (controllers, also known as back-end controllers). 7.Controller Returns to ModelAndView after execution. 8. The HandlerAdapter returns the Controller execution result ModelAndView to the DispatcherServlet. 9.DispatcherServlet passes ModelAndView to ViewReslover. 10.ViewReslover parses and returns a specific View. 11. The DispatcherServlet renders the View according to the View (that is, populates the View with model data). DispatcherServlet responds to the user.

The illustration

SpringMVC component parsing

1. Front-end Controller: DispatcherServlet User requests arrive at the front-end Controller, which is C (Controller) in MVC design mode. It is the control center of the whole process, and it calls components to handle user requests

HandlerMapping is responsible for finding handlers according to user requests. SpringMVC provides different mappers to implement different mapping methods, such as configuration file method, implementation interface method, annotation method, etc.

3. Processor adapter: The HandlerAdapter executes on the processor through the HandlerAdapter, which is the application of the adapter pattern. By extending the adapter, more types of processors can be executed

It is the specific business controller we want to write in the development. The DispatcherServlet forwards the user request to the Handler. The specific user request is processed by Handler.

5. View resolver: The View Resolver is responsible for generating the View from the processing result. The View Resolver first resolves the logical View name into the physical View name, that is, the specific page address, and then generates the View object. Finally, render the View and show the results to the user through the page.

The SpringMVC framework provides support for many View types, including jstlView, freemarkerView, pdfView, and more. The most common view is a JSP. In general, it is necessary to display model data to users through page tags or page templates, and programmers need to develop specific pages according to business requirements

SpringMVC annotation parsing

@requestMapping establishes the mapping between request urls and request processing methods. Location: Specifies the first-level access directory of the request URL. If this is not specified, it is equivalent to the application of the root directory method, the second level of the request URL access directory, together with the @reqquestMapping class of the first level of the access virtual path attribute: value: used to specify the requested URL. Method: specifies the method of the request. Params: specifies the conditions that limit the parameters of the request. It supports simple expressions. The key and value of the request parameters must be the same as those configured. For example, params = {“accountName”} indicates that the request parameters must have accountName Params = {“moeny! 100”}, indicating that the request parameter money cannot be 100

The sample

@Controller
@RequestMapping("/user")
public class Usercontroller {
    /* Jumps to the specified page instead of the web.xml configuration */
    @RequestMapping(value = "/quick",method= RequestMethod.POST,params = {"username"})
    public String save(a){
        System.out.println("Controller save running!!);
        return "success.jsp"; }}Copy the code

Access path: http://lcalhost: Port number /user/quick? username=xxx

The request method must be Post

The request parameter must be username

Spring namespace introduction

Namespace:

xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
Copy the code

1. Constraint address:

     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
Copy the code

2. Component scanning SpringMVC is based on the Spring container, so the Controller needs to be stored in the Spring container when performing SpringMVC operations. If annotated with @Controller annotation, Use
to scan components.

Configuration of the view resolver

For SpringMVC have default component configuration, the default component is a DispatcherServlet. The properties in the configuration file configuration, The configuration file address org/springframework/web/servlet/DispatcherServlet. The properties, the file is configured with the default view parser, as follows:

org.springframework.web.servlet.ViewResolver=org.springframework.web.servlet.view.InternalResourceViewResolver
Copy the code

If you look at the parser source code, you can see the default Settings for the parser as follows:

REDIRECT_URL_PREFIX = "redirect:"-- Redirects the prefix FORWARD_URL_PREFIX ="forward:"-- Forward prefix (default) prefix =""; -- View name prefix suffix =""; -- View name suffixCopy the code

View resolver We can change the prefixes and suffixes of views through property injection

<! Configure the internal resource view parser --> <beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  <property name="prefix" value="/WEB-INF/views/"></property> 
     <property name="suffix" value=".jsp"></property></bean>
Copy the code

This is the first chapter of SpringMVC series, which mainly focuses on principle analysis and some basic operations. I will keep updating in the future. This blog mainly focuses on data structure, algorithm and Java development