Introduction to Spring MVC Tutorial

Source: Internet
Author: User
Tags http redirect spring mvc tutorial
Basically a compact version of the SPRINGMVC reference, very simple, because most of the web framework concept is universal.
This article is more concerned about the conceptual issues in Springmvc, as for the details, not in this study notes.

This document is based on Spring2.5.2

Overview
Spring's web framework is designed around Dispatcherservlet. The role of Dispatcherservlet is to distribute requests to different processors. The Spring web framework includes configurable processor (handler) mappings, view resolution, localization (local) resolution, theme (theme) parsing, and support for file uploads. The default processor in spring's web framework is the Controller interface, a very simple interface that contains only the Modelandview handlerequest (request, Response) method. You can create your own controller (also known as a processor) by implementing this interface, but it is more recommended that you inherit the series of controllers that spring provides, such as Abstractcontroller, Abstractcommandcontroller and Simpleformcontroller.

features of the Spring Web MVC framework

Clear Role Partitioning: Controllers (Controller), validators (Validator), command objects (Commands object), Form objects (Form object), model objects (models object), Servlet distributor (Dispatcherservlet), processor mappings (handler mapping), view parser (views resolver), and so on. Each role can be implemented by a dedicated object.

Powerful and straightforward configuration: Both framework classes and application classes can be configured as JavaBean, supporting references across multiple context, such as references to business objects and validators (validator) in Web controllers.

Adaptable, non-intrusive: You can choose the appropriate controller subclasses (simple, command, form, Wizard, Multi-Action, or custom) based on different scenarios, rather than from a single control such as action/ Actionform) inheritance.

Reusable business code: You can use an existing business object as a command or Form object without having to extend the base class for a particular frame.

Customizable bindings (binding) and Validation (validation): For example, a type mismatch is used as an application-level validation error, which can save the wrong value. such as localized date and number bindings, and so on.

Customizable handler mapping and view resolution:spring provide from the simplest URL mappings to complex, proprietary customization strategies.

Flexible model transformation: In the Springweb framework, a map based key/value pair is used to achieve easy integration with various view technologies.

Customizable localization and theme (theme) Resolution: Supports the option of using the Spring tag library in JSP, supports JSTL, supports velocity (no extra middle tier), and so on.

Simple and powerful JSP tag library: supports many features including data binding and themes (theme). It provides maximum flexibility in labeling.

JSP Form Tag library: A Form tag library introduced in Spring2.0 that makes it easier to write forms in a JSP.

The life cycle of the Spring bean can be limited to the current HTTP request or HTTP session. To be precise, this is not the nature of the spring MVC framework itself, but should be attributed to the Webapplicationcontext container used by sping MVC.

This diagram is a common MVC diagram, and basically the main web framework is doing so.



Controller

The concept of a controller is part of the MVC design pattern (specifically, C in MVC). The behavior of an application is often defined as a service interface, and the controller allows the user to access the services provided by the application. The controller resolves user input and converts it into a reasonable model data, which can be further displayed to the user by the view. Spring implements the controller concept in an abstract way that can support different types of controllers.

Controller or recommend a request a controller way, except for the wizard type.

To provide a set of infrastructure, all spring controllers inherit Abstractcontroller, Abstractcontroller provides functionality such as caching support and mimetype settings.

Spring provides multiactioncontroller to combine multiple request processing methods into a single controller so that the related functions can be grouped together.

Spring's command controllers is an important part of spring MVC. Command controllers provide a way to interact with data objects and dynamically bind parameters from HttpServletRequest to the specified data object.

Processor Mappings

The basic function of handlermapping is to pass the request to the Handlerexecutionchain. First, this handlerexecutionchain must contain a processor capable of processing the request. Second, the chain can also contain a series of interceptors that can intercept the request. When the request is received, dispatcherservlet the request to the processor map, allowing it to check the request and find an appropriate handlerexecutionchain. Dispatcherservlet then executes the processors and interceptors defined in the chain (Interceptor).

It is more powerful in processor mappings by configuring interceptors, including before the processor executes, after execution, or before and after the execution of the Interceptor. You can also support more features by customizing the handlermapping. For example, a custom processor map can be selected not only according to the URL of the request, but also by selecting the processor based on the specific session state associated with the request.

