JSP implicit object and MVC design pattern

Source: Internet
Author: User

JSP implicit object and MVC design pattern

Today, let's take a look at the implicit image and MVC design pattern of JSP applications.

First, let's talk about the JSP implicit object: the JSP implicit object is an instance of a group of classes loaded by the Web container. It is an object that can be used directly on the JSP page. There are four main categories: 1. Input and Output objects: control the input and output (request, response, out) of the page ).

2. Scope communication object: Retrieves Servlet-related information (session, application, pageContext) related to JSP pages ).

3. Servlet object: Provides page and config information ).

4. Error object: handling errors on the page (exception ).

 

First, let's take a look at the input and output objects: request object: request implicit object indicates the client's request, which contains all the request information. The common method is voidsetContentType (String name ): set the type and character encoding of the content generated as a response.

Void sendRedirect (Stringname): sends a response to the browser indicating that it should request another URL (data will be lost, and the code below sendRedirect method will not be executed after the jump.

Out object: The out implicit object should be used on the JSP page to send the object content in text format to the client.

The out object is returned by calling the getOut method of the pageContext object. Its function and usage are very similar to the PrintWriter object returned by the ServletResponse. getWriter method.

The out implicit object type on the JSP page is JspWriter. JspWriter is equivalent to a PrintWriter with the cache function. You can adjust the cache size by setting the buffer attribute of the page instruction on the JSP page, even disable its cache.

The out implicit object on the JSP page is equivalent to the buffer packaging Class Object inserted before the PrintWriter object returned by the ServletResponse. getWriter method.

 

The out object calls ServletResponse only when the content written to the out object meets any of the following conditions. the getWriter method returns the PrintWriter object to write the content in the buffer zone of the out object to the buffer zone provided by the Servlet engine: set the buffer attribute of the page command to disable the cache function of the out object. The content written to the out object is full of the buffer of the out object. The entire JSP page ends. The communication object: The pageContext object is javax. servlet. jsp. the instance object of the PageContext class, javax. servlet. jsp. the PageContext class is javax. servlet. jsp. the subclass of JspContext.

The pageContext object is returned by calling the JspFactory. getPageContext method.

The pageContext object encapsulates the running information of the current JSP page. It provides methods for returning other implicit objects on the JSP page.

On the JSP page, you only need to pass the pageContext object to an instance object of a Java class. In this Java object, you can access and call other functions of the implicit object.

The pageContext object allows you to access all the implicit objects defined in the current page scope.

 

GetException () method returns exception implicit object getPage () method returns page implicit object getRequest () method returns request implicit object getResponse () method returns response implicit object getServletConfig () method return config implicit object getServletContext () method return application implicit object getSession () method return session implicit object getOut () the method returns an out implicit object. The PageContext class defines a setAttribute method to store the object in a HashMap object inside the pageContext object, A getAttribute method is also defined to retrieve objects stored in the HashMap object.

Void setAttribute (String name, ob ject value) ob ject getAttribute (String name)

(Note: In addition to storing and retrieving attribute objects, the PageContext class also defines how to store and retrieve attribute objects in other domains .)

The setAttribute method and getAttribute method can be called in the application, session, request, and pageContext objects to set and retrieve attributes within their respective domains.

Attributes stored in the application object can be accessed by all servlets and JSP pages in the same WEB application.

Attributes stored in the session object can be accessed by all servlets and JSP pages of the same session.

Attributes stored in the request object can be accessed by all servlets and JSP pages of the same request, for example, multiple servlets and JSP pages connected by the PageContext. forward and PageContext. include methods.

Attributes stored in the pageContext object can only be accessed by each component called in the current response process of the current JSP page. For example, the JSP page that is responding to the current request and the custom tag classes it calls.

The PageContext class also provides a unified management method for attributes in various domains to simplify access to attributes in various domains.

Public void setAttribute (java. lang. String name, java. lang. ob ject value, int scope) public java. lang. ob ject getAttribute (String name, int scope)

 

The value of the scope parameter is PageContext. APPLICATION_SCOPE PageContext. SESSION_SCOPE PageContext. REQUEST_SCOPE PageContext. PAGE_SCOPE publicvoid removeAttribute (String name)

Publicvoid removeAttribute (String name, int scope)

The getAttributeNamesInScope method findAttribute method PageContext class defines a forward method and two include methods to simplify and replace RequestDispatcher respectively. forward method and RequestDispatcher. call the include method: public void forward (java. lang. string relativeUrlPath) throwsjavax. servlet. servletException, java. io. IOException public voidinclude (java. lang. string relativeUrlPath)

 

Throwsjavax. servlet. servletException, java. io. IOException public void include (java. lang. string relativeUrlPath, boolean flush) throws javax. servlet. servletException, java. io. the resource paths passed by IOException to these methods can only be relative paths. If the path starts with "/", it indicates the root directory relative to the current WEB application. Otherwise, the access path mapped to the current JSP.

 

The session Object of the session object indicates the user's session status. This mechanism can be used to easily identify each user and save and track the user's session status. The most common method for session objects: void setAttribute (String name, ob ject value)

Void getAttribute (String name)

The application Object acts on the entire application. All client windows can share the object, which exists from the server until the server is closed. The most common method of application objects: void setAttribute (String name, ob ject value): name/value, store the value of an object in application (the type of the stored value is ob ject ).

 

Void getAttribute (String name): obtains the value of the object stored in the application based on the name (the type of the obtained value is ob ject ).

Set the context initial parameters. Add content to the appropriate location of the web. xm l file:

<Context-param> <param-name> website </param-name> <param-value> www.sohu.com </param-value> </context-param>

On the JSP page, use the getInitParameter () method of The applicatin object to obtain the parameter value corresponding to the website parameter. In Servlet, use the method of the same name as the ServletContext object to obtain the parameter value.

 

Use the log () method to record logs.

You can use the log () method provided by the application object to implement the logging function. logs recorded on the Tomcat server are stored in the logs directory of the Tomcat root directory. The log Content is divided into different files for record.

Servlet object: The page Object provides access to all objects defined on the webpage. The page Object indicates the page itself, which is an instance of the java. lang. ob ject class.

Config object: The config object stores some initial information about Servlet. The config object is an instance of the javax. servlet. ServletConfig interface. The ServletConfig interface provides methods to retrieve Servlet initialization parameters. The config object indicates the configuration of Servlet initialization data on the JSP page.

Error object exception: exception object processing error on the JSP page: printStackTrace () method is used to display stack traces of exceptions. We have introduced the JSP implicit object, next, let's talk about the Design Pattern of MVC: before developing a software, we must first design its architecture. A basic architecture idea is to divide the software into different modules, the key to the problem is how to divide modules.

 

MVC (Model-View-Controller) is a software design mode invented for Smalltalk-80 programming language in 1980s, It is a design method of separating business logic and display interface.

The Model part of MVC is responsible for managing the business data of the program. The View part is responsible for displaying the interface and Controller) it is responsible for interacting with users (receiving requests and selecting the response view ).

