Spring-spring mvc Framework

Source: Internet
Author: User

Spring mvc is at the core of Spring FEATURES. It lists Spring FEATURES on the official website. This corresponds to "modern web" (MODERN web ), that is, the first item of Spring features. It also reflects its important role. On the other hand, it is also because mvc was born earlier in the Spring Project.

As long as it is related to network applications, spring mvc is a mature and fully functional architecture, regardless of whether there is interaction with users (with UI) or no interaction. To read the following content, you must have a basic understanding of java, spring (dependency injection), and servlet.

Shows the MVC Framework of Spring:

 

In Spring MVC, the front-end controller is the DispatcherServlet Servlet, which takes charge of the user's request and the final system response. This DispatcherServlet does not touch the specific business logic at all, but delegates all the tasks to the Controller for doing (Controller ), of course, DispatcherServlet knows that the current task should be handed over to the Controller, which will be explained later. Then, when the Controller finishes all the tasks, it is the turn of View to play, A simple understanding is like a PPT. The view here is like a template in the PPT. It can deliver data to the customer in different forms, such as jsp, xml, and json. Let's take a look at how to implement it:

1. Servlet part. As mentioned above, the front-end controller is the Servlet DispatcherServlet, which is obviously required on the web. add a servlet to xml, and then let DispatcherServlet process all user requests. below is the web. xml file:

[Html]
<? Xml version = "1.0" encoding = "UTF-8"?>
<Web-app version = "2.5" xmlns = "http://java.sun.com/xml/ns/javaee"
Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
Xsi: schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<! -- Processes application requests -->
<Servlet>
<Servlet-name> appServlet </servlet-name>
<Servlet-class> org. springframework. web. servlet. DispatcherServlet </servlet-class>
<Init-param>
<Param-name> contextConfigLocation </param-name>
<Param-value>/WEB-INF/spring/appServlet/servlet-context.xml </param-value>
</Init-param>
<Load-on-startup> 1 </load-on-startup>
</Servlet>

<Servlet-mapping>
<Servlet-name> appServlet </servlet-name>
<Url-pattern>/</url-pattern>
</Servlet-mapping>
</Web-app>
Here, contextConfigLocation is used as an initialization parameter (init-param). You can set its value during servlet initialization, this value defines the spring application context (context-context, refers to an environment, mainly a variety of beans, can be understood as a variety of component configuration files (XML format) the context will be loaded by the DispatcherServlet, so that the Dispatcher will allocate tasks according to the content of the context when working. For details, refer to the figure below:

For context configuration, here is the xml configuration method, the above Code specifies the configuration file is/WEB-INF/spring/appServlet/servlet-context.xml, this can also use the java configuration method, here, you need to add AnnotationConfigWebApplicationContext to the initial parameter of DispatcherServlet. In the following example, we can see that components can be configured in XML, but java code can also be used. Next let's take a look at the first controller

2. Controller class. The following is the most mini control class:

[Html]
Package xyz. sample. baremvc;

Import org. springframework. stereotype. Controller;
Import org. springframework. web. bind. annotation. RequestMapping;

/**
* Handles requests for the application home page.
*/
@ Controller
Public class HomeController {

@ RequestMapping (value = "/")
Public String home (){
System. out. println ("HomeController: Passing through ...");
Return "WEB-INF/views/home. jsp ";
}
}
The above class has several notes:
1. The annotation @ Controller (which can be translated into "Comments" to indicate the role of the following classes) is used to indicate that the HomeController class is used as the Controller in Spring MVC ), according to the figure above, this class has the ability to process user requests. In addition, @ Controller is the specific annotation in the annotation of @ Component (a bit similar to @ Component is the parent class of @ Controller, @ Component is equivalent to a relatively high degree of abstraction, @ Controller is a specific @ Component), so HomeController is also used as a Component ), during Spring initialization scanning, it will be automatically detected and added to Spring container (Spring containers or Spring context are similar), and then generate corresponding class instances, finally, it is allowed to be injected into the system like any other Spring component.

2. The home method uses the annotation @ RequestMapping, indicating that the home method can be used to process user requests corresponding to the path "/" (root path ).

3. Here, the processing of home is to print a string in the log, and then return the WEB-INF/views/home. jsp, Which is handed to View for processing. Here is a jsp file. By default, if we do not set a specific View, spring uses the default View to process WEB-INF/views/home. jsp Response (Response); the corresponding View will be detailed later, here as long as you know that the View will put the system home. the jsp file is displayed to the customer.

The following is the corresponding home. jsp file. The file is very simple, just a Hello:

[Html]
<% @ Taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<% @ Page session = "false" %>
<Html>
<Head>
<Title> Home </title>
</Head>
<Body>
<H1> Hello world! </H1>
</Body>
</Html>
3. Configure the Spring context, the Spring context mentioned above in Servlet has not been created (/WEB-INF/spring/appServlet/servlet-context.xml), look at the following code:
[Html]
<? 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"
Xmlns: context = "http://www.springframework.org/schema/context"
Xsi: schemaLocation ="
Http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd ">

<! -- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

