Build a WEB application framework using Spring MVC-complete case study, springmvc
Reprinted please indicate the source: http://blog.csdn.net/u013474104/article/details/43707459
================
1. Introduction
First, Spring MVC is developed based on three layers. What about the three layers?
M (model)-model layerAfter the Controller completes logical processing, it usually generates some information, which needs to be returned to the user and displayed on the browser. We call this information a model;
V (view)-view layer, We use JSP as the view layer, through which the model data can be rendered and output, and passed to the client through the output response;
C (controller)-control layerFrom the time the user submits the request, these requests will be directed to a specific controller through a front-end controller Servlet, Which is parsed by the front-end controller Servlet.
Relationship between the three layers:The user submits a request, parses it by the front-end controller Servlet, and then specifies the controller. After the controller processes the logic information, it returns the model data and then renders and outputs the model data through the specified view, finally presented to the client, that is, the user.
2. Introduce the spring mvc jar package
Because my previous article introduced the use of Maven (the project was built using Maven), we will use Maven dependencies here to download spring jar packages.
If you do not know how to configure the dependency, enter the URL: http://mvnrepository.com/, Here provide jar package dependency query and so on.
First, search for required,
There are a lot of related lists below. Find what we need or you can enter the name to search faster
Click in and select the version
Click in and copy the dependency to your pom. xml file.
Pom. xml configuration:
<Project>... <! -- Define attributes for $ {propertieName} access --> <properties> <project. build. sourceEncoding> UTF-8 </project. build. sourceEncoding> <spring. version> 4.1.3.RELEASE </spring. version> </properties> <! -- Dependency Association --> <dependencies> <dependency> <groupId> org. springframework </groupId> <artifactId> spring-webmvc </artifactId> <version >$ {spring. version }</version> </dependency> </dependencies>... </project>
Execute pom. xml update
Check that all associated jar files are downloaded to the local repository. This is the benefit of using Maven!
3. configure a front-end controller Servlet
In Spring MVC, all requests must go through a front-end controller Servlet, namely DispatcherServlet, which is the core of Spring MVC.
The DispatcherServlet must be configured in the Web. xml file of the web application. The configuration is as follows:
<? Xml version = "1.0" encoding = "UTF-8"?> <Web-app...>... <! -- Spring mvc front-end Controller --> <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 to load the configuration to the Spring application context based on an XML file. The xml file name is specified by default through <servlet-name>, that is, our common $ {<servlet-name>}-servlet. xml, as in the preceding example, the xml file is named: wwo-servlet.xml (the default path is located under the WEB-INF directory of the application ). Generally, our spring configuration file can be divided into multiple XML files, one for the service layer, one for the persistence layer, and the other for the data source configuration. What should we do?
Spring provides me with a ContextLoaderListener, which is a Servlet listener. We only need to configure the ContextLoaderListener in the web. xml file. The configuration is as follows:
<? Xml version = "1.0" encoding = "UTF-8"?> <Web-app...>... <! -- Spring listener --> <listener-class> org. springframework. web. context. contextLoaderListener </listener-class> </listener>... </web-app>
However, if you configure the listener like this, it loads 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 it as follows:
<? Xml version = "1.0" encoding = "UTF-8"?> <Web-app...>... <! -- Spring listener --> <listener-class> org. springframework. web. context. ContextLoaderListener </listener-class> </listener> <! -- Specify the listener to load the specified spring xml configuration file --> <context-param> <param-name> contextConfigLocation </param-name> <! -- Corresponding to the data source, service layer, persistent 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>
Well, the xml configuration file of spring will be clearly identified!
However, the problem is that all requests pass through the listener, including requests for static resources. What if it is a static resource?
Show that we also need to deal with the so-called static resources, spring provides us with the <mvc: resources> element can handle this problem, the service-context.xml file configuration 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: 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"> <! -- Processing static resources --> <mvc: resources location = "/JScript/**" mapping = "/JScript/"/> </beans>
In this way, the request for URL containing/JScript/is specially processed for resources located under/JScript!
Note: For DispatcherServlet and ContextLoaderListener explanations, see: http://blog.csdn.net/u013474104/article/details/44086811
4. Configure annotation-driven Spring MVC
Okay, not much to mention! Currently, most of spring can use annotations to replace the previous tasks in the configuration file. Next, most of them will be done using annotations.
A. Define the Controller
DispatcherServlet needs to consult one or more processors to explicitly distribute requests to that controller. Spring provides many processor ing implementations, so we only need DefaultAnnotationHandlerMapping.
DefaultAnnotationHandlerMapping: Map requests to the Controller and controller methods using the @ requestMapping annotation.
First, you must load annotation classes and methods into the context application, that is, the spring container!
Add the following configuration in the configuration file to implement the annotation function:
<Beans>... <! -- Scan <span style = "font-family: Arial, Helvetica, sans-serif;"> </span> <span style = "font-family: Arial, helvetica, sans-serif; "> annotation --> </span> <context: component-scan base-package =" com. blog "> <! -- Configure the component filter --> <! -- Specify the scanned package --> <context: include-filter type = "annotation" expression = "com. blog. controller"/> <! -- Specify the 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 just for Example
The following configurations are sufficient, if not required:
<Beans>... <! -- Scan the annotation under the specified package --> <context: component-scan base-package = "com. blog"/>... </beans>
Note:
By default, <context: component-scan> finds the classes marked with constructor annotations. These special annotations are as follows:
@ Component -- generic constructor annotation that identifies this class as a Spring Component;
@ Controller -- Define the class as Spring MVC controller;
@ Repository -- identifies the class as a data warehouse;
@ Service -- identifies the class as a Service;
Any custom annotation marked with @ component.
Generally, it is better to distinguish a class from the control, database access, and business layers. The corresponding annotations @ Controller, @ Repository, and @ Service are used respectively, while @ Component and @ Component are used as few as possible!
Next, we can declare a controller logging on to the home page (or home page:
Switch spring mvc to the jar of version 3.x, which is later than 4.x.
This is because the annotations of 4.x may be slightly different from those of 3.x. This example focuses on the development of 3.x.
Switch configuration:
<Project>... <! -- Define attributes for $ {propertieName} access --> <properties> <project. build. sourceEncoding> UTF-8 </project. build. sourceEncoding> <spring. version> 3.2.13.RELEASE </spring. version> </properties>... </project>
B. Rendering View
-- After calling the corresponding service layer through the above controller, We need to render the view to display it on the client when we want to inform the user of the processing result!
The configuration code in the wwo-servlet.xml file is as follows:
<! -- Principle: the logical view name uses the jstl label to add the prefix and suffix to determine the view path resolution view, therefore, you must set viewClass to replace InternalResourceViewResolver with JstlView --> <bean class = "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 my commonly used rendering view configuration method, but next we will talk about rendering through Apache Tiles layout manager!
Apache Tiles: for general web applications, the InternalResourceViewResolver view is basically enough. However, for some complex web applications, you should use the Apache Tiles layout manager. The advantage is that it can share some common elements (or pages) by pages, in this way, elements can be reused.
Official Website: http://tiles.apache.org/
The configuration code in the wwo-servlet.xml file is as follows:
<! -- Apache Tiles replaces JstlView. If you want some common elements to be shared by pages, you can use the Apache Tiles layout manager. Parse the Layout View of Tiles through Spring MVC configuration! Create a view Parser: TilesViewResolver; load the definition of Tiles: TilesConfigurer; load the tiles definition by TilesConfigurer, and use TilesViewResolver to parse the view. Views. xml is the definition file for tiles, all of which are scattered under the/WEB-INF/views/directory;/WEB-INF/views/**/views. xml: **, search for/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/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 general layout --> <definition name = "template" template = "/blog/main/main_template.jsp"> <put-attribute name = "top" value = "/blog/ main/title. jsp "/> </definition> <! -- Define tiles of main --> <definition name = "main" extends = "template"> <put-attribute name = "content" value = "/blog/main. jsp "/> </definition> </tiles-definitions>
Note: The attribute name of the definition label corresponds to the logic view name returned by return at the control layer.
Next, let's look at how to configure and use main_template.jsp to achieve the purpose of reuse.
That is to say, main_template.jsp can be composed 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">Now, we can see that you want to use the tags-tiles tag library for your purpose!
Effect:
Main_template.jsp:
Title. jsp page:
Main. jsp display page:
Now, the Spring MVC Architecture is complete!