How does SpringMVC gradually simplify Servlet programming? springmvcservlet
How does Spring MVC gradually simplify Servlet programming?
Servlet and JSP are two basic technologies used to develop java Web applications. Spring MVC is a module used for Web application development in the Spring framework, being able to clearly understand the process of gradually simplifying Servlet-to-Spring MVC development technology is of great help to deeply understand the role of Spring MVC in Web application development. We will introduce the simplified process from the directory structure of the project:
1. In Servlet
Under the application directory is the WEB-INF Directory, which contains the classes subdirectory, Servlet class and other Java classes must be placed below this, in the most basic Servlet class, the init (), service (), destroy (), getServletConfig (), and getServletInfo () methods defined by the Servlet interface must be implemented. The most basic logic is put in service () method. The most common method in servic () is to output content through PrintWriter.
Evolution 1: All methods must be implemented when the Servlet interface is implemented, even if some methods do not contain any code at all. However, the GenericServlet abstract class implements the Servlet and ServletConfig interfaces to simplify the task. |
Therefore, with the help of the GenericServlet abstract class, we only need to rewrite the service method to implement our task.
Evolution 2: however, GenericServlet is not commonly used, because HttpServlet is the main character and does not need to overwrite the service () method but doGet () and doPost () to write logic. |
HttpServlet overwrites the GenericServlet class, which converts ServletRequest and ServletRespond objects into HttpServletRequest and HttpServletRespond objects respectively, and calls the most common doGet () (presented from the server to the client) and doPost () (obtained from the client to the server for processing) and other seven methods without the need to override the service method.
Using the deployment descriptor is a way to configure the Servlet application, the deployment descriptor is named web. xml and placed under the WEB-INF directory.
Servlet also provides four state Persistence Technologies: URL rewriting, hiding domains, cookies, and HTTPSession. HTTPSession is the most commonly used one.
Ii. JSP Addition
Evolution 3: Servlet has two disadvantages: 1) All HTML tags written in Servlet must contain java strings to handle HTTP response packets; 2) All texts are hard-coded, that is, a slight change also requires re-compilation. JSP solves the preceding problems and is used together with Servlet. |
JSP is essentially a Servlet, but it does not need to be compiled. The JSP page is a text file with a. jsp extension. After the first request, a simple JSP page is translated as a (JSP name) _ jsp Servlet. After the translation, the Servelt can see: _ jspInit (), _ jspDestory (), _ jspService () is actually the same as Servlet.
Contents placed in the WEB-INF folder cannot be accessed directly through the browser input address, and outside the WEB-INF folder is OK, after adding a new JSP page, you do not need to restart the JSP/Servlet container (such as tomcat ).
Decoupling 1: using standard JSP to access and operate JavaBean is the first step for separating presentation (HTML) from business implementation (Java code. |
Comments (<% -- content -- %>), commands (<% @ command name %>), scripts (<% script %> ), expression (<% = value assignment result %>), declare (<%! Declaration %>), Action (<jsp: useBean/> ).
Evolution 4: EL in JSP can easily access application data, so that the JSP page does not require any declarations, expressions, and scripts. |
EL expression $ {expression} and value [] and. Operator.
Evolution 5: Based on EL, JSP standard tag Library (JSTL) further solves operations such as traversing Map, set, condition test, XML processing, and database operation access. |
To use JSTL, you need the taglib command:
<% @ Taglib uri = "uri" prefix = "prefix" %>
JSTL label type: Declares value assignment, condition judgment, loop traversal, formatting, and functions (mainly string functions)
Evolution 6: JSP standard tag Library (JSTL) provides some labels to solve common problems, but for some very common evil problems, javax needs to be extended. servlet. jsp. the members in the tagetx package implement custom tags. |
The implementation of custom tags is called the tag processor. A simple tag processor is a classic custom tag that inherits the SimpleTag implementation. The classic Tag Processor needs to implement tags, IterationTag and BodyTag interfaces, or extended TagSupport and BodyTagSupport. The simple Tag processor needs to implement
The build tag processor is that the Servlet API and jsp api (servlet-api.jar and jsp-api.jar) files need to be included in the build directory. A custom tag consists of a component processor (WEB-INF/classes) and a tag Descriptor (. tld in a WEB-INF) file. You also need the taglib command to use custom labels.
You can package the custom tag processor and tag descriptor into a jar package and specify an absolute URI so that it can be published like JSTL.
Evolution 7: Writing custom tags is a lengthy and trivial task. You need to write and mutate a tag processing class and describe it in the tag library. The tag file method allows you to customize tags without discrimination of tag processing classes and tag library description files. You do not need to compile or describe the tag file before using it. |
Tag file does not need to be compiled in advance and only requires JSP syntax. A tag file has commands, scripts, EL, Action elements, and custom tags. A tag file is suffixed with tags and tagx, and can contain other resources, A tag file contained by other files should be suffixed with tagf.
The tag file must be placed in the WEB-INF/tags directory of the path to take effect, and like the tag processor, the tag file can also be packaged into a jar file.
Decoupling 2: Servlet provides an excuse to listen for a series of events and events. The upper-layer servlet/JSP applications can call these APIs for event-driven development. |
Listeners are inherited from java. util. Event objects. Listener interfaces can be divided into ServletContext, HttpSession, and ServletRequest. A listener is an interface for a group of actions. Compile a listener. You only need to write a java class to implement the corresponding listener interface. Then, add the listener element in the @ WebListener annotation or deployment Description document for registration.
Evolution 8: Filter is used to intercept Request requests. Before a user requests to access resources, ServletRequest and ServletResponse can implement log record, encryption and decryption, session check, and image file protection. |
To implement Filter, you must implement the javax. servlet. Filter interface and the init (), doFilter (), and destroy () methods. You can configure the Filter by using @ WebFilter or the filter element in the deployment description. The sequence and rules of the implementation of the Filter Chain must be taken into account. In the deployment descriptor, the configuration is first executed.
Evolution 9: Modify Request and Response to implement the Decorator Mode |
Evolution 10: Servlet or Filter occupies the county seat for request processing. If the task takes a long time to complete, when the user's concurrent requests exceed the county tree, the container will have no available threads. The Servlet uses the timeout time to process asynchronous requests and releases the threads waiting for completion. |
Evolution 11: Although configuration can be performed through annotations, deployment descriptors are still needed when more precise configuration is required. The deployment descriptor must be named web. xml and located under the WEB-INF directory, Java classes must be placed under the WEB-INF/classes directory, and Java class libraries must be located under the WEB-INF/lib directory. All application resources must be packaged into JAR files suffixed with. war. |
Evolution 12: web fragment can deploy plug-ins and frameworks in existing web applications. |
Iii. Implementation of Spring MVC
Evolution 13: Servlet dynamic loading allows you to add new web objects without restarting web applications, servlet Container loaders can publish applications in the form of plug-ins without modifying the deployment description, which is particularly useful for the use of the framework. |
The (create, register, and use) (Filter, Listener, Servlet) method provided in the ServletContext interface.
The initializer library is a plug-in framework with two resources: MyServletContainerInitializer class and javax. servlet. servletContainerInitializer Metafile, which must be placed under the WEB-INF/services Directory and has only one line: initializer. name of the implementation class of MyServletContainerInitializer.
Evolution 13: Spring, as an open-source lightweight enterprise application development framework, provides the implementation of dependency injection methods. Dependency injection is a code testability solution. |
In short, there are two components A and B, and A depends on B. Assuming that A is A class and B is used by another method, A must first obtain the instance reference of component B. Spring dependency injection will first create B's instance, then create A's instance, and then inject B into A's instance.
Spring XML configuration is written in the spring-config.xml file, the configuration file can be a copy, can also be divided into multiple copies to support modular configuration, both through the master configuration file read multiple configuration files, you can also read the main configuration file from other configuration files.
Spring creates a control reversal container by means of the constructor or the setter method.
Decoupling 3: Spring MVC model implements model 2 for Web Application Development |
An MVC-mode application consists of three parts: model, view, and controller. View is used to display applications. The model encapsulates application data and business logic. The Controller is responsible for receiving user input, changing the model, and adjusting the display of views.
Spring MVC uses Servlet as the controller, while Structs2 uses Filter as the controller. Most of them use JSP pages as views. The model uses POJO (Plain Old Java Object). In practice, a JavaBean is used to hold the State of the model, and the business logic is put into an Action class, A JavaBean must have a constructor without parameters. It accesses parameters through getter/setter and supports persistence.
The basic Spring MVC project structure includes:
1) A Product class, as the domain object of the product, must implement the java. io. Serializable interface for the Product class because it must be stored in HttpSession.
2) A ProductForm class encapsulates the input items of an HTML form. The ProductForm class fish Product class is similar and does not expose the objects at the Servlet layer of ServletRequest to other layers, in addition, when data verification fails, the form object is used to save and display users' input in the original form.
3) A ControolerServlet class acts as a controller.
4) Two JSP pages serve as views.
Decoupling 4: decoupling the Controller code. If you write all the business logic code in the Servlet controller, the Servlet class will continue to expand as the application complexity increases, the business logic code should be extracted to an independent controller class. |
Both the InputProductController class and the SaveProductController class implement the Controller Interface, which makes the Controller Servlet more focused, just like a Dispatcher, instead of a controller, that is, DispatcherServlet is used to distribute the controller.
Evolution 14: When a Web application executes an action, it needs to validate the input. The programmatic verification is used for user input verification by encoding, And the declarative validation provides XML documents or attribute files containing Teaching and Research rules. |
Evolution 15: When MVC is applied, backend business logic can be called in the Controller class. A complex logical service class is encapsulated in the later section. In the service class, you can instantiate a DAO class to access the database. In the Spring environment, the Service object can be automatically injected into the Controller instance, while the DAO object can be automatically injected into the Service object. |
Iv. Advantages of Spring MVC
Advantages of Spring MVC:
1) No need to write DispatcherServlet;
2) XML-based file configuration does not need to be re-compiled;
3) the controller can be instantiated and bean can be constructed based on user input;
4) user input can be automatically bound and the data type can be converted correctly;
5) user input validation can be performed, and user input forms can be redirected back to support programming-based verification and declarative verification;
6) as part of the Spring framework, other functions provided by Spring can be implemented;
7) supports internationalization and localization;
8) supports multi-view technology (JSP, FreeMarker, Velocity ).
Evolution 16: Spring MVC comes with an out-of-the-box Dispatcher Servlet. The Controller Interface is provided and the handleRequest method is exposed. |
To use this Servlet, You need to configure in the deployment descriptor and will find the configuration file under the WEB-INF directory of an applicationServletName-Servlet. xml. Controller needs to implement org. springframework. web. servlet. mvc. Controller and Controller Interface implementation class functions to process a single action.
You also need to add the JAR files required by Spring MVC.
Evolution 17: Spring MVC uses the view parser to parse the view. You can configure the attempt parser by defining a ViewResolver in the configuration file. |
The springmvc-config.xml implements the configuration of Dispatcher Servlet and ViewResolver. You also need to configure in the deployment descriptor.
Evolution 18: using the annotation-based controller configuration method, a controller class can process multiple actions. |
@ Controller annotation type indicates that the Spring class instance is a Controller;
@ RequestMapping annotation can be used to develop corresponding processing methods for each action in the Controller;
@ Autowired and @ Service annotations can inject dependencies into the Controller;
The @ ModelAttribute annotation can be used to implement Model-type instances generated every time Spring MVC calls the request processing method.
Evolution 19: Data Binding is a feature that binds user input to a domain model and does not require form beans such as form bean. The tag library of the form will assist in such work. |
To use the form tag library, you must declare the taglib command.
Evolution 20: Data Binding of Spring itself is disorganized and requires Converter and Formatter to bind data. |
Converter is a common component and can be used in any layer of the application, while Formatter is specially designed for the Web layer.
Required Converter interface and Formatter interface. You also need to register in springmvc-config.xml.
Evolution 21: Converter and Formatter only act on the field level, and Validator can act on the object level. During the Controller call, one or more Formatter views will be used to convert the field values. Once the Formatter is successfully formatted, Validator will intervene. |
There are two verification methods for user input in Spring MVC: The validation framework of Spring and the implementation of JSR 303. The former needs to implement the Validator interface and call the reject method to add errors. The latter adds constraints to object attributes through annotations. Such validators do not require explicit registration, but can be added in the springmvc-config.xml if you want to get error information from a property file.
Evolution 22: Spring MVC provides support for internationalization and local deployment. It is necessary to isolate text meta files into attribute files. |
The text elements of each language area are stored in an independent property file, each file contains a key/value pair, and each key sweater represents a specific language area object. And configure in springmvc-config.xml.