SpringMVC introductory learning (1)

What is SpringMVC?

Generally, when you first start learning a framework, you will definitely ask this question. First, put an old picture.


Spring web mvc and Struts2 both belong to the framework of the presentation layer , it is a part of the Spring framework , we can see from the overall structure of Spring .

SpringMVC is an MVC-based web framework

Since the development and design mode of mvc is mentioned, let's take a look at the application of mvc mode in the b/s system :


1.  The user initiates a request request to the controller (Controller)

Controls receiving the data requested by the user and entrusting it to the model for processing

2.  The controller processes the data through the model (Model) and obtains the processing result

Model usually refers to business logic

3. The model processing result is returned to the controller

4.  The controller displays the model data in the view (View)

In the web , the model cannot display the data directly on the view, it needs to be done through the controller. If the model in the C/S application can display the data in the view.

5.  The controller responds the view to the user

Display the desired data or processing results to the user through the view.

SpringMVC Architecture Diagram

Architecture Flow:

Step 1: Initiate a request to the front controller (DispatcherServlet)

Step 2: The front controller requests HandlerMapping to find the Handler

You can search according to xml configuration and annotations

Step 3: The handler mapper HandlerMapping returns Handler to the front controller

Step 4: The front controller calls the handler adapter to execute the Handler

Step 5: Handler adapter to execute Handler

Step 6: Handler execution completes and returns ModelAndView to the adapter

Step 7: The handler adapter returns the ModelAndView to the front controller

ModelAndView is an underlying object of the springmvc framework, including Model and view

Step 8: The front controller requests the view resolver to perform view resolution

According to the logical view name is resolved into a real view (jsp)

Step 9: The view resolver returns the View to the front controller

Step 10: Front-end controller for view rendering

View rendering populates the request field with model data ( in the ModelAndView object )

Step 11: The front controller responds to the user with the result


Component introduction:

1. Front-end controller DispatcherServlet (no need for programmer development)

The function is to receive the request and respond to the result, which is equivalent to the repeater, the central processing unit.

With DispatcherServlet reduces the coupling between other components. 

2 , the processor mapper HandlerMapping ( no need for programmer development )

Role: Find Handler according to the requested url 

3. Handler Adapter HandlerAdapter

Role: execute Handler according to specific rules (rules required by HandlerAdapter )

4. Handler ( requires programmer development )

Note: When writing Handler , follow the requirements of HandlerAdapter , so that the adapter can execute Handler correctly

5. View resolver View resolver ( no need for programmer development )

Function: perform view resolution, and resolve it into a real view ( view ) according to the logical view name

6. View View ( requires programmers to develop jsp )

View is an interface, and the implementation class supports different View types ( jsp , freemarker , pdf... )

Getting Started Program:

Requirement: Realize the product list query in the previous mybatis study

Environment preparation: database mysql5.1, four tables in mybatis learning, jdk1.7.0_72, springmvc3.2, spring3.2 (must include spring-webmvc-3.2.0.RELEASE.jar)

1. First configure the front controller in web.xml

