Spring MVC learning Summary (1) -- mvc overview and environment configuration are reproduced from the [Zhang Guo] blog, springmvc
Spring MVC learning Summary (1) -- mvc overview and environment Configuration
Directory
- I. MVC Overview
- II. Introduction to Spring MVC
- 3. The first Spring MVC project: Hello World
- 3.1 create a Web project through Maven
- 3.2 add dependent jar packages
- 3.3 modify the DispatcherServlet controller of the web. xml registration center.
- 3.4 add Spring MVC configuration file
- 3.5 create a HelloWorld Controller
- 3.6 create a view
- 3.7 test run
- 3.8 sample download
I. MVC Overview
MVC is short for models, views, and controllers. It is a software design specification, code is organized using a method that separates business logic, data, and display. The main function of MVC is to reduce the bidirectional coupling between views and business logic. MVC is not a design pattern, but an architecture pattern. Of course, there are differences between different MVC.
In early web development, Model1 is usually used. Model1 consists of two layers: view layer and model layer. Model2 divides a project into three parts: View, control, and model. This not only improves the code reuse rate and project scalability, but also greatly reduces the project maintenance cost. The implementation of Model 1 mode is relatively simple and suitable for rapid development of small-scale projects. In Model1, the JSP page is composed of two roles: View and Controller. The control logic and presentation logic are mixed together, as a result, code reusability is very low, which increases the scalability and maintenance of applications. Model2 eliminates the disadvantages of model1.
Model1
Model2
Common server-side MVC frameworks include Struts, Spring MVC, and ASP. net mvc, Zend Framework, and JSF; common front-end MVC frameworks: angularjs, reactjs, and backbone; other models such as MVP and MVVM have been developed by MVC.
II. Introduction to Spring MVC
Spring MVC is a part of Spring Framework and a lightweight Web Framework that implements MVC Based on Java. Features of Spring MVC:
1. lightweight
2. Efficient
3. good compatibility with Spring
4. Powerful functions
RESTful, data verification, formatting, binding mechanism, localization, topic, etc.
5. Concise and flexible
Spring web framework is designed around DispatcherServlet. DispatcherServlet is used to distribute requests to different processors. Beginning with Spring 2.5, users using Java 5 or later versions can adopt the annotation-based controller declaration method. On the official website, Spring's web module provides many unique features, including:
Clear roles: Controller, validator, command object, form object, model object, and Servlet distributor) handler ing and view resolver. Each role can be implemented by a special object.
Powerful and direct Configuration: The framework class and application class can be configured as JavaBean and can be referenced across multiple contexts. For example, the service object and validator can be referenced in the web controller.
Adaptive, non-intrusive: You can select an appropriate controller subclass (simple, command, form, wizard, multi-action, or custom) based on different application scenarios ), instead of inheriting from a single controller (such as Action/ActionForm.
Reusable business code: You can use an existing business object as a command or form object without extending the base class of a specific framework.
Customizable binding and validation): For example, if the Type mismatch is used as an application-level verification error, the error value can be saved. For example, the localized date and number binding. In some other frameworks, you can only use string form objects. You need to manually Parse them and convert them to business objects.
Customizable handler mapping and view resolution: Spring provides simple URL ing to complicated and dedicated custom policies. Compared with some web MVC frameworks that force developers to use a single specific technology, Spring is more flexible.
Flexible model conversion: In the Springweb framework, Map-based Key/value pairs are used to easily integrate with various view technologies.
Customizable localization and theme resolution: Spring label library, JSTL, Velocity (no additional Middle Layer required) can be selected in JSP.
Simple and powerful JSP Tag Library): Supports many features, such as data binding and theme. It provides maximum flexibility in marking.
JSP form tag Library: The form tag library introduced in Spring2.0 makes it easier to write forms in JSP.
The lifecycle of Spring Bean can be restricted to the current HTTP Request or HTTP Session.. To be precise, this is not a feature of Spring MVC framework, but belongs to the WebApplicationContext container used by Sping MVC.
3. The first Spring MVC project: Hello World3.1. Create a Web project through Maven
Create a Maven project in Eclipse, select "Create a simple project", and Create a simple project without selecting a template.
For more details, see the previous article:
Copy all content in webcontent to the webapp directory and delete the webContent directory. The deletion result is as follows:
Modify the project deployment information, delete the test folder, and add webapp as the project root directory:
If you do not want to add a dependency on Server runtime in pom. xml, you must manually add the dependency here, as shown in:
In addition, if an error occurs in pom. xml, modify the settings and save the settings.
3.2 add dependent jar packages
1. Modify the pom. xml file and add jar package dependencies, including the Spring framework core library, Spring MVC, and JSTL. The details are as follows:
<Project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion> 4.0.0 </modelVersion> <groupId> com. zhangguo </groupId> <artifactId> SpringMVC01 </artifactId> <version> 0.0.1 </version> <packaging> war </packaging> <properties> <project. build. sourceEncodi Ng> UTF-8 </project. build. sourceEncoding> <spring. version> 4.3.0.RELEASE </spring. version> </properties> <dependencies> <! -- Core library of Spring framework --> <dependency> <groupId> org. springframework </groupId> <artifactId> spring-context </artifactId> <version >$ {spring. version }</version> </dependency> <! -- Spring MVC --> <dependency> <groupId> org. springframework </groupId> <artifactId> spring-webmvc </artifactId> <version >$ {spring. version }</version> </dependency> <! -- JSTL --> <dependency> <groupId> javax. servlet </groupId> <artifactId> jstl </artifactId> <version> 1.2 </version> </dependency> </dependencies> </project>
When the dependency is successful, the jar package will be loaded as follows:
3.3 modify the DispatcherServlet controller of the web. xml registration center.
Like many other MVC frameworks, the Spring MVC Framework request-driven distributes requests and provides other functions around a central Servlet. DispatcherServlet is an actual Servlet (which inherits from the HttpServlet base class ). As shown in, when a request is initiated, the request is intercepted by the front-end controller. A proxy request is generated based on the request parameters, and the actual controller corresponding to the request is found. The controller processes the request, creates a data model, and accesses the database, the model is returned to the central controller. The controller uses the model and view to render the view results, returns the results to the central controller, and then returns the results to the requester.
Modify the web. xml file to register the Servlet. The modified web. xml file is as follows:
<? 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_3_0.xsd" id = "WebApp_ID" version = "3.0"> <servlet> <! -- Name --> <servlet-name> springmvc </servlet-name> <! -- Servlet class --> <servlet-class> org. springframework. web. servlet. DispatcherServlet </servlet-class> <! -- The startup sequence, the smaller the number, the earlier the startup --> <load-on-startup> 1 </load-on-startup> <init-param> <! -- SpringMVC configuration parameter file location --> <param-name> contextConfigLocation </param-name> <! -- The default name is ServletName-servlet.xml --> <param-value> classpath *: springmvc-servlet.xml </param-value> </init-param> </servlet> <! -- All requests are intercepted by springmvc --> <servlet-mapping> <servlet-name> springmvc </servlet-name> <url-pattern>/</url-pattern> </ servlet-mapping> </web-app>
3.4 add Spring MVC configuration file
Add the springmvc-servlet.xml configuration file under the src/main/java source code directory, the configuration form is similar to the Spring container configuration, in order to support annotation-based IOC, set the function of automatic scanning package, the specific configuration information 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: 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.xsd http://www.springframework.org/schema/context h Ttp: // www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd "> <! -- Automatically scans the package to realize IOC that supports annotation --> <context: component-scan base-package = "com. zhangguo. springmvc01"/> <! -- Spring MVC does not process static resources --> <mvc: default-servlet-handler/> <! -- Support mvc annotation driver --> <mvc: annotation-driven/> <! -- View parser --> <bean class = "org. springframework. web. servlet. view. InternalResourceViewResolver" id = "internalResourceViewResolver"> <! -- Prefix --> <property name = "prefix" value = "/WEB-INF/view/"/> <! -- Suffix --> <property name = "suffix" value = ". jsp"/> </bean> </beans>
In view resolution, we store all views under the/WEB-INF/directory to ensure view security, because this Directory Client cannot be directly accessed.
3.5 create a HelloWorld Controller
Create the package com. zhangguo. springmvc01.controller In the src/main/java source code directory and create a common class: HelloWorld under the package. The Code is as follows:
package com.zhangguo.springmvc01.controller;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;@Controller@RequestMapping("/Hello")public class HelloWorld { @RequestMapping("/Sayhi") public String SayHi(Model model) { model.addAttribute("message", "Hello Spring MVC!"); return "sayhi"; }}
Annotation @ Controller is used to enable the Spring IOC container to automatically scan during initialization; @ RequestMapping is used to map request paths, here, because the classes and methods are mapped, the access should be/Hello/Sayhi; parameters of the Model type declared in the method are used to bring the data in the Action to the view; the result returned by the method is the view name sayhi.
3.6 create a view
Create a view in the WEB-INF/view directory and the information that the view brings back from the Action is as follows:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><!DOCTYPE html>3.7 test run
To start a Tomcat running project, check the startup information. If an exception exists, resolve the exception information. The result is as follows: