Handwriting a SPRINGMVC frame yourself

Source: Internet
Author: User
Tags locale reflection xmlns
handwriting A springmvc frame yourself

There are many front-end frames, but none of the frameworks dominate, and the back-end framework now spring has finished unification. So learning Spring is a required course for Java programmers.


The Spring framework is familiar to Java back-end programmers, only to the extent that it was realized with reflection, but only after knowing that there are a lot of clever designs inside. If you do not look at the source of Spring, you will lose a chance to learn from the master: its code specifications, design ideas are worth learning. Most of our programmers are wild and do not know what code specifications are. Wrote one months of code, and finally the other old drivers to spend 3 days to reconstruct, I believe most of the old drivers are very headache to see the novice code.


Needless to say, we're getting to the point today, in Web application design, the MVC pattern has been widely used. SPRINGMVC takes the Dispatcherservlet as the core and coordinates and organizes the different components to complete the request processing and returns the response work, implementing the MVC pattern. To implement your own SPRINGMVC framework, you need to start with the following points:


First, understand the SPRINGMVC operation process and nine major components

Ii. The function analysis of realizing SPRINGMVC by oneself

Third, handwritten springmvc frame


First, understand the SPRINGMVC operation process and nine major components


1, Springmvc of the operation process


· User sends request to Front controller Dispatcherservlet

· Dispatcherservlet received a request to call the Handlermapping processor mapper.

· The processor mapper finds the specific processor based on the request URL, and the Processor object and processor interceptor (if any) are returned to Dispatcherservlet.

· Dispatcherservlet calling the processor via the Handleradapter processor adapter

· The execution processor (controller, also known as the back-end controller).

· Controller execution Complete return Modelandview

· Handleradapter returns the controller execution result Modelandview to Dispatcherservlet

· Dispatcherservlet passing Modelandview to Viewreslover view parser

· Viewreslover return to specific view after parsing

· Dispatcherservlet view is rendered (the model data is populated into the view).

· The Dispatcherservlet responds to the user.


As can be seen from the above, Dispatcherservlet has the function of accepting requests, responding to results, and forwarding. With Dispatcherservlet, you can reduce the degree of coupling between components.


2, SPRINGMVC of nine components

protected void Initstrategies (ApplicationContext context) {

Used to process upload requests. The process is to wrap the normal request into multiparthttpservletrequest, which can call the GetFile method directly to get the file.

Initmultipartresolver (context);


Springmvc mainly has two places to use the locale: first, when the Viewresolver view is parsed, and the second is the use of international resources or themes.

Initlocaleresolver (context);


Used to resolve topics. A theme in Springmvc corresponds to a properties file that contains all the resources associated with the current topic,

such as pictures, CSS styles and so on. SPRINGMVC's theme also supports internationalization,

Initthemeresolver (context);


Used to find the handler.

Inithandlermappings (context);


From the name, it is an adapter. The structure of the processing methods required by the servlet is fixed, and is a method that takes request and response as parameters.

How to make the fixed servlet processing method invoke the flexible handler to handle it. That's what handleradapter to do.

Inithandleradapters (context);


Other components are used for work. In the process of work will inevitably appear problems, what to do after the problem.

This requires a special role to handle the exception, which is handlerexceptionresolver in Springmvc.

Inithandlerexceptionresolvers (context);


Some handler after processing and did not set the view or set the viewname, then need to get viewname from the request,

How to get viewname from the request is what Requesttoviewnametranslator is going to do.

Initrequesttoviewnametranslator (context);


The viewresolver is used to resolve the view name and locale of a string type to a view of the view type.

View is used to render the page, that is, the parameters returned by the program are filled in the template, generating HTML (and possibly other types) of files.

Initviewresolvers (context);


Used to manage Flashmap, Flashmap is used primarily to pass parameters in redirect redirection.

Initflashmapmanager (context);

}



Second, self-realization SPRINGMVC function analysis


This article only implements SPRINGMVC configuration loading, instantiating the scanned package, handlermapping URL mapping to the corresponding controller's method, exception blocking, and dynamic invocation to return the output of the result to the browser function. The rest of the SPRINGMVC feature readers can try their own implementation.


1. Read configuration



As can be seen from the figure, SPRINGMVC is essentially a servlet, which inherits from HttpServlet.


The Frameworkservlet is responsible for initializing the SPRINGMVC container and setting the spring container to the parent container. Because this article is only to implement SPRINGMVC, for the spring container does not do too much explaining (interested students can see another blogger article: to spring big guy bowed down-a lot of source code outflow analysis).


In order to read the configuration in Web. XML, we use the ServletConfig class, which represents the configuration information for the current servlet in Web. Xml. Load our own mydispatcherservlet and read the configuration file via Web. Xml.


2. Initialization phase

In the above, we know that Dispatcherservlet's Initstrategies method initializes 9 large components, but this article implements some of the SPRINGMVC's most basic components, not all of them, in order, including:


· Load configuration file

· Scan all classes below the User Configuration package

· Gets the scanned class, which is instantiated through the reflection mechanism. and put it in the IOC container (map's key value pair Beanname-bean) Beanname default is the first letter lowercase

· Initialize handlermapping, here is actually the URL and method corresponding to the map in a k-v, in the run phase out


3. Operation Stage

Each request will call the Doget or Dopost method, so the unified run phase is handled in the Dodispatch method, which matches the corresponding method according to the URL request to handlermapping. The reflection mechanism is then used to invoke the corresponding method of the URL in the controller, and the results are returned. The following features are included in order:

· Abnormal interception

· Get parameters passed in and process parameters

· The method name corresponding to the URL is taken out through the initialized handlermapping, and the reflection call



Third, handwritten springmvc frame


Project documents and Catalogues:



First, create a new MAVEN project and import the following dependencies in Pom.xml. For convenience, the blogger directly imported the Springboot Web package, which has all the web development stuff we need:

<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.liugh</groupId>

<artifactId>liughMVC</artifactId>

<version>0.0.1-SNAPSHOT</version>

<packaging>war</packaging>

<dependencyManagement>

<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-dependencies</artifactId>

<version>1.4.3.RELEASE</version>

<type>pom</type>

<scope>import</scope>

</dependency>

</dependencies>

</dependencyManagement>

<properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

<maven.compiler.source>1.8</maven.compiler.source>

<maven.compiler.target>1.8</maven.compiler.target>

<java.version>1.8</java.version>

</properties>

<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

</dependencies>

</project>


Next, we create a Web. XML under Web-inf, with the following configuration:

<?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" xmlns:web= "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"

version= "3.0" >

<servlet>

<servlet-name>MySpringMVC</servlet-name>

<servlet-class>com.liugh.servlet.MyDispatcherServlet</servlet-class>

<init-param>

<param-name>contextConfigLocation</param-name>

<param-value>application.properties</param-value>

</init-param>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>MySpringMVC</servlet-name>

<url-pattern>/*</url-pattern>

</servlet-mapping>


</web-app>


The application.properties file simply configures the package to be scanned into the SPRINGMVC container.

Scanpackage=com.liugh.core


Create your own controller annotations, which can only be labeled on the class:

Package com.liugh.annotation;


Import java.lang.annotation.Documented;

Import Java.lang.annotation.ElementType;

Import java.lang.annotation.Retention;

Import Java.lang.annotation.RetentionPolicy;

Import Java.lang.annotation.Target;


@Target (Elementtype.type)

@Retention (Retentionpolicy.runtime)

@Documented

Public @interface Mycontroller {

/**

* Indicates controller registration alias

* @return

*/

String value () default "";

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.