1. For Springmvc primer

What is 1.1, the Springmvc

SpringMVC is a component in Spring, currently (2019) in the Internet company used a lot, is a must learn a framework technology! SpringMVC is used in the Web layer as a controller (equivalent to traditional servlets and Struts actions, or Hendler) to handle user requests. For example, if a user types http:// web domain /login in the address bar, SpringMVC will intercept the request and invoke the corresponding methods in the Controller layer. But none of this is springMVC’s responsibility), and ultimately returns the results back to the user, along with the appropriate page (or just json/ XML, etc.). Springmvc is about doing the front and back of the process, dealing with the user!! Springmvc needs a Spring JAR to run, so learning spring is very important!

Spring Web MVC and Struts2 both belong to the presentation layer framework. It is part of the Spring framework, as can be seen from the overall structure of Spring, as shown in the following figure:

1.2.Springmvc process

As shown below:

1.3. Getting started

Requirement: Use a browser to display a list of goods

1.3.1. Create a Web project

SpringMVC is a presentation layer framework that needs to be built for Web engineering development. Create a dynamic Web project:

Enter the project name and select configure Tomcat (if it already exists, use it directly) as shown below:

Click Finish, as shown below:

As shown in the figure below, the web version is 2.5, which can automatically generate the web.xml configuration file.

Create effect as shown below:

1.3.2. Import jar packages

Import the JAR package of springMVC from the pre-class materials, as shown below:

Copy jar to lib directory, project directly load jar package, as shown below:

1.3.3. Adding a configuration file

Create a config resource folder to store the configuration files as shown below:

1.3.3.1. Create for springmvc. XML

SpringMVC itself is a sub-project of Spring, which is very Spring compatible and does not require a lot of configuration. Just configure a Controller scan and let Spring manage the page control layer, the Controller.

Created for springmvc. 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" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
</beans>
Copy the code
Configure the processor adapter HandlerAdapter in 1.3.3.2.springMVC.xml

Since the Handler is developed according to the requirements of the adapter, we will first configure the HandlerAdapter in springMVC.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" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <! -- Processor adapter: HandlerAdapter. All processor adapters implement the HandlerAdapter interface.
    <! - SimpleControllerHandlerAdapter adapter can perform implements interface Controller Handler so, configuration of the adapter now, all processors Handler must implement the Controller interface. -->
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" /> 
</beans>
Copy the code
HandlerMapping is configured in 1.3.3.3.springMVC.xml

Configure the ViewResolver in 1.3.3.3.web. XML

Configure the ViewResolver so that the JSPS can be parsed. The final JSP physical address: prefix + logical view name + suffix

Configure the ViewResolver code:

<! - view the interpreter - > < bean class = "org. Springframework. Web. Servlet. The InternalResourceViewResolver" > <! Prefix -- - > < property name = "prefix" value = "/ WEB - INF/JSP/" / > <! -- suffix - > < property name = "suffix" value = "JSP" / > < / bean >Copy the code
The overall effect code in 1.3.3.5.web.xml

In general, web.xml should contain:

1. The “header” of SpringMVC. XML

2. Component scanning configuration processor Handler (Controller)

3. HandlerAdapter

4. HandlerMapping

5. ViewResolver

The overall effect code in web.xml is as follows:

<? 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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd "> <! controler@service --> <context:component-scan base-package="com.gx.springmvc"/> <! - processor mapper -- > < bean class = "org. Springframework. Web. Servlet. MVC) method. The annotation. The RequestMappingHandlerMapping" / > <! - processor adapter - > < bean class = "org. Springframework. Web. Servlet. MVC. Method. The annotation. RequestMappingHandlerAdapter" / > <! - view the interpreter - > < bean class = "org. Springframework. Web. Servlet. The InternalResourceViewResolver" > <! Prefix -- - > < property name = "prefix" value = "/ WEB - INF/JSP/" / > <! -- suffix - > < property name = "suffix" value = "JSP" / > < / bean > < / beans >Copy the code

Constraint files required by the configuration file are located as follows:

Create packages com. Gx. For springmvc. Controller

1.3.3.6. Configure front-end controller DispatcherServlet in web. XML