<!--springmvc front controller-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--contextConfigLocation configures the configuration files loaded by springmvc (configure processor mappers, adapters, etc., if contextConfigLocation is not configured, the default load is /WEB-INF/servlet name=servlet.xml(springmvc-servlet.xml)) -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!--There are three configuration methods:
The first type: *.action, the access ends with .action and is parsed by DispatcherServlet
The second type: /, so the accessed addresses are parsed by DispatcherServlet. For the parsing of static files, it is necessary to configure not to allow DispatcherServlet to parse. This method can achieve RESTful urls
The third type: /*, this configuration is wrong. When using this configuration, when it is finally forwarded to a jsp page, the jsp address will still be parsed by the DispatcherServlet. If the handler cannot be found according to the jsp page, an error will be reported. -->
<url-pattern>*.action</url-pattern>
</servlet-mapping>

2, create the springmvc.xml file under the classpath

According to the above springmvc architecture diagram, we can find that we need to configure in the springmvc.xml configuration file: 1, processor mapper (find the corresponding Handler according to the requested URL), 2 processor adapter (execute the corresponding Handler according to the corresponding rules) Handler), 3, view resolver (for view resolution)

<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 ">
 <!-- Configure adapters and mappers-->
 <mvc:annotation-driven></mvc:annotation-driven>
 <!-- -Can scan the controller, service here let the scan controller configure the component scan controller -->
 <context:component-scan base-package="com.travelsky.cn.ssm.controller"></context:component-scan>
   <!- - Configure the view parser prefix and suffix that parses JSP to find the prefix and suffix of the view page. The final view address is: prefix + logical view name + suffix. The logical view needs to return the ModelAndView specification in the Controller. For example, the logical view name is hello, then the final view address is: The returned jsp view address is: "jsp/items/hello.jsp"-->
   <bean class="org.springframework.web.servlet.view.
InternalResourceViewResolver"> <!--Prefix -->
	
					
	  
			  		  	<property name="prefix" value="/jsp/items/"/>
<!--后缀 -->
<property name="suffix" value=".jsp"/>
  </bean>
  
</beans>	  		  			

3. Create the /WEB-INF/jsp/itemsList.jsp view page:

<%@ 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>Query product list</title>
</head>
<body>
Product list:
<table width="100%" border=1>
<tr>
	<td>Product name</td>
	<td>Item Price</td>
	<td>Item description</td>
</tr>
<c:forEach items="${itemsList }" var="item">
<tr>
	<td>${item.name }</td>
	<td>${item.price }</td>
	<td>${item.detail }</td>
</tr>
</c:forEach>

</table>
</body>
</html>

4. Develop Handler

Use annotation mappers and annotation adapters. (Annotated mappers and annotation adapters must be paired)

//use Controller to identify it as a controller
@Controller
public class ItemsController3 {
	
	//Commodity query list
	//@RequestMapping implements mapping between queryItems method and url, one method corresponds to one url
	//It is generally recommended to write the same url and method
	@RequestMapping("/queryItems")
	public ModelAndView queryItems()throws Exception{
		
		/ / Call the service to find the database, query the product list, here use static data simulation
		List<Items> itemsList = new ArrayList<Items>();
		// fill the list with static data
		
		Items items_1 = new Items();
		items_1.setName("Lenovo Notebook");
		items_1.setPrice(6000f);
		items_1.setDetail("ThinkPad T430 Lenovo laptop!");
		
		Items items_2 = new Items();
		items_2.setName("iPhone");
		items_2.setPrice(5000f);
		items_2.setDetail("iphone6 ​​Apple mobile phone!");
		
		itemsList.add(items_1);
		itemsList.add(items_2);
		
		//return ModelAndView
		ModelAndView modelAndView = new ModelAndView();
		//equivalent to setAttribut of request, get data through itemsList in jsp page
		modelAndView.addObject("itemsList", itemsList);
		
		//specify the view
		modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp");
		
		return modelAndView;
		
	}

5. Deploy and debug

If the page displays a list of items by requesting http://localhost:8080/springmvc/queryItems.action, it means that the starter program is running successfully!


Source code analysis:

Analyze the execution process of springmvc through the front-end controller source code

Step 1: The front controller receives the request

call doDiapatch


Step 2:

1. DispatherServlet calls HandlerMapping (handler mapper) to find Handler according to url


third step:DispatherServlet calls HandlerAdapter ( handler adapter ) to package and execute the Handler found by HandlerMapping . After the HandlerAdapter executes the Handler , it returns a ModelAndView (springmvc encapsulation object )

DispatherServlet finds a suitable adapter:

Adapter executes Hanlder


Step 4: View Rendering DispatherServlet takes ModelAndView to call ViewResolver (view resolver) for view resolution, and returns a View (many Views of different view types ) after the resolution is completed.


View resolution, get the view:


Call the rendering method of the view to fill the model data into the request field

Rendering method:



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325974641&siteId=291194637