Intercepting Device
Spring's processor mappings support interceptors. This is useful when you want to provide special functionality for certain requests, such as authenticating a user.
Log, test performance, do authorization and certification depends on it.

The interceptor in the processor map must implement the Handlerinterceptor interface in the Org.springframework.web.servlet package. This interface defines three methods, one to be invoked before the processor executes, one to be invoked after the processor executes, and another to be invoked after the entire request has been processed. These three methods provide you with enough flexibility to do any processing before and after the operation.

view and view resolution
Viewresolver and view are the two interfaces that are particularly important in spring's view processing. Viewresolver provides a mapping from the view name to the actual view. View handles the preparation of the request and submits the request to a specific view technique.

View parsing chain
Spring supports the use of multiple view parsers. You can think of them as an analytic chain. This has many benefits, such as redefining some views in certain situations. Defining a view parsing chain is easy, as long as you define multiple parsers in the context of the application. If necessary, the sequence of each parser can also be declared with the order attribute.

If a parser doesn't find a suitable view, spring will look in the context to see if the other parser is configured. If there is, it will continue to parse, otherwise, srping will throw a exception.

Remember that when a view parser cannot find a suitable view, it may return a null value. However, not every parser does this. This is because, in some cases, the parser may not be able to detect the existence of a view that meets the requirements. Internalresourceviewresolver, for example, calls the RequestDispatcher internally. Request distribution is the only way to check if a JSP file exists, unfortunately, this method can only be used once. The same problem also applies to velocityviewresolver and other parsers. When using these parsers, it is a good idea to read their Javadoc carefully to see if the parser you need cannot discover a view that does not exist. The side effect of this problem is that if the Internalresourceviewresolver parser is not placed at the end of the chain, those parsers behind the internalresourceviewresolver are not used at all. Because Internalresourceviewresolver always returns a view.

REDIRECT (Rediret) to another view
One way to force redirection in a controller is to have the controller create and return an instance of spring's redirectview. In this case, Dispatcherservlet does not use the usual view resolution mechanism, and now that it has got a (redirected) view, it lets the view do the rest of the work.

Although using Redirectview helps us achieve the goal, if the controller generates Redirectview, the controller will inevitably know that the result of a request is to redirect the user to another page. This is not the best implementation because it makes the system too tightly coupled between the different modules. In fact, the controller should not ask how the return result is generated, and usually it should only care about the name of the view injected to it.

The solution to this problem is to rely on the redirect: prefix. If the returned view name contains the redirect: prefix, Urlbasedviewresolver (and its subclasses) will know that the system is generating an HTTP redirect. The rest of the view name is treated as a redirected URL.

Instant is web programming also need to consider loose coupling problem.

Localization Parser

Most of the spring architecture supports internationalization, and the Spring Web MVC framework is no exception. Dispatcherservlet allows automatic parsing of messages using client localization information. This work is done by the Localeresolver object.

When the request is received, Dispatcherservlet locates a localization parser and, if found, uses it to set localized information. With the Requestcontext.getlocale () method, you can always get localized information for clients that are resolved by the localization parser.

Working with Themes
The Sping Web MVC framework allows you to control the style of a Web page through Themes (theme), which will further improve the user experience. In simple terms, a topic is a set of static resources (such as stylesheets and pictures) that can affect the visual effects of an application.
This thing is very good, do not know if anyone used it.

Spring support for staging file uploads (multipart file upload)

Spring's Form Tag library

Handling Exceptions

Unexpected exceptions can occur when a request is processed by a controller that matches the request.

Customary Priority Principles
For many projects, strict adherence to existing practices and the use of reasonable default options are probably needed for these projects ... Now spring WEB MVC explicitly supports the thrust of this practice-first principle. This means that if you create a set of naming conventions, and so on, you can significantly reduce the number of items that your system needs to configure to establish processor mappings, view parsers, Modelandview instances, and so on. This provides a great convenience for rapid prototyping development. It also provides a degree of (usually good) consistency in the code base, which can then be selected and developed into a molded product.

Note-based controller configuration
Define a controller using @controller
Using the @requestmapping mapping request
Using @requestparam Binding request parameters to method parameters
Use @modelattribute to provide a link from the model to the data
Use @sessionattributes to specify properties stored in a session

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.