Configure SpringMVC’s front-end 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_2_5.xsd" id="WebApp_ID" Version = "2.5" > < display - name > for springmvc - first < / display - name > < welcome - file - the list > < welcome - file > index. The HTML < / welcome - file > <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <! <servlet> <servlet-name> SpringMVC </ servletname > <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <! -- Specify SpringMVC configuration file --> <! / web-INF /${servlet-name}-servlet.xml --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <! SpringMVC --> <url-pattern>*. Action </url-pattern> </servlet-mapping> </web-app>Copy the code

As you can see from the above configuration, the front-end controller is basically the same as the servlet configuration

Focus on:

1, Configure contextConfigLocation: the configuration file used to load SpringMVC (configure processor mapper, adapter, etc.)

Without contextConfigLocation, web-INF /[Servlet name of DispatcherServlet]-servlet.xml is loaded by default

So both the processor mapper and the processor adapter will be included in the springMVC.xml we specified in the classpath. 2. There are three main interception methods of DispatcherServlet, as follows:

*. Action, which accesses addresses ending in. Action and is parsed by DispatcherServlet. This method is the simplest and does not cause static resources (JPG, JS, CSS) to be blocked. Method 2: /, all accessed addresses are resolved by DispatcherServlet. This method can implement REST-style urls, which are used by many Internet type applications. However, static files (JPG, JS, CSS) will not display properly if intercepted, so static file parsing needs to be configured not to be parsed by DispatcherServlet. [Recommended use in development]

*, this configuration is not correct, using this configuration, most important when forwarding to a JSP page, the DispatcherServlet will still parse the JSP address, according to the JSP page can not find the Handler, will report an error. [Not recommended in development]

1.3.4. Add JSP pages

Create the JSP to the project /WEB-INF/ JSP directory, JSP as follows:

<%@ 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="${itemList }" 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} / itemEdit action? Id = ${item. Id}" > change < / a > < / td > < / tr > < / c: forEach > < / table > < / form >  </body> </html>Copy the code

1.3.5. Realizing the display of commodity list page

1.3.5.1. Create a pojo

Analyze the page and view the data required by the page, as shown below:

Create item POJOs

public class Item {
	Id / / commodities
	private int id;
	// Product name
	private String name;
	// Commodity prices
	private double price;
	// Item creation time
	private Date createtime;
	// Product description
	private Stringdetail; Create a constructor with parameters set/get... }Copy the code
1.3.5.2. Create a plain Java class ItemController

1. ItemController is a plain Java class that doesn’t need to implement any interfaces.

2. Add the @Controller annotation to the class in 1.3.3.1. The creation of SpringMVC.xml is already configured to scan the Controller package, so it is directly managed by Spring

Add @requestMapping to the method to specify the REQUESTED URL. Action can be added or not.

Modelandview.addobject sets and assigns values to its pages (using collections).

@Controller
public class ItemController {

	// @requestMapping: matches the requested URL with the requested URL
	// Action can be written or not written
		// Create the commodity data that the page needs to display
	@RequestMapping(value = "/item/itemlist.action")
    public ModelAndView itemList(){
    	List<Items> list= new ArrayList<Items>();
    	list.add(new Items (1."XiaoMi 9".233f,new Date(),"hhh1"));
    	list.add(new Items (2."XiaoMi 8".233f,new Date(),"hhh1"));
    	list.add(new Items (3."XiaoMi 7".233f,new Date(),"hhh1"));
    	list.add(new Items (4."XiaoMi 6".233f,new Date(),"hhh1"));

		// Create ModelAndView to hold data and view
		ModelAndView modelAndView = new ModelAndView();
		// Set the data to the model
		modelAndView.addObject("itemList", list); // The first argument should correspond to ${value} in JSP.
		// To set the view JSP, you need to set the physical address of the view
		modelAndView.setViewName("/WEB-INF/jsp/itemList.jsp");

		returnmodelAndView; }}Copy the code

1.3.6. Start the project test

Start the project, the browser to access the address http://localhost:8080/springMVC/item/itemlist.action effect below:

1.3.7.org.springframework.web.servlet.DispatcherServlet noHandlerFound

, of course, not every small white once is test failure, very lucky, you are all in the small white QAQ, am I wrong, brother, best wishes, you quoted the org. Springframework. Web. Servlet. DispatcherServlet noHandlerFound warning: No mapping found for HTTP request with URI [/springMVC/iteam/itemlist.action] in DispatcherServlet with name ‘springMVC’ If abnormal, 95% is this abnormal, do not ask me why, the factory director is my table pot.. Cough, this anomaly is relatively easy to appear, I will mention a few cases of this anomaly, shot conscious double click comment 666

Error in configuration of springDispatcherServlet in web.xml

The Handler class does not have the @Controller annotation. The Handler will not scan the class for the @requestMapping annotation.

3. The @requestMapping value is inconsistent with the address entered in the browser

When accessing a static resource, the request is intercepted by a DispatcherServlet interceptor

5. Check the configuration file. Some paths must not correspond

If the starter program is successful, then congratulations, please explore the next step

2. For springMVC framework

2.1 Architecture diagram of springMVC

Ahem… Are you curious why the above springMVC program can be used that way? I’m curious, then I need to analyze the springMVC architecture diagram, tetwitQAq

2.2. Architectural process

1. The user sends the request to the DispatcherServlet of the front-end controller

2. The DispatcherServlet invokes the HandlerMapping processor mapper upon receiving the request.

3. The processor mapper finds the specific processor based on the request URL, generates the processor object and the processor interceptor (if any) and returns it to the DispatcherServlet.

4. The DispatcherServlet invokes the handler through the HandlerAdapter processor adapter

5. Execution processor (Controller, also known as back-end Controller).

6. Controller returns to ModelAndView after execution

7. The HandlerAdapter returns the Controller execution result ModelAndView to the DispatcherServlet

8. The DispatcherServlet passes the ModelAndView to the ViewReslover view parser

ViewReslover returns a specific View after parsing

10. The DispatcherServlet renders the View (i.e. populates the View with model data).

11. DispatcherServlet responds to user

2.3. Springmvc component description

In the various components of SpringMVC, the processor mapper, processor adapter, and view parser are called the three components of SpringMVC.

The following components are typically implemented using frameworks:

 DispatcherServlet: When the user request reaches the front-end controller, it is equivalent to C in MVC mode. DispatcherServlet is the center of the whole process control, and it calls other components to handle the user’s request. The existence of dispatcherServlet reduces the coupling between components.

HandlerMapping HandlerMapping is responsible for finding handlers based on user request URLS. Springmvc provides different mappers to implement different mapping methods, such as configuration files, interface implementation, and annotations.

Handler: processor The Handler is a back-end controller following the front-end controller of DispatcherServlet. Under the control of DispatcherServlet, the Handler processes user requests. Because handlers involve specific user business requests, it is common for programmers to develop handlers based on business requirements.

HandlAdapter: The processor adapter executes on the processor through the HandlerAdapter. This is an application of the adapter pattern, which can be extended to execute on more types of processors. Below are a number of different adapters that can eventually be connected using USB ports

 ViewResolver: View Resolver is responsible for generating View from the processing result. The View Resolver first parses the logical View name into the physical View name, i.e. the specific page address, and generates View objects. Finally, it renders the View and presents the processing result to users through the page.

The SpringMVC framework provides support for many View types, including jstlView, freemarkerView, pdfView, and more. The most common view we use 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.

Components that need to be developed by users include handler and View

2.4. Components loaded by default (Understanding)

We can use these components without doing any configuration because the framework already loads them by default. The configuration file location is shown below:

The code is as follows:

# Default implementation classes for DispatcherServlet's strategy interfaces. # Used as fallback when no matching beans are found in the DispatcherServlet context. # Not meant to be customized by application developers. org.springframework.web.servlet.LocaleResolver=org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver org.springframework.web.servlet.ThemeResolver=org.springframework.web.servlet.theme.FixedThemeResolver org.springframework.web.servlet.HandlerMapping=org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,\ org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping org.springframework.web.servlet.HandlerAdapter=org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,\ org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,\ org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter org.springframework.web.servlet.HandlerExceptionResolver=org.springframework.web.servlet.mvc.annotation.AnnotationMethod HandlerExceptionResolver,\ org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver,\ org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver org.springframework.web.servlet.RequestToViewNameTranslator=org.springframework.web.servlet.view.DefaultRequestToViewNam eTranslator org.springframework.web.servlet.ViewResolver=org.springframework.web.servlet.view.InternalResourceViewResolver org.springframework.web.servlet.FlashMapManager=org.springframework.web.servlet.support.SessionFlashMapManagerCopy the code

2.5. Component scanner

Component scanner main benefits: Using the component scanner saves you the hassle of configuring each Controller class in the Spring container.

Use < context:component-scan > to automatically scan the Controller class marked @Controller,