<! -- Scans within the base package of the application for @ Components to configure as beans -->
<! -- @ Controller, @ Service, @ Configuration, etc. -->
<Context: component-scan base-package = "xyz. sample. baremvc"/>

<! -- Enables the Spring MVC @ Controller programming model -->
<Mvc: annotation-driven/>

</Beans>
1. The root element of xml here is <beans>, so it mainly involves creating various beans. The bean here is actually component ).
2. There are three namespaces, the first is the default beans, and then the mvc and context.

3. <context: component-scan/> indicates that the Spring container is required to scan and check the class, in this way, all codes that contain comments of the @ Component subtype (for example, the @ Controller above is the subtype of @ Component) will be checked, and in order to improve efficiency, here the range of automatic check is only in xyz .. sample. run the following command under the baremvc package.

4. <mvc: annotation-driven/> indicates that annotation can be used for work, that is, Spring MVC is supported to forward requests to @ Controller for processing; of course, it can also involve conversion, formatting, and validity.

After completing the preceding steps, start the server and enter http: // localhost: 8080/baremvc in the address bar to see the following results:

 

The above example is very simple, but involves the key part of the Spring MVC application. Let's take a look at the call process of this application:

A. When Tomcat is started, our Spring MVC application is started, and DispatcherServlet is loaded in, because we have set this Servlet in Web. xml.

B. DispatcherServlet loads the Spring application context based on annotation (annotation). Here we use regular expressions for the specified package (the specified package can use regular expressions) to obtain the annotated components.

C. These annotated components are detected by Spring container.

D. the http request of HTTP: // localhost: 8080/baremvc matches the servlet-mapping in our DispatcherServlet, so DispatcherServlet will process this HTTP Request

E. The above HTTP request implies that the user's request path is "/". then DispatcherServlet finds that there is a ing in the corresponding path request (this is actually the Handler Mapping in our second example)

F. Dispatcher decides how to process the request. The policy it uses is HandlerAdapter. This can be understood as follows. For a request, a corresponding handler must be provided (solution) the handler may use different types of handler based on the current situation, therefore, a HandlerAdapter is needed to convert different types of handler to process requests in different situations. We can specify the HandlerAdapter (or multiple HandlerAdapter, which can be linked together). If the HandlerAdapter is not specified, the system's default HandlerAdapter will be used, here is the annotation-based policy. Here, the request is forwarded to @ Controller, and then the @ RequestMapping method matching the corresponding path is found. The input parameter is assigned to the method and the method is used to process the request. The example of using other HandlerAdapter hasn't been done yet, but we don't care about it for the time being, as long as we know it, it's okay.

G. Then, the home method is used to print a log and return a string. This string implies what is to be presented to the user and helps the View to select an appropriate rendering mode.

H. Then we know from the first figure that after the Controller finishes the task, the task is handed over to DispatcherServlet. For how to select the proper view, DispatcherServlet needs a policy. This policy is called ViewResolver, through this ViewResolver (View arbitrator), the View will be arbitrated and the response will be presented to the user. This ViewResolver can also be defined by itself. If no configuration is available by default, the system will use InternalResourceViewResolver. This ViewResolver will create a JSTLView, which simply delegates the task to the RequestDispatcher inside the Servlet to present the resource, therefore, this View is suitable for JSP or HTML pages.

I. The Servlet finally presents the response to the user through the developed jsp

4. Abstract The View and let the Controller return a purely logical name.

In the above home function, we can see that the returned address is a pure physical address. In order to reduce coupling and make the application more flexible, of course, this hard encoding method cannot be used; the Controller should return a logical name, and the final physical path is determined by the View. In this way, the Controller only cares about the logical processing and leaves the display to the View, truly separates C from V. See the transformed Controller:

[Java]
@ Controller
Public class HomeController {

@ RequestMapping (value = "/")
Public String home (){
System. out. println ("HomeController: Passing through ...");
Return "home ";
}
}
The above home function returns a logic name "home", which indicates that the system needs to call a view called "home" to the user, however, the system determines what the "home" view looks like. Of course, we know that ViewResolver is used here. Of course, we can unify the names of these views. The above direct "home" is still a bit "stiff".
Next we need to map the "home" name to the "WEB-INF/views/home. jsp" file. As mentioned above, by default, this ing is handled through the InternalResourceViewResolver class. We can use our own ViewResolver to process the ing from this logic to the physical. However, in this example, we only need to make a slight adjustment to InternalResourceViewResolver to achieve our goal.
InternalResourceViewResolver returns the name of the Controller (in fact, it is sent by DispatcherServlet), but adds an optional prefix suffix before and after it (it is null by default ), then, the string is handed over to the JSTLView created by the Servlet engine, and then the JSTLView entrusts the RequestDispatcher In the Servlet engine to perform real work and present the view template. Here is the jsp view template. This example is relatively simple, as long as the View name returns to add the corresponding prefix suffix, prefix "WEB-INF/views/", suffix ". jsp ". One simple way to configure ViewResolver is to use java-based container configuration (In addition, XML-based container configuration/context configuration ), define our Resolver as a Bean. The corresponding code is as follows:

[Java]
Package xyz. sample. baremvc;

Import org. springframework. context. annotation. Bean;
Import org. springframework. context. annotation. Configuration;
Import org. springframework. web. servlet. ViewResolver;
Import org. springframework. web. servlet. view. InternalResourceViewResolver;

@ Configuration
Public class AppConfig {

// Resolve logical view names to. jsp resources in the/WEB-INF/views directory
@ Bean
ViewResolver viewResolver (){
InternalResourceViewResolver resolver = new InternalResourceViewResolver ();
Resolver. setPrefix ("WEB-INF/views /");
Resolver. setSuffix (". jsp ");
Return resolver;
}
}
The above Code requires the support of the cglib library. You can download the code online or go to my resources to download cglib.
Because @ Configuration is also a @ Component, it will also be scanned during scanning, and the Configuration Component will be added to the Spring container, the Spring container also scans all beans and finds ViewResolver (that is, a resolver created by the viewResolver function is added to our container as a Bean ), then, the ViewResolver is used to process the logical View name.

The above uses the java method. Some people prefer the xml method, as shown below:

[Html]
<! -- Resolve logical view names to. jsp resources in the/WEB-INF/views directory -->
<Bean class = "org. springframework. web. servlet. view. InternalResourceViewResolver">
<Property name = "prefix" value = "/WEB-INF/views/"/>
<Property name = "suffix" value = ". jsp"/>
</Bean>
This effect is the same as creating an InternalResourceViewResolver bean and setting its bean attributes to process the View name.
5. process user input

We always need to interact with users. Let's see how to handle some simple user input and then output the results to users. There are multiple input and output methods in Spring MVC. Let's look at the simplest one. Here, we add a request processing method in the above HomeController so that it can obtain the characters entered by two users, then compare them, and output the results to users through jsp, look at the added method:

[Java]
Package xyz. sample. baremvc;

Import java. util. Comparator;

Import org. springframework. beans. factory. annotation. Autowired;
Import org. springframework. stereotype. Controller;
Import org. springframework. ui. Model;
Import org. springframework. web. bind. annotation. RequestMapping;
Import org. springframework. web. bind. annotation. RequestMethod;
Import org. springframework. web. bind. annotation. RequestParam;

/**
* Handles requests for the application home page.
*/
@ Controller
Public class HomeController {

@ Autowired
Comparator <String> comparator;

@ RequestMapping (value = "/")
Public String home (){
System. out. println ("HomeController: Passing through ...");
Return "home ";
}

@ RequestMapping (value = "/compare", method = RequestMethod. GET)
Public String compare (@ RequestParam ("input1") String input1,
@ RequestParam ("input2") String input2, Model model ){

Int result = comparator. compare (input1, input2 );
String inEnglish = (result <0 )? "Less than": (result> 0? "Greater than": "equal ");

String output = "According to our Comparator, '" + input1 + "'is" + inEnglish + "'" + input2 + "'";

Model. addAttribute ("output", output );
Return "compareResult ";
}
}
1. added a compare function. This function is used to process user requests when the user requests the path "/compare ".
2. This function requires the user to pass in two characters as its parameter through the GET request. If the user does not pass two strings with the specified name (input1 and input2, an HTTP 400 error will be prompted. Here, the compare function obtains the parameter in the user GET request through the annotation @ RequestParam.

3. We use our own comparator to compare the two strings. Note that @ Autowired, Spring finds components of the same type as comparator (Comparator <String>) in the container, and then wired (connection) to comparator (it can be understood as calling setComparator)

4. Finally, we use the Model to place the comparison results, so that the View can get the results in the Model. Here we only need to regard the Model as a HashMap, name> data. The data placed in the Model is mainly used to allow the View to access the useful data. In the above example, it is only a string and will be presented to jsp in the future.

We create a corresponding jsp file to display the results, WEB-INF/views/compareResult. jsp:

[Html]
<% @ Taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<% @ Page session = "false" %>
<Html>
<Head>
<Title> Result </title>
</Head>
<Body>
<H1> <c: out value = "$ {output}"> </c: out>
</Body>
</Html>
Now we also need to create a component injected to the comparator in the Controller. The code for this component is as follows:
[Java]
Package xyz. sample. baremvc;

Import java. util. Comparator;
Import org. springframework. stereotype. Component;

@ Service
Public class CaseInsensitiveComparator implements Comparator <String> {
Public int compare (String s1, String s2 ){
Assert s1! = Null & s2! = Null;
Return String. CASE_INSENSITIVE_ORDER.compare (s1, s2 );
}
}
This Comparator is a simple comparator that implements the Comparator <String> interface, so that it can be injected into the Controller comparator. Because @ Service is also a type of @ Component, it can also be automatically scanned. Of course, We also noticed that some people have to ask whether this can be done through the @ Bean definition in @ Configuration above. Of course, the answer is yes, and it can also be defined in XML. Different definitions make the control layers provided by these classes different. This should be referred to the corresponding annotation.

 
Finally, if you want to learn more about the features of Spring MVC, you can refer to this show 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.