Build a Web application framework with spring MVC-complete case

Source: Internet
Author: User

Chen Kozhan-Reprint Please specify the source, http://blog.csdn.net/u013474104/article/details/43707459

============

1. Introduction

First spring MVC is based on three levels, and what about three levels?

M (model)-models layer , after the controller completes the logic processing, usually produces some information, and this information needs to return to the user and displays on the browser, we call this information the model;

V (view)- The view layer, we use JSP as the view layer, through the view can make these model data render output, and through this output response to you pass to the client;

C (Controller)-the control layer , which begins with the user submitting the request, passes through a front-end controller servlet, then resolves by the front-end controller servlet, and then assigns the user request to a particular controller, the control layer.

three layers of the relationship: the user submits the request, through the front-end controller servlet parsing, and then specify the controller, when the controller processing logic information, return model data, and then the specified view of the model data rendered output, and finally presented to the client, that is, the user.

2. Introducing the Spring MVC jar Package

Because my previous article described Maven's use (the project was built with MAVEN), we use MAVEN dependencies to correlate the download of spring's jar packages.

If you don't know how to configure dependencies, enter the URL: http://mvnrepository.com/, which provides a jar-dependent query, and so on.

First, search for what is needed,


There's a whole bunch of related listings, find what we need or you can enter a named search faster


Click to go to select version


Click to go in and copy the dependencies out to your pom.xml, then


Pom.xml configuration:

<project>...<!--define properties for ${propertiename} access  <properties>  < Project.build.sourceencoding>utf-8</project.build.sourceencoding>  <spring.version>4.1.3. release</spring.version>  </properties>  <!--dependency---  <dependencies>  < Dependency><groupid>org.springframework</groupid><artifactid>spring-webmvc</artifactid ><version>${spring.version}</version></dependency>  </dependencies>...</ Project>

After you finish, perform pom.xml update


See, the associated jar will be downloaded to the local repository, which is the benefit of using Maven!

3. Configuring a front-end controller servlet

In spring MVC, all requests are required to be a front-end controller servlet, Dispatcherservlet, which is the core of spring MVC.

The Dispatcherservlet must be configured in the Web. xml file for the application, configured as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><web-app ... >...<!--Spring MVC front-end controller-  <servlet><servlet-name>wwo</servlet-name>< servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class><init-param>< Param-name>contextconfiglocation</param-name><param-value>                            Classpath:conf/wwo-servlet.xml                        </param-value></init-param><load-on-startup>1</load-on-startup></servlet> <servlet-mapping><servlet-name>wwo</servlet-name><url-pattern>/</url-pattern> </servlet-mapping>...</web-app>

The purpose of Dispatcherservlet is both to load its configuration into the spring application context based on an XML file, and the XML file is named by default by <servlet-name> to the XML file name, which is our common ${<servlet-name>}-servlet.xml, as the above example XML file is named: Wwo-servlet.xml (the default path is located in the Web-inf directory of the application). Usually our spring configuration file can be divided into multiple XML files, one for the service layer, one for the persistence layer and one for the data source configuration. What about that?

Spring provides me with a contextloaderlistener, which is a servlet listener, and we simply configure the Contextloaderlistener in the Web. xml file as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><web-app ...>...<!--Spring Listener-  <listener>  <listener-class>  Org.springframework.web.context.ContextLoaderListener  </listener-class >  </listener>...</web-app>
However, if you configure the listener in general, it will load the spring configuration file/web-inf/applicationcontext.xml by default.

If we want to specify the name of the spring configuration file or load multiple spring XML configuration files, we need to configure this:

<?xml version= "1.0" encoding= "UTF-8"? ><web-app ...>...<!--Spring Listener-  <listener>  <listener-class>  Org.springframework.web.context.ContextLoaderListener  </listener-class >  </listener>  <!--Specifies that the listener loads the specified spring XML configuration file--  <context-param>  < Param-name>contextconfiglocation</param-name>  <!--are data source, service layer, persistence layer, security---  < param-value>  classpath:conf/datasource-context.xml  classpath:conf/service-context.xml  Classpath:conf/persistence-context.xml  /web-inf/wwo-security.xml  </param-value>  </ Context-param>...</web-app>


OK, so the XML configuration file of Spring is very clear!

However, the problem here is that all requests go through this listener, including requests for static resources, and here's the problem. What if it's a static resource?

shows that we are also dealing with so-called static resources, and spring provides us with a <mvc:resources> element that can handle this problem , the Service-context.xml file is configured 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:mvc= "Http://www.springframework.org/schema/mvc" xsi: schemalocation= "Http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/ Spring-mvc.xsdhttp://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsd "><!--handling of static resources--><mvc:resources location="/jscript/** "mapping="/jscript/"/> </beans>

This allows the URL to contain/jscript/requests, which correspond to the resources located under/jscript/for special processing!

Note: For Dispatcherservlet and contextloaderlistener explanations see: http://blog.csdn.net/u013474104/article/details/44086811

4. Configuring note-driven spring MVC

Well, don't say much! Now spring has mostly been able to use annotations instead of what we used to do in the config file, and most of the time we'll do it using annotations.

A. Defining the Controller

Dispatcherservlet needs to consult with one or more processors to explicitly distribute the request to that controller. Spring provides a number of processor mapping implementations, which we only need to defaultannotationhandlermapping to implement.