JSP design mode: the JSP specification provides two solutions for Building Web applications using JSP pages-JSP Mode 1 and Mode 2. The difference between the two modes lies in the processing position.

JSP Mode 1 (JSP + JavaBean): In the architecture of Mode 1, the JSP page is responsible for processing the request and sending the response to the client.

Typical exchange process of Model1: first, the user calls the JSP page in the Web application through a browser and sends a request. After the JSP page receives a request from the browser, read data from the database by calling the JavaBean object method, and then return the data to the browser on the JSP page. The corresponding information is displayed in the browser.

Advantages: It is very suitable for quick development of small Web projects and has low technical requirements for Java Web developers.

Disadvantages: Java and HTML are soft together, which may cause great difficulties in the later stages of Web project development and maintenance.

JSP Mode 2 (MVC): Mode 2 architecture integration uses Servlet and JSP pages. In this mode, the JSP page is used for the presentation layer, and the Servlet is responsible for processing various tasks.

Model2 interaction process: first, the user sends a request to the Servlet in the Web application through a browser. After receiving the request, the Servlet instantiates the JavaBean object and calls the method of the JavaBean object, the JavaBean object returns the data read from the database. The Servlet selects the appropriate JSP and displays the data read from the database through this JSP, finally, the JSP page returns the final result to the browser.

 

Advantage: the business logic and representation content are well separated. This development method is suitable for large-scale projects developed by many people.

Disadvantages: the difficulty of Web project development has increased, and the technical requirements for developers have also increased.

As a controller, Servlet is responsible for processing requests and creating any beans required for the JSP page. The controller is also responsible for determining the JSP page to which the request is sent. The JSP page retrieves the objects created by the Servlet and extracts dynamic content and inserts it into a template.

Note: because the model is on the web server side and the final view is on the user's browser side, the server will respond only after the browser sends a request, and no response will be made without a request, therefore, it is difficult to implement the "state change notification" event of the model in web applications. The view cannot be automatically updated as the model changes. Because the mvc model in the true sense cannot be fully implemented in web applications, Pattern 2 is only a variant of the mvc design pattern. Someone simply calls it "webMVC ".

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.