What is SpringMVC?

Struts2 in the Web layer, Spring in the middle, Hibernate in the DAO layer, and Mybatis in the same way as Hibernate. Another framework for dealing with databases is at the DAO layer, and today’s SpringMVC is another framework at the Web layer.

The full name of SpringMVC is Spring Web MVC. Springmvc is a module of Spring, and as you can see from the name, SpringMVC is a front-end Web framework based on THE MVC design pattern.

MVC: M (Model), V (View), C (Control)

MVC application concept diagram

Two, springMVC entry program

Through this to quickly understand the general development process of SpringMVC, in fact, through the ABOVE MVC analysis diagram, almost know how to develop. The point is three steps.

  • 1. Configure a serlvet in web. XML.

  • 2, write a handler(Controller) class for business processing.

  • 3. Write JSPS or other views to display data

The idea is there, so start writing it.

Problem description: Use SpringMVC to complete front-end request processing

2.1. Create a Web project

2.2. Add jar packages

2.3 programming steps

The first three steps are just the most critical three through the ANALYSIS of MVC diagram, among which there should be more steps to implement, such as the Spring configuration file, but the key focus is still the three.

  • 1. Create class Po

  • 2. Configure front-end controller and DispatcherServlet

  • 3. Create a SpringMVC configuration file

  • 4. Develop handler(Controller)

  • Configure the handler in the SpringMVC configuration file (named springMVC.xml)

  • 6. Develop JSP or other views

  • 8. Deploy tests

2.4. Create class Po

2.5. Configure front-end controllers

1 <! -- Front-end controller for SpringMVC --> 2 <servlet> 3 <servlet-name> SpringMVC </servlet-name> 4 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 5 <! -- Specify the address of the springMVC configuration file --> 6 <init-param> 7 <param-name>contextConfigLocation</param-name> 8 <param-value>classpath:springmvc.xml</param-value> 9 </init-param> 10 </servlet> 11 <servlet-mapping> 12 <servlet-name>springmvc</servlet-name> 13 <! *. Do: only requests with the suffix. Do can access this servlet. All requests can access this servlet(except JSP), including static requests (processing problems, no need) 16 3, /* : there is a problem, because access to JSP also access the servlet, and we do not need to access JSP, 17 --> 18 <url-pattern>*. Do </url-pattern> 19 </ servle-mapping >Copy the code

2.6. Create a SpringMVC configuration file

In the config directory, create the springmVC.xml file

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

2.7. Develop the Handler (Controller) class, which handles business logic.

2.8. Configure the handler class in springmvc. XML.

Note: 2.7 and 2.8 are explained together, because there are three ways to develop the handler class, so the configuration is also linked together, so as to avoid separate, can not see clearly

There are several ways to develop Springmvc handlers, but we’ll only cover three: implementing HttpRequestHandler, implementing Controller, and using annotations.

Implement HttpRequestHandler interface

1 package com.wuhao.springmvc.controller; 2 3 import java.io.IOException; 4 import java.util.ArrayList; 5 import java.util.List; 6 7 import javax.servlet.ServletException; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 11 import org.springframework.web.HttpRequestHandler; 12 13 import com.wuhao.springmvc.domain.Items; 14 15 public class ItemController implements HttpRequestHandler { 16 17 @Override 18 public void handleRequest(HttpServletRequest request, HttpServletResponse response) 19 throws ServletException, IOException {20 List<Items> itemsList = new ArrayList<Items>(); IOException {20 List<Items> itemsList = new ArrayList<Items>(); 22 23 Items items_1 = new Items(); 24 Items_1.setName (" lenovo laptop HttpRequestHandler"); 25 items_1.setPrice(6000f); 26 Items_1.setdetail ("ThinkPad T430 Lenovo laptop!" ); 27 28 Items items_2 = new Items(); 29 Items_2.setName (" iPhone "); 30 items_2.setPrice(5000f); 31 Items_2.setdetail ("iphone6 iPhone!" ); 32 33 itemsList.add(items_1); 34 itemsList.add(items_2); Request. SetAttribute ("itemsList", itemsList); 38 / / specified view 39 request. GetRequestDispatcher ("/WEB - INF/JSP/items/itemsList. JSP "). The forward (request, response); 40 41} 42 43}Copy the code

The processor is configured in springMVC.xml

With localhost:8080/ project name /queryItems01.do we can access DispatcherSerlvet and the servlet will help us find your corresponding processor (based on the following configuration, QueryItems01 corresponds to a processor class, which can be found)

1 <! <bean name="/queryItems01.do" class="com.wuhao.springmvc.controller.ItemController"></bean>Copy the code

Implementing the Controller interface

1 package com.wuhao.springmvc.controller; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 9 import org.springframework.web.servlet.ModelAndView; 10 import org.springframework.web.servlet.mvc.Controller; 11 12 import com.wuhao.springmvc.domain.Items; 13 14 public class ItemController02 implements Controller { 15 16 @Override 17 public ModelAndView handleRequest(HttpServletRequest request, 18 HttpServletResponse Response) throws Exception {19 // Get the item List (using static data to emulate) 20 List<Items> itemsList = new ArrayList<Items>(); 21 22 Items items_1 = new Items(); 23 Items_1.setName (" lenovo notebook Controller"); 24 items_1.setPrice(6000f); 25 Items_1.setdetail ("ThinkPad T430 Lenovo laptop!" ); 26 27 Items items_2 = new Items(); 28 Items_2.setName (" iPhone "); 29 items_2.setPrice(5000f); 30 Items_2.setdetail ("iphone6 iPhone!" ); 31 32 itemsList.add(items_1); 33 itemsList.add(items_2); 35 // To implement the Controller interface, you must use the MoldeAndView object to load the data into the corresponding JSP view, and then return the object. 36 // There are two steps: pass the data to the object, pass the specified view to the object, and return the object. 37 ModelAndView mv = new ModelAndView(); 38 // similar to request.setAttribute("itemsList", itemsList); 39 mv.addObject("itemsList", itemsList); 40 and 41 / / specified view 42 mv. SetViewName ("/WEB - INF/JSP/items/itemsList. JSP "); 43 44 return mv; 45 46} 47 48}Copy the code

Configure the Handler class

<! <bean name="/queryItems02.do" <bean name="/queryItems02.do" class="com.wuhao.springmvc.controller.ItemController02"></bean>Copy the code

Development with annotations

Configuring annotations is configuring a scanner to scan where annotations are used

<! Handle that uses annotations needs to be configured with a component scanner, Load handler base - package: specify to scan the package -- -- > < context: component scan base - package = "com. Wuhao. For springmvc. Controller" ></context:component-scan>Copy the code

2.9. Develop JSP

Create JSP: itemsList under WEB-INF/ JSP /items/

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> <! PUBLIC DOCTYPE HTML "- / / / / 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 > query goods list < / title > < / head > < body > < form action =" ${contextPath pageContext. Request }/item/ queryitem. action" method="post"> <table width="100%" border=1> <tr> < TD ><input type="submit" value=" query "/></td> </tr> </table> < table width = "100%" border = 1 > < tr > < td > commodity name < / td > < td > commodity prices < / td > < td > production date < / td > < td > product description < / td > < td > action < / td > < / tr > < c: forEach  items="${itemsList }" var="item"> <tr> <td>${item.name }</td> <td>${item.price }</td> <td><fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/></td> <td>${item.detail }</td> <td><a Href = "${pageContext. Request. ContextPath} / editItems do? Id = ${item. Id}" > change < / a > < / td > < / tr > < / c: forEach > < / table > < / form > </body> </html>Copy the code

2.10. Deployment test

Test the three processing classes written in different ways above. Access is successful

3. Analysis of springMVC framework schematic diagram

We have seen the application of springMVC’s MVC design pattern and written a simple example. The key points are configuring the DispatcherServlet, writing the processing class and configuring the JSP, the three key points of MVC, but this is also a rough use of SpringMVC. I don’t know how it works, like

  • How does SpringMVC find the processor?

  • How does SpringMVC execute the processor?

  • How does SpringMVC find view objects?

Look at the picture can be

  • Send requests to the front-end controller (DispatcherServlet). The controller will filter out which requests can access the servlet and which cannot, which is the function of url-pattern, and load the springMVC.xml configuration file

  • 2. The front-end controller will find HandlerMapping, and the component that completes the URL to controller mapping through HandlerMapping. Generally speaking, it will find and store the URL configured or annotated in SpringMVC.xml and corresponding processing class. It’s actually a collection of maps that hold this mapping, map< URL, handler>; In this way, all such mappings are recorded

  • 3. Once you have these mapping relationships and find the handler for the URL, HandlerMapping returns its handler (the handler shown in red), followed by a number of interceptors

  • There will be many interceptors before the returned processor.

  • 4. Once the DispatcherServlet gets to the handler, it finds the HandlerAdapter and uses it to access and execute the handler.

Some of you might wonder, why do we need a processor adapter? We already have a processing class, so we can just call it.

No, because we only know where the handler is, we don’t know which method in the handler is being executed, so we don’t know how the handler was created. HttpRequestHandler? Annotation, or something else, we don’t know, so we need a HandlerAdapter to help us figure out which method to call.

  • 5. Execute the processor

  • The handler returns a ModelAndView object to the HandlerAdapter

  • 7. Return the ModelAndView object to the front-end controller (DispatcherServlet) via the HandlerAdapter

  • 8. The front-end controller requests the ViewResolver to carry out view resolution. According to the logical view name, the view is resolved into a real view (JSP)

  • 9. Return the view object to the front controller.

  • 10. View rendering, which puts data from a ModelAndView object into the Request field, allows the page to load the data.

  • 11. In step 8, the page is found by name, and in step 10, the required data is in the Request field, and the view is ready to render. Finally, return it.

Through the above diagram and analysis process, the above three questions can be solved perfectly. Once you understand the diagram, springMVC is ready to use it. Pretty simple, pretty much like Struts2, just remember the schematic.

Component analysis (default component and manually configured component)

You can see that in the picture

  • Front-end controller: Decouples other components, which increases component extensibility without direct configuration development

  • Processor mapper: no development, direct use, see above

  • Processor adapter: No development required,

  • Processors: Need to be developed in many ways

  • View resolver: No development required

  • Views: Need to be developed

That’s it. All you really need to write are two (processor + view) and one configuration (front controller). That’s the three key points of MVC.

The processor mapper, processor adapter, and view resolver are configured by default and can be viewed in the following locations

DispatchServlet.properties

BeanNameUrlHandlerMapping: mapper

4.1 non-annotated processor mapper and processor adapter [Take a look]

BeanNameUrlHandlerMapping: mapper

BeanNameUrlHandlerMapping in for springmvc configuration files, configuration

Its role is to find the URL configured in SpringMVC.xml and the bean of the processor

HttpRequestHandlerAdapter: the adapter to perform HttpRequestHandler interface processing method of a class

HttpRequestHandlerAdapter in for springmvc configuration files, configuration

HttpRequestHandler: HttpRequestHandler: HttpRequestHandler: HttpRequestHandler: HttpRequestHandler: HttpRequestHandler

How to adapt, is the need to see the source code, you can baidu to explain the source of the adapter.

SimpleControllerHandlerAdapter: adaptation to perform to achieve the processing method of a class of Controller interface

SimpleControllerHandlerAdapter in for springmvc configuration files, configuration

Summary: This is how non-annotated components are configured. It’s very simple, notice

  • More than one processor mapper and processor adapter can be configured

  • Processor mapper and processor adapter can be used interchangeably

4.2 Configure annotated processor mapper and adapter (Master)

  • Org. Springframework. Web. Servlet. MVC. The annotation. The DefaultAnnotationHandlerMapping is before spring3.1 use the annotation of the mapping

  • Org. Springframework. Web. Servlet. MVC) method. The annotation. The RequestMappingHandlerMapping is after spring3.1 use the annotation of the mapping

  • Org. Springframework. Web. Servlet. MVC. The annotation. AnnotationMethodHandlerAdapter is before spring3.1 use annotations adapter

  • Org. Springframework. Web. Servlet. MVC) method. The annotation. RequestMappingHandlerAdapter is after spring3.1 use annotations configurator

Note:

Annotated mappers and adapters are different before and after version 3.1

2. Annotated processor mapper and processor adapter must be used together and cannot be used with non-annotated processor mapper and adapter (annotated processor mapper cannot be configured with non-annotated processor adapter, either)

There are two configuration modes:

1. Use bean tag configuration

2. Use MVC tags (recommended)

4.3. View resolver

4.3.1 JSP View parser (default is to use this parser)

Prefix: prefix suffix: suffix. After configuration, when specifying a view, you don’t need to write the prefix and suffix, and just write the key code. See below

Although the specified view only write the items/itemsList but will help us with our configuration of prefixes and suffixes, namely into/WEB – INF/JSP/items/itemsList. JSP

4.3.2 Freemarker View parser

org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver

When used in the study.

5. Three functions of requestMapping annotations

RequestMapping has three functions: mapping request urls, narrowing requests, and limiting request methods

5.1. Map request URL

That is, write it in the method, and we’ve already used this functionality, so I’ll explain it in detail here

@requestMapping (value=”/item,/user”) or @requestMapping (“/item “) value are arrays that can map multiple urls to the same method, separated by commas. RequestMapping(value=”/item “) @requestMapping (value=”/item “) @requestMapping (“/item “)

5.2. Narrow requests

Requestmapping on top of the class allows you to categorize urls and narrow requests

Add in the class

Plus the method

The access path is: http://localhost:8080/xxx/items/queryItems.do

5.3. Limit the request method

The access restriction method must be get or POST, which is equivalent to filtering requests.

Restrict GET methods, which allow access only to requests that come in the form of GET requests

@RequestMapping(method = RequestMethod.GET)

HTTP Status 405-request method ‘POST’ not supported HTTP Status 405-request method ‘POST’ not supported

Qualify the POST method.

@RequestMapping(method = RequestMethod.POST)

You can specify the response result by response. For example, the response JSON data is as follows

The get and post @ RequestMapping (method = {RequestMethod. Get RequestMethod. Post})

The controller class returns a value from a method

There are also three: ModelAndView objects, void, and String

6.1. Return the ModelAndView object

The Controller method defines and returns a ModelAndView object to which model data can be added and the view specified. It is then parsed through the view parser. That’s what they used up there. There’s no need to explain it too much

6.2, void

If void is returned, request and Response can be defined on the controller method parameter, specifying the result of the response using request or Response. But it can be used like this, which means that the controller method has these two parameters by default. You can use it by adding)

Redirect to the page using Request as follows

Request. GetRequestDispatcher (” path “page). The forward (request, response)

Redirect via the Response page

response.sendRedirect(“url”)

You can specify the response result by response. For example, the response JSON data is as follows

response.setCharacterEncoding(“utf-8”);

response.setContentType(“application/json; charset=utf-8”);

The response. GetWriter (). The write (” json string “);

6.3, String

Use one: Return the logical view

Explanation: The parameter has a Model object, which is the default parameter and can be used once declared. The Model object adds properties to the Request scope, just as the ModelAndView object adds values to the Request scope, except that the Model object cannot specify a view. The Model is exactly half of the Model and View, so it makes sense. Second, because you don’t have a modelAndView object, you can’t specify the view, but you can just return the view address, just as you would with a modelAndView object.

Use 2: Request forwarding