Java Server Pages - JSP

 Index


JSP

JSP or Java Server Pages is a technology that is used to create web application just like servlet technology. A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain than servlet because we can separate designing and development.

JSP Architecture

  • Firstly Client sends an http request to the server. As with a normal page, your browser sends an http request to the web browser. For e.g. authentication windows where you enter user id and password in the system and click the submit button, the client thus sends this information to the server to check whether it is valid or not.
  • Web server recognizes the request made by the client that is it for a JSP page or any other HTML extension page. If the request made by the client is for a JSP page, then the Web server forwards it to the JSP engine. JSP engine processes the page. This is by using URL or JSP page which ends with .jsp extension.

  • Then comes the translation phase. This phase is of utmost importance as the JSP engine loads the JSP page, and converts it into servlet content i.e. all the template text converts to println() statements and all JSP elements convert to Java code. As in the diagram hello.jsp gets converted to helloServlet.java. It is important to note that jsp content gets converted to java code in the translation phase.

  • Translation phase is followed by the compilation phase. JSP engine compiles servlet into .class files that can execute. It forwards the initial request to the servlet engine. As shown in the diagram hello.jsp gets translated to helloServlet.java and then compiled to a class file called helloSevlet.class. This phase is also called the request processing phase as the request is getting processed here.

  • Thereafter the servlet class is loaded by a part of the web container, namely servlet engine, and This class file is then executed. The output is finally produced in HTML format after execution. The output is sent in an HTTP response to the web server by the servlet engine. The diagrams show the complete process.

  • Then The web server forwards the response to the client’s browser. This HTTP response is in the form of static HTML content as it is more user friendly and easily understandable.

  • Finally, the dynamically generated web content is handled statically by the web browser. Then the HTML page inside the HTTP response is handled as if it is a static page.

Life cycle of JSP

  • JSP Translation - When the client sends the request to the web server, it goes to the web container. Now evidently, if the JSP page is newer and the servlet class is older, it means that the page got modified. In that case, the translation is done otherwise, this step is skipped so as to improve the performance of the system as it takes time.
  • JSP Compilation - Prior to compilation, JSP engine probes if the page has ever been compiled. If the page has some modifications or if it has never been compiled, then JSP engine compiles the page. Now the compilation follows three steps:
    • Parsing JSP
    • Conversion of JSP to Servlet
    • Compiling the servlet
  • Class Loading - At this stage, the .class file gets loaded by the loader i.e., corresponding servlet class file is loaded.
  • Instantiation - As we compiled the servlet, the object of the generated servlet is created. This process takes place after the class file is loaded in the memory. As soon as the instantiation takes place the objects: ServletConfig and ServletContext get accessible to the JSP class. ServletConfig is a pre-defined interface used to develop flexible servlets. ServletContext is generated by the web container when the project is deployed. ServletConfig object exists as one per servlet program, whereas ServletContext object exists as one per web application.
  • Initialization - After instantiation, container invokes jspInit() method better known as initialization of JSP. It basically initializes the instance we created. Talking in detail, it is done to initialize resources needed to process the request i.e. resources like databases, allow JSP pages to read data, create lookup tables, and manage network connections. Though it is invoked by the container only once, it can be overridden by the author.
  • Request Processing - After the initialization of servlet instances, a new thread gets created. All the interactions necessary to process requests occur at this stage. Thus, container invokes _jspService() method. This method contains two parameters:
    • HTTPServletRequest req
    • HTTPServletResponse res
This service method is responsible for generating a response to the request. Not only this, but it also generates response to all seven HTTP methods, namely:
    • GET - GET is a read only request. It tends to get information from the server. GET request posses 3 standard triggers:
      • Typing in the address line of the browser and clicking enter or go.
      • Pressing submit button in HTML form.
      • Clicking on the link of a web page in order to access it.
    • POST - This method gets triggered when the form settings is made as a post.
    • HEAD - This method is almost similar to the GET method. Though this method doesn’t return a message body, it can check if a resource hasn’t been recently updated, valid, and accessible.
    • PUT - Using the request payload, PUT method replaces current representations of the target resource.
    • DELETE - This method deletes the specified resource.
    • CONNECT - This method establishes a path identified by the target resource to reach the server.
    • OPTIONS - This method describes the communication options that we need to communicate with the target resource.
  • Destruction - The destruction basically represents cleanup. For the cleanup jspDestroy() method gets invoked. This cleanup means that the JSP page after processing gets removed from the container. This method destroys the instance of the servlet class code, and all the connections to database and network are released. Opened files are also closed. jspDestroy() is overridden whenever the cleanup needs to be done.

JSP Syntax Basics

Directive

Directives supply directions and messages to a JSP container. The directives provide global information about the entire page of JSP. Hence, they are an essential part of the JSP code. These special instructions are used for translating JSP to servlet code.
There are 3 types of directives:
  1. Page directive
  2. Include directive
  3. Taglib directive
  • Page directive - The page directive is used for defining attributes that can be applied to a complete JSP page. You may place your code for Page Directives anywhere within your JSP page. However, in general, page directives are implied at the top of your JSP page. The basic syntax of the page directive is:
<%@ page attribute = "attribute_value" %>
  • The attributes used by the Page directives are:
    • buffer: Buffer attribute sets the buffer size in KB to control the JSP page's output.
    • contentType: The ContentType attribute defines the document's MIME (Multipurpose Internet Mail Extension) in the HTTP response header.
    • autoFlush: The autofill attribute controls the behavior of the servlet output buffer. It monitors the buffer output and specifies whether the filled buffer output should be flushed automatically or an exception should be raised to indicate buffer overflow.
    • errorPage: Defining the "ErrorPage" attribute is the correct way to handle JSP errors. If an exception occurs on the current page, it will be redirected to the error page.
    • extends: extends attribute used for specifying a superclass that tells whether the generated servlet has to extend or not.
    • import: The import attribute is used to specify a list of packages or classes used in JSP code, just as Java's import statement does in a Java code.
    • isErrorPage: This "isErrorPage" attribute of the Page directive is used to specify that the current page can be displayed as an error page.
    • info: This "info" attribute sets the JSP page information, which is later obtained using the getServletInfo() method of the servlet interface.
    • isThreadSafe: Both the servlet and JSP are multithreaded. If you want to control JSP page behavior and define the threading model, you can use the "isThreadSafe" attribute of the page directive.
    • Language: The language attribute specifies the programming language used in the JSP page. The default value of the language attribute is "Java".
    • Session: In JSP, the page directive session attribute specifies whether the current JSP page participates in the current HTTP session.
    • isELIgnored: This isELIgnored attribute is used to specify whether the expression language (EL) implied by the JSP page will be ignored.
    • isScriptingEnabled: This "isScriptingEnabled" attribute determines if the scripting elements are allowed for use or not.

  • Include Directive - The JSP "include directive" is used to include one file in another JSP file. This includes HTML, JSP, text, and other files. This directive is also used to create templates according to the developer's requirement and breaks the pages in the header, footer, and sidebar. To use this Include Directive, you have to write it like:
<%@ include file = "relative url" >

  • Taglib Directive - The JSP taglib directive is implemented to define a tag library with "taglib" as its prefix. Custom tag sections of JSP use taglib. JSP's taglibdirective is used as standard tag libraries. To implement taglib, you have to write it like this:
<%@ taglib uri="uri" prefix="value"%>

Declaration

We know that at the end a JSP page is translated into servlet class. So when we declare a variable or method in JSP inside declaration Tag, it means the declaration is made inside the servlet class but outside the service method. You can declare static member, instance variable and methods inside declaration tag.
  • Syntax:
<% ! Declaration %>
  • Example:

Scriptlet tag

Scriptlet Tag allows you to write java code inside JSP page. Scriptlet tag implements the _JSP service method functionality by writing script /java code.
  • Syntax:
<% java code %>
  • Example:

Standard Actions

The JSP specification provides a standard tag called Action tag used within JSP code and is used to remove or eliminate Scriptlet code from your JSP code as JSP Scriptlets are obsolete and are not considered nowadays. There are many JSP action tags or elements, and each of them has its own uses and characteristics. Each JSP action tag is implemented to perform some precise tasks.

<jsp:action_name attribute = "attribute_value" />
Here is the list of JSP Actions:
  • jsp:forward: is used for forwarding the request and response to other resources.
  • jsp:include: is used for including another resource.
  • jsp:body: is used for defining dynamically-defined body of XML element.
  • jsp:useBean: is used for creating or locating bean objects.
  • jsp:setProperty: is used for setting the value of property in the bean object.
  • jsp:getProperty: is used for printing the value of the property of the bean.
  • jsp:element: is used for defining XML elements dynamically.
  • jsp:plugin: is used for embedding other components (applets).
  • jsp:param: is used for setting the parameter for (forward or include) value.
  • jsp:text: is used for writing template text in JSP pages and documents.
  • jsp:fallback: is used for printing the message if plugins are working.
  • jsp:attribute: is used for defining attributes of dynamically-defined XML element.
Basic Attributes of Action Tags - Two basic attributes are commonly used for all action tags. These are:
  • id: The id attribute defines unique action elements and allows actions to be referenced within the JSP page. When the action creates an object's instance, the id attribute is used to refer to it.
  • Scope: The scope attribute is used for identifying an action's life cycle. It correlates with the id attribute because the scope attribute is used to establish that particular object's lifespan associated with the ID.
Example:

Custom tag libraries

