Preliminary SpringMVC, into the world SpringMVC

1.Springmvc entry

What is 1.1.Springmvc

SpringMVC Spring is a component of the current (2019) at the Internet company with a lot of technology is an essential framework for learning! SpringMVC for web layer corresponds Controller (equivalent to action servlet and conventional struts or Hendler), to process the user request. For example, users in the address bar http: // domain / login, then springmvc will intercept this request and the corresponding method call controller layer, (middle may contain business logic validation user name and password, as well as queries database operations, but these are not springmvc duty), the final results returned to the user, and returns the corresponding page (of course, only to be returned data format json / xml, etc.). springmvc is to do in front of and behind the living process of dealing with the user! ! springmvc need to have spring jar package as a support to run up, so learn Spring is also very important!

Spring web mvc Struts2 belong frame and the presentation layer, which is part of the Spring framework, we can see the entire configuration of Spring, as shown below:

Here Insert Picture Description

1.2.Springmvc process flow

As shown below:

Here Insert Picture Description

1.3. Getting Started program

Requirements: Use browser to display the Product List

1.3.1. Creating a web project

springMVC is a presentation layer framework, need to build a web project development. Create a dynamic web project:

Enter a project name, select Configure Tomcat (if there is direct use), as shown below:

Here Insert Picture Description

Select successful, click Finish, as shown below:

Here Insert Picture Description
Select just successfully set of Tomcat, as shown below:
Here Insert Picture Description

FIG selected as the web version 2.5, can automatically generate web.xml configuration file,

Here Insert Picture Description

Create the following picture:

Here Insert Picture Description

1.3.2. Import jar package

SpringMVC introduced from the front profile class jar package, as shown below:

Here Insert Picture Description

Copy the jar to the lib directory, engineering loaded directly jar package, as shown below:

Here Insert Picture Description

1.3.3. Join Profiles

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

Here Insert Picture Description

1.3.3.1. Creating springmvc.xml

Creating SpringMVC core configuration file itself is springmvc.xml SpringMVC Spring subprojects, of Spring compatibility is very good, you do not need to do a lot of configuration. Here and only one Controller scan on it, let the Spring of page Control Layer Controller management.

Creating 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>
复制代码
1.3.3.2.springmvc.xml adapter processor configured HandlerAdapter

Because the processor Handler should be developed according to the requirements of the adapter, so let's look at the configuration adapter HandlerAdapter, in the configuration 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">

    <!-- 处理器适配器:HandlerAdapter。所有处理器适配器都实现了HandlerAdapter接口-->
    <!-- SimpleControllerHandlerAdapter适配器能执行实现了Controller接口的Handler 
    所以,现在配置了这个适配器的话,所有的处理器Handler必须要实现Controller接口才行。
-->
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" /> 
</beans>
复制代码
1.3.3.3.springmvc.xml processor configured mapper HandlerMapping

Here Insert Picture Description

1.3.3.4.web.xml configuration view resolver ViewResolver

Configuration view resolver ViewResolver, jsp can be resolved so that the final physical address jsp: prefix + suffix logical view name +

Configuration view resolver ViewResolver Code:

 <!-- 视图解释器 -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
              <!-- 前缀 -->
        	<property name="prefix" value="/WEB-INF/jsp/"/>
        	  <!-- 后缀 -->
        	<property name="suffix" value=".jsp"/>
        </bean>
复制代码
1.3.3.5.web.xml the overall effect of the code

web.xml in general to include:

1, springmvc.xml "head"

2, configure the processor component scans Handler (Controller)

3, the adapter processor HandlerAdapter

4, the processor mapper HandlerMapping

5 viewresolver ViewResolver

the overall effect web.xml code 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"/>
      
        <!-- 处理器映射器 -->
        <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
      
        <!-- 处理器适配器 -->
        <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
       
        <!-- 视图解释器 -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
              <!-- 前缀 -->
        	<property name="prefix" value="/WEB-INF/jsp/"/>
        	  <!-- 后缀 -->
        	<property name="suffix" value=".jsp"/>
        </bean>
   </beans>