defaultannotationhandlermapping: Maps the request to the Controller and controller methods using the @requestmapping annotation.

To begin with, you must load the annotated classes and methods into the context application, the spring container, before you can use them!

We need to add the following configuration to the configuration file to implement the annotation feature:

<beans>...<!--scanning <span style= "font-family:arial, Helvetica, Sans-serif;" > </span><span style= "font-family:arial, Helvetica, Sans-serif under the specified package." > Annotations--></span><context:component-scan base-package= "Com.blog" ><!--Configuring the component filter--><!-- Specifies that the scanned package--><context:include-filter type= "annotation" expression= "Com.blog.controller"/><!--Specify a package that does not need to be scanned-- ><context:exclude-filter type= "Annotation" expression= "Com.blog.dao"/></context:component-scan> ...</beans>

Note: The above is for illustrative purposes only

The following configuration is basic enough, if not specifically required:

<beans>...<!--Scan annotations under the specified package--><context:component-scan base-package= "Com.blog"/>...</beans>
Description

By default,,<context:component-scan> finds classes that are annotated with stereotype annotations, which are the following special annotations:

@Component-a generic stereotype annotation that identifies the class as a spring component;

@Controller-Identifies that the class is defined as a spring MVC Controller;

@Repository-Identifies the class as a data warehouse;

@Service-Identifies the class as a service;

Any custom annotations that use @component annotations.

Generally to distinguish between a class belonging to the control, database access and business layer, will use the corresponding annotation @Controller,@Repository and @Service, and minimize the use of @Component,@ The component is universal!

Next we can declare a controller that logs on to the main page (or home page):

Switch the spring MVC to the 3.x version of the jar before using more than 4.x.

This is because 4.x annotations may be somewhat different from 3.x, and this example focuses on the development of the 3.x version.

Toggle Configuration:

<project>...<!--define properties for ${propertiename} access  <properties>  < Project.build.sourceencoding>utf-8</project.build.sourceencoding>  <spring.version>3.2.13. Release</spring.version>  </properties>...</project>

B. Render View

--After the above controller to call the corresponding business layer, and then to the results of processing to inform the user, we need to render the view, so that the client can be displayed!

The code configured in the Wwo-servlet.xml file is as follows:

<!--principle: The logical view name determines the view path resolution view by adding a prefix suffix, because the JSP view uses the JSTL tag. So you need to replace Internalresourceviewresolver with Jstlview--><bean class= "by setting Viewclass to belong to" Org.springframework.web.servlet.view.InternalResourceViewResolver "><property name=" Viewclass "value=" Org.springframework.web.servlet.view.JstlView "/><property name=" prefix "value="/"/><property name=" Suffix "value=". JSP "/></bean>
The above is the configuration method of my usual rendering view, but what we are going to say is to render it through the Apache Tiles layout manager!

Apache Tiles: For a generic Web application, the Internalresourceviewresolver view is basically enough. However, for some complex web applications, the Apache tiles layout manager should be used, and the advantage is that it allows some common elements (or pages) to be shared by the page to reuse elements.

Official website: http://tiles.apache.org/

The code configured in the Wwo-servlet.xml file is as follows:

<!--Apache Tiles instead of Jstlview if you want some common elements to be shared by the page, you can use the Apache Tiles layout manager. Parse the layout view of tiles with spring MVC configuration! Establish the View resolver: tilesviewresolver; load tiles definition: tilesconfigurer; tiles defined by tilesconfigurer load and use Tilesviewresolver to parse the view. Views.xml is the tiles definition file, they are all scattered in the/web-inf/views/directory;/web-inf/views/**/views.xml:**, find/web-inf/views/ Directory so views.xml file--<bean class= "Org.springframework.web.servlet.view.tiles2.TilesViewResolver"/> < Bean class= "Org.springframework.web.servlet.view.tiles2.TilesConfigurer" > <property name= "Definitions" > <list> <value>/WEB-INF/main-tiles/main-tiles.xml</value> </list> </property> </ Bean>

Let's take a look at the configuration of the/web-inf/main-tiles/main-titles.xml file:

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE tiles-definitions Public "-//apache software foundation//dtd tiles Configuration 2.1//en" "/http Tiles.apache.org/dtds/tiles-config_2_1.dtd "><tiles-definitions><!--define a common layout--><definition name = "template" template= "/blog/main/main_template.jsp" ><put-attribute name= "Top" value= "/blog/main/title.jsp"/ ></definition><!--Define Main's tiles--><definition name= "main" extends= "template" >< Put-attribute name= "Content" value= "/blog/main/main.jsp"/></definition></tiles-definitions>

Note: Here the definition Label property name is the corresponding control layer, return the logical view name.

Again, look at how to configure the use in main_template.jsp, to achieve the purpose of reuse.

In other words,main_template.jsp can be made up of several. JSP pages!

main_template.jsp file:

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "    pageencoding=" UTF-8 "%><%@ taglib prefix=" T "uri=" http://tiles.apache.org/tags-tiles "% ><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
Well, we can see that we want to use the Tags-tiles tag Library to achieve the goal!

Effect:

main_template.jsp the page displayed:



title.jsp the page displayed:


main.jsp the page displayed:


Okay, here's the Spring MVC architecture!


Build a Web application framework with spring MVC-complete case

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.