JSP custom tags are defined as actions prepared by the developers as per their requirements. Custom Tags are also said to be “JSP Actions” or “Custom actions”. To prepare user-defined actions we have to prepare a set of user-defined tags called “Custom Tags”.

JSP Custom tags are simply called user-defined tags. When a JSP is converted into a servlet, these tags get converted to a class. They are called tag handlers as they do act on an object. These actions get invoked by the web container at the time of execution of the servlet.

The preparation of the custom tag needs 3 elements.
  • Tag Handler Class - It creates the Tag Handler class and this class performs the action at the start or at the end of the tag. Creating the tag Handler class must extend the TagSupport class and override its method doStartTag(). Writing data for the JSP file we must use the JspWriter class.getOut() method provided by the PageContext class and it returns the instance of JspWrite class. pageContext instance by default provided by TagSupport class.
    • Syntax:
  • TLD File - It is abbreviated as Tag Library Descriptor(TLD) for creating user custom tags. The extension should be .tld. This file has to create under the WEB-INF directory.
    • Syntax:
  • JSP Page with Tag lib Library - This is JSP page used for writing our created custom tags within the .jsp file
    • Syntax:

Implicit Objects

The JSP engine produces these objects during the translation phase (i.e., at the time of translation from JSP to Servlet). They are being formed within the service method so that JSP developers can use them directly in Scriptlet without declaration and initialization.

JSP provides us 9 implicit objects
  • Application - This implicit object is the type of ServletContext. Which means it provides a reference to the ServletContext interface. We have various action elements that interact with the ServletContext interface.
  • Response - This implicit object is the type of HttpServletResponse. It is directly linked with the response to the client. We can add so many things with this response object like status codes, cookies, date stamps, etc. so basically it is the instance of the HttpServletResponse interface. One advantage is we do not need to create a response object on JSP because it is implicitly available. So it is created by the web container as all the implicit objects are created by the web container only for each request they receive from the client. The response object is basically used to navigate to other resources. Hence it is used to manipulate the response object and we redirect it to other resources we mentioned. we can also specify the error, http status code, etc.
  • Request - This object is also created by the web container, this implicit object is the type of HttpServletRequest and it gets created by each JSP request. It basically gives us the user information which can be used further like username, password, remote address, header information, server name, character encoding, server port, content type, etc. basically it provides us the information about the request or we can say input parameter. The request object is also created by the web container on the JSP page so we do not require to create any implicit request object.
  • Session - This implicit object is also created by the web container and can be used to get the session information. we can also use this object to remove, set and get attribute. This object is of type HttpSession.
  • Exception - This implicit object is also created by the web container and this is the type of Throwable class. But this implicit object we can only use in error pages and it is used to print the exception.
  • Out - This implicit object is also created by the web container. If we want to write any data to buffer then we have this out the implicit object. This object is a type of JspWriter.
  • Config - This object is of type ServletConfig. This object is also created by the web container. It is basically used for initialization purpose, it gets the parameters from web.xml.
  • Page Context - This object is of type PageContext. It removes, get and set attribute from below mentioned scope :
    • application
    • request
    • session
    • page
  • Page Object - This page is the type of Object class. Also created by the web container.

Object Scope

Object scope in JSP is segregated into four parts and they are page, request, session and application.
  • page - ‘page’ scope means, the JSP object can be accessed only from within the same page where it was created. The default scope for JSP objects created using <jsp:useBean> tag is page. JSP implicit objects out, exception, response, pageContext, config and page have ‘page’ scope.
  • request - A JSP object created using the ‘request’ scope can be accessed from any pages that serve that request. More than one page can serve a single request. The JSP object will be bound to the request object. Implicit object request has the ‘request’ scope.
  • session - ‘session’ scope means, the JSP object is accessible from pages that belong to the same session from where it was created. The JSP object that is created using the session scope is bound to the session object. Implicit object session has the ‘session’ scope.
  • application - A JSP object created using the ‘application’ scope can be accessed from any page across the application. The JSP object is bound to the application object. Implicit object application has the ‘application’ scope.

Session Management

A session can be defined as an object associated with each user with a unique session ID, and the user's data is based on the account they have registered. Different forms of data can be set in a session; These data related to each user of the site help the user and the website owner in different ways. As you know, HTTP is a "stateless" protocol; Whenever a user visits a web page, the user opens a separate connection with the web server, and the server does not keep a record of preceding client requests.

Different approaches to maintain a session between client and server are:

  • Cookies: Cookies are text files that allow programmers to store some information on a client computer, and they are kept for usage tracking purposes.
  • Passing Session ID in URL: Adding and passing session ID to URL is also a way to identify a session. However, this method is obsolete and insecure because the URL can be tracked.
Top

Comments

Popular posts from this blog

Servlet

Struts