复制代码

Profile desired constraint file, and as shown below:

Here Insert Picture Description

Create a package com.gx.springmvc.controller

1.3.3.6. DispatcherServlet front controller configuration in web.xml

SpringMVC front controller configuration in web.xml DispatcherServlet

<?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>springmvc-first</display-name>
	<welcome-file-list>
		<welcome-file>index.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>

	<!-- 配置SpringMVC前端控制器 -->
	<servlet>
		<servlet-name>springMVC</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- 指定SpringMVC配置文件 -->
		<!-- SpringMVC的配置文件的默认路径是/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>
		<!-- 设置所有以action结尾的请求进入SpringMVC -->
		<url-pattern>*.action</url-pattern>
	</servlet-mapping>
</web-app>

复制代码

As can be seen from the above configuration, before learning servlet configuration substantially exactly the same time, it is equivalent to a front end controller servlet

Priority Note:

1, the configuration the contextConfigLocation : springmvc used to load configuration files (configuration mapper processor, adapter, etc.)

Not configured contextConfigLocation, then loaded by default WEB-INF / [Servlet name of DispatcherServlet] -servlet.xml

So mapper processor and processor adapter will fit in our classpath specified in springmvc.xml. 2, the DispatcherServlet interception way , there are three main ways to intercept, as follows:

Method 1: * .action , you can access the address .action ending, be resolved by DispatcherServlet. This method is simple, does not cause static resources (jpg, js, css) was blocked. [Development] is often used in two ways: / , all accessible by DispatcherServlet address parsing, REST-style url this method can be achieved, many types of applications using the Internet in this way. However, this method results in static files (jpg, js, css) after being intercepted can not be shown, so the resolution requires a static configuration files let DispatcherServlet resolution. [Development] is recommended

Three ways: * When such configuration is wrong with this configuration, the most important is forwarded to a jsp page, jsp address will still be resolved by the DispatcherServlet, according to jsp page can not be found Handler, error. [Development] is not recommended

1.3.4. The jsp page

jsp to create under 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"%>
<!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> 
<form action="${pageContext.request.contextPath }/item/queryitem.action" method="post">
查询条件:
<table width="100%" border=1>
<tr>
<td><input type="submit" value="查询"/></td>
</tr>
</table>
商品列表:
<table width="100%" border=1>
<tr>
	<td>商品名称</td>
	<td>商品价格</td>
	<td>生产日期</td>
	<td>商品描述</td>
	<td>操作</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}">修改</a></td>

</tr>
</c:forEach>

</table>
</form>
</body>
</html>
复制代码

1.3.5. Implement display the Product List Next

1.3.5.1. Creating pojo

Page analysis, data needed to view the page, as shown below:

Here Insert Picture Description

Creating merchandise pojo

public class Item {
	// 商品id
	private int id;
	// 商品名称
	private String name;
	// 商品价格
	private double price;
	// 商品创建时间
	private Date createtime;
	// 商品描述
	private String detail;

创建带参数的构造器
set/get。。。
}
复制代码
1.3.5.2. Creating common java class ItemController

1, ItemController java class is a common, need not implement any interface.

2, requires the class to add @Controller notes , in 1.3.3.1. Creating springmvc.xml has been configured to scan the Controller package, so sent directly to Spring Management

3, in the method of surface @RequestMapping add annotations , which specify the request url. Where ".action" can also be added without.

4, due to the entry procedures, for the time being not connected to a database, modelAndView.addObject to their page settings and assignment (on set)

@Controller
public class ItemController {

	// @RequestMapping:里面放的是请求的url,和用户请求的url进行匹配
	// action可以写也可以不写
		// 创建页面需要显示的商品数据
	@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,用来存放数据和视图
		ModelAndView modelAndView = new ModelAndView();
		// 设置数据到模型中
		modelAndView.addObject("itemList", list); //第一个参数要对应JSP中的${value}
		// 设置视图jsp,需要设置视图的物理地址
		modelAndView.setViewName("/WEB-INF/jsp/itemList.jsp");