The component scanner is configured in the springmVC.xml configuration file as follows:

<! -- Configure the controller to scan packets between multiple packets --><context:component-scan base-package="cn.itcast.springmvc.controller" />
Copy the code

2.6. Annotation mapper and adapter

2.6.1. Configure a processor mapper

Annotated processor mapper that maps methods labeled @resquestMapping in a class. According to the url matching method defined by @ResquestMapping, the HandlerMethod object is returned to the front-end controller. The HandlerMethod object encapsulates the Method corresponding to the URL.

Since spring3.1 version, abolishing the DefaultAnnotationHandlerMapping use, it is recommended to use RequestMappingHandlerMapping complete annotation processor type mapping.

In the springmVC.xml configuration file, the configuration is as follows:

<! -- Configure processor mapper --><bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
Copy the code

@requestMapping: Defines the mapping of request urls to handler function methods

2.6.2. Configure the processor adapter

Annotated processor adapter that ADAPTS the method tagged @resquestMapping.

Since spring3.1 version, abolishing the AnnotationMethodHandlerAdapter use, it is recommended to use RequestMappingHandlerAdapter complete annotation processor adapter.

In the springmVC.xml configuration file, the configuration is as follows:

<! Configure the processor adapter --><bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" />

Copy the code
2.6.3. Annotation driven

It is more cumbersome to configure the processor mapper and processor adapter directly, which can be loaded using the annotation driver. For SpringMVC use < MVC: annotation – driven > loading RequestMappingHandlerMapping and RequestMappingHandlerAdapter automatically The annotation processor and adapter configuration can be replaced with < MVC :annotation-driven > in the SpringMVC.xml configuration file.

<! -- Annotation driven --><mvc:annotation-driven />
Copy the code

2.7. View resolver

View the parser using the default InternalResourceViewResolver for SpringMVC framework, this view support JSP view resolution in for SpringMVC parser. The XML configuration file configuration is as follows:

<! -- Example: prefix="/WEB-INF/jsp/", suffix=".jsp", viewname="test" -> 
		"/WEB-INF/jsp/test.jsp" -->
	<!-- 配置视图解析器 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 配置逻辑视图的前缀 -->
		<property name="prefix" value="/WEB-INF/jsp/" />
		<!-- 配置逻辑视图的后缀 -->
		<property name="suffix" value=".jsp" />
	</bean>
Copy the code

The logical view name needs to be returned in the Controller to specify ModelAndView. For example, if the logical view name is ItemList, the JSP view address will be returned: web-INF/JSP/itemlist.jsp

Final JSP physical address: prefix + logical view name + suffix

2.7.1. Modifying Handler (ItemController)

Modify ItemController set in the view of code @ RequestMapping: the requested url is put inside, and matching the user requested url / / action can write also can not write

package com.gx.springmvc;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;


import com.gx.po.Items;
@Controller
public class ItemController {
	@RequestMapping(value = "/item/itemlist.action")
    public ModelAndView itemList(){
    	List<Items> list= new ArrayList<Items>();
    	list.add(new Items (1."XiaoMi 9".233f,new Date(),"hhh1"));
    	list.add(new Items (2."XiaoMi 8".233f,new Date(),"hhh1"));
    	list.add(new Items (3."XiaoMi 7".233f,new Date(),"hhh1"));
    	list.add(new Items (4."XiaoMi 6".233f,new Date(),"hhh1"));
    	
    	ModelAndView mav= new ModelAndView();
    	
    	mav.addObject("itemList",list);
    	mav.setViewName("itemList");
    	returnmav; }}Copy the code
Effect of 2.7.2.

The effect is the same as before, as shown below:

Ah? Pull down! I’m embarrassed to say it. But I can’t stop your proud heart. Then back me up and make me feel your pride! Ha ha

Ha… Ha ha.. Ah.. Ahem… Hic gas QAQ…

2.8 conclusion

I hope you had better be in accordance with the above ideas to start knocking again, walk a process, do not have a high hand low (you will find a start on the bug heaps), learning programming is the most taboo is low!!

If this article helped you at all, please give it a thumbs up. Thanks

Finally, if there is insufficient or improper place, welcome to criticize, grateful! If you have any questions welcome to leave a message, absolutely the first time reply!

Welcome everyone to pay attention to my public number, discuss technology together, yearning for technology, the pursuit of technology, good come is a friend oh…