		return modelAndView;
	}
}
复制代码

1.3.6. Start test project

Startup Items, browser access to the address http: // localhost: 8080 / springMVC / item / itemlist.action the following picture:

Here Insert Picture Description

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

Of course, not every white can test failed once, very lucky, you're Wan none of the white QAQ, I did not guess wrong, brother tinkling, you reported 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, and 95% are the exception, do not ask me why, I watch the director pot. . Keke, is more prone to this anomaly, I will cite a few cases of the exception it appears, double-click in the gun conscious attention 666 comments

1, an error of springDispatcherServlet arranged in web.xml

2, Handler class does not add @Controller annotation processor will not be scanned if the class has used @RequestMapping comment.

3, @ RequestMapping value and in the browser address entered inconsistent

4, when accessing static resources, the request will be blocked DispatcherServlet interceptor

5, check the configuration file, it must be in some places does not correspond to the path

If the entry procedure is successful, then Congratulations, your next step is to explore

2.springMVC architecture

2.1springMVC architecture diagram

Ahem .. Xiongtai you are not very curious why the above springMVC program can use it like? Curious on the right, it would need to analyze the architecture diagram springMVC, trained, trained, trained QAQ

Here Insert Picture Description

2.2. Process Architecture

1, the user sends a request to the front-end controller DispatcherServlet

2, DispatcherServlet call request is received HandlerMapping processor mapper.

3, the processor finds a specific mapping processor according to the request url, the object generation processor and a processor blocker (if any is generated) together back to DispatcherServlet.

4, DispatcherServlet call processor by HandlerAdapter processor adapter

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

6, Controller execute complete return ModelAndView

7, HandlerAdapter the controller to return the results ModelAndView DispatcherServlet

8, DispatcherServlet ModelAndView will pass ViewReslover view resolver

9, ViewReslover particular View returns parsed

10, DispatcherServlet render view of View (model data coming filled into view).

11, DispatcherServlet response to user

2.3.springmvc Component Description

Springmvc the various components, the processor mapper processor adapter viewresolver springmvc called the three components .

The following components are typically implemented using the framework provided:

the DispatcherServlet: front-end controller user request reaches the front end controller, it is equivalent mvc mode c, dispatcherServlet center of the entire process is controlled by the other components of the processing which calls the user's request, the presence of reduced DispatcherServlet between components coupling.

HandlerMapping: a processor mapper HandlerMapping responsible user request url found Handler i.e. processor, provides a different SpringMVC mapper mapping achieve different ways, for example: profiles, to achieve interface mode, annotation methods.

Handler: processor Handler is the second back-end DispatcherServlet front controller, under the control of DispatcherServlet Handler for specific user requests are processed. Since Handler related to specific user service request, it is generally required Handler programmers based on business needs.

HandlAdapter: Processor Adapter through HandlerAdapter of processors, which is an application of the adapter mode, the processor may be more types of expansion performed by the adapter. The figure is the number of different adapters, can ultimately be used usb interface

Here Insert Picture Description

ViewResolver: view resolver View is responsible for the Resolver View to generate the processing result, the Resolver View resolved to a specific name is the view of the physical page address according to the logical name of the view, then the view object generates View, View last rendering processing results page presented to the user.

View: view springmvc framework provides a lot of View view type of support, including: jstlView, freemarkerView, pdfView and so on. Our view is that the most commonly used jsp.

You need to model data show generally by page or tag page by page template technology to users, programmers need to develop a specific page based on business needs.

Component requires the user to have developed handler, view

2.4. Default component loaded (understand)

We did not do any configuration, you can use these components because these components framework has been loaded by default, the profile location as shown below:

Here Insert Picture Description

code show as below:

# 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.AnnotationMethodHandlerExceptionResolver,\
	org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver,\
	org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver

org.springframework.web.servlet.RequestToViewNameTranslator=org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator

org.springframework.web.servlet.ViewResolver=org.springframework.web.servlet.view.InternalResourceViewResolver

org.springframework.web.servlet.FlashMapManager=org.springframework.web.servlet.support.SessionFlashMapManager

复制代码

2.5. Components scanner

The main role of the scanner assembly: using the scanner assembly complicated configuration is omitted in each class Controller spring containers .

Use <context: component-scan> tag @Controller automatically scan controller class,

Springmvc.xml scanner assembly configuration file is as follows:

<!-- 配置controller扫描包,多个包之间用,分隔 -->
<context:component-scan base-package="cn.itcast.springmvc.controller" />
复制代码

2.6. Annotation map and Adapters

2.6.1. Configure the processor Mapper

Annotation processors mapper class tagged @ResquestMapping method map. The method defined url @ResquestMapping @ResquestMapping matching tag, the matching HandlerMethod successful return object to the front controller. HandlerMethod object corresponding method of packaging url Method.

From spring3.1 release, abolished the use of DefaultAnnotationHandlerMapping recommended RequestMappingHandlerMapping complete mapping annotation processors.

In springmvc.xml configuration file is as follows:

<!-- 配置处理器映射器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
复制代码

Annotation Description: @RequestMapping : definition request url to the mapping processor function method

2.6.2. Processor Adapter Configuration

Annotation processors adapter for marking @ResquestMapping method is adapted.

From spring3.1 release, abolished the use of AnnotationMethodHandlerAdapter recommended RequestMappingHandlerAdapter complete annotation processors adaptation.

In springmvc.xml configuration file is as follows:

<!-- 配置处理器适配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" />

复制代码
2.6.3. Annotation-driven

Direct mapping and a processor configure the processor adapter troublesome, annotations can be used to load the driver. Use SpringMVC <mvc: annotation-driven> RequestMappingHandlerAdapter autoloader RequestMappingHandlerMapping and can be used in the configuration file springmvc.xml <mvc: annotation-driven> alternative configurations annotation processor and adapters.

<!-- 注解驱动 -->
<mvc:annotation-driven />
复制代码

2.7. View resolvers

View SpringMVC framework parser uses the default InternalResourceViewResolver, this view resolver support JSP view resolution in springmvc.xml configuration file 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>
复制代码

Logical view names need to be specified in return ModelAndView controller, such as named logical view ItemList, jsp view of the final return address: "WEB-INF / jsp / itemList.jsp"

The final physical address jsp: prefix + suffix logical view name +

2.7.1. Modify Handler (ItemController)

Modify the settings view ItemController code @RequestMapping : url is put inside the request, and requests the user to match url // action may or may not write the 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");
    	return mav;
    }
}

复制代码
2.7.2. Effects

Exactly as before, as shown below:

Here Insert Picture Description
Here brother tinkling, springMVC entry procedures and SpringMVC architecture will have a certain understanding! Is not that great sense of accomplishment

Ah? Leave it! I am sorry to say, but I can not stop you proud of heart. Then the top of me and let me feel the feelings your pride! Haha

Ha ... ha ha .. ah .. Ahem .. belch gas a QAQ ...

2.8 Conclusion

I hope that the best is in accordance with the above ideas to their own hands to knock again, take a process , not to have unrealistic expectations (you'll find a hands-on bug piles), the most taboo is to learn programming attracted me! ! !

If this article there is a little bit of help to you, then please point a chant praise, thank you ~

Finally, if there is insufficient or is not correct, please correct me criticism, grateful! If you have questions please leave a message, the absolute first time to reply!

I welcome you to focus on the public number, to explore technology, yearning technology, the pursuit of technology, said good pots Friends is coming Oh ...

Here Insert Picture Description

Guess you like

Origin juejin.im/post/5dddc3a16fb9a0716c07f97e