Jsp

Welcome To Tripathi Jsp Page

Jsp Overview:

What is JSP?

JavaServer Pages (JSP) is a technology for developing web pages that support dynamic content which helps developers insert java code in HTML pages by making use of special JSP tags, most of which start with <% and end with %>.

A Jsp component is a type of Java servlet that is designed to fulfill the role of a user interface for a Java web application. Web developers write JSPs as text files that combine HTML or XHTML code, XML elements, and embedded JSP actions and commands.

Using JSP, you can collect input from users through web page forms, present records from a database or another source, and create web pages dynamically.
JSP tags can be used for a variety of purposes, such as retrieving information from a database or registering user preferences, accessing JavaBeans components, passing control between pages and sharing information between requests, pages etc.

Why Use JSP?

JavaServer Pages often serve the same purpose as programs implemented using the Common Gateway Interface (CGI). But JSP offer several advantages in comparison with the CGI.
  • Performance is significantly better because JSP allows embedding Dynamic Elements in HTML Pages itself instead of having a separate CGI files.
  • JSP are always compiled before it's processed by the server unlike CGI/Perl which requires the server to load an interpreter and the target script each time the page is requested.
  • JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc.
  • JSP pages can be used in combination with servlets that handle the business logic, the model supported by Java servlet template engines.
Finally, JSP is an integral part of Java EE, a complete platform for enterprise class applications. This means that JSP can play a part in the simplest applications to the most complex and demanding.

Advantages of JSP:

Following is the list of other advantages of using JSP over other technologies:
  • vs. Active Server Pages (ASP): The advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual Basic or other MS specific language, so it is more powerful and easier to use. Second, it is portable to other operating systems and non-Microsoft Web servers.
  • vs. Pure Servlets: It is more convenient to write (and to modify!) regular HTML than to have plenty of println statements that generate the HTML.
  • vs. Server-Side Includes (SSI): SSI is really only intended for simple inclusions, not for "real" programs that use form data, make database connections, and the like.
  • vs. JavaScript: JavaScript can generate HTML dynamically on the client but can hardly interact with the web server to perform complex tasks like database access and image processing etc.
  • vs. Static HTML: Regular HTML, of course, cannot contain dynamic information.

    Jsp Implicit Objects:

    JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer can call them directly without being explicitly declared. JSP Implicit Objects are also called pre-defined variables.
    JSP supports nine Implicit Objects which are listed below:
    Object Description
    requestThis is the HttpServletRequest object associated with the request.
    responseThis is the HttpServletResponse object associated with the response to the client.
    outThis is the PrintWriter object used to send output to the client.
    sessionThis is the HttpSession object associated with the request.
    applicationThis is the ServletContext object associated with application context.
    configThis is the ServletConfig object associated with the page.
    pageContextThis encapsulates use of server-specific features like higher performance JspWriters.
    pageThis is simply a synonym for this, and is used to call the methods defined by the translated servlet class.
    ExceptionThe Exception object allows the exception data to be accessed by designated JSP.

    The request Object:

    The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time a client requests a page the JSP engine creates a new object to represent that request.
    The request object provides methods to get HTTP header information including form data, cookies, HTTP methods etc.
    We would see complete set of methods associated with request object in coming chapter: JSP - Client Request.

    The response Object:

    The response object is an instance of a javax.servlet.http.HttpServletResponse object. Just as the server creates the request object, it also creates an object to represent the response to the client.
    The response object also defines the interfaces that deal with creating new HTTP headers. Through this object the JSP programmer can add new cookies or date stamps, HTTP status codes etc.
    We would see complete set of methods associated with response object in coming chapter: JSP - Server Response.

    The out Object:

    The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is used to send content in a response.
    The initial JspWriter object is instantiated differently depending on whether the page is buffered or not. Buffering can be easily turned off by using the buffered='false' attribute of the page directive.
    The JspWriter object contains most of the same methods as the java.io.PrintWriter class. However, JspWriter has some additional methods designed to deal with buffering. Unlike the PrintWriter object, JspWriter throws IOExceptions.
    Following are the important methods which we would use to write boolean char, int, double, object, String etc.
    Method Description
    out.print(dataType dt)Print a data type value
    out.println(dataType dt)Print a data type value then terminate the line with new line character.
    out.flush() Flush the stream.

    The session Object:

    The session object is an instance of javax.servlet.http.HttpSession and behaves exactly the same way that session objects behave under Java Servlets.
    The session object is used to track client session between client requests. We would see complete usage of session object in coming chapter: JSP - Session Tracking.

    The application Object:

    The application object is direct wrapper around the ServletContext object for the generated Servlet and in reality an instance of a javax.servlet.ServletContext object.
    This object is a representation of the JSP page through its entire lifecycle. This object is created when the JSP page is initialized and will be removed when the JSP page is removed by the jspDestroy() method.
    By adding an attribute to application, you can ensure that all JSP files that make up your web application have access to it.
    You can check a simple use of Application Object in chapter: JSP - Hits Counter

    The config Object:

    The config object is an instantiation of javax.servlet.ServletConfig and is a direct wrapper around the ServletConfig object for the generated servlet.
    This object allows the JSP programmer access to the Servlet or JSP engine initialization parameters such as the paths or file locations etc.
    The following config method is the only one you might ever use, and its usage is trivial:
     
    config.getServletName();
    This returns the servlet name, which is the string contained in the element defined in the WEB-INF\web.xml file

    The pageContext Object:

    The pageContext object is an instance of a javax.servlet.jsp.PageContext object. The pageContext object is used to represent the entire JSP page.
    This object is intended as a means to access information about the page while avoiding most of the implementation details.
    This object stores references to the request and response objects for each request. The application, config, session, and out objects are derived by accessing attributes of this object.
    The pageContext object also contains information about the directives issued to the JSP page, including the buffering information, the errorPageURL, and page scope.
    The PageContext class defines several fields, including PAGE_SCOPE, REQUEST_SCOPE, SESSION_SCOPE, and APPLICATION_SCOPE, which identify the four scopes. It also supports more than 40 methods, about half of which are inherited from the javax.servlet.jsp. JspContext class.
    One of the important methods is removeAttribute, which accepts either one or two arguments. For example, pageContext.removeAttribute ("attrName") removes the attribute from all scopes, while the following code only removes it from the page scope:
     
    pageContext.removeAttribute("attrName", PAGE_SCOPE);
    You can check a very good usage of pageContext in coming chapter: JSP - File Uploading.

    The page Object:

    This object is an actual reference to the instance of the page. It can be thought of as an object that represents the entire JSP page.
    The page object is really a direct synonym for the this object.

    The exception Object:

    The exception object is a wrapper containing the exception thrown from the previous page. It is typically used to generate an appropriate response to the error condition.

    Jsp Custom Tags:

    A custom tag is a user-defined JSP language element. When a JSP page containing a custom tag is translated into a servlet, the tag is converted to operations on an object called a tag handler. The Web container then invokes those operations when the JSP page's servlet is executed.
    JSP tag extensions let you create new tags that you can insert directly into a JavaServer Page just as you would the built-in tags you learned about in earlier chapter. The JSP 2.0 specification introduced Simple Tag Handlers for writing these custom tags.
    To write a customer tab you can simply extend SimpleTagSupport class and override the doTag() method, where you can place your code to generate content for the tag.

    Create "Hello" Tag:

    Consider you want to define a custom tag named and you want to use it in the following fashion without a body:
    
    
    To create a custom JSP tag, you must first create a Java class that acts as a tag handler. So let us create HelloTag class as follows:
    package com.tutorialspoint;
    
    import javax.servlet.jsp.tagext.*;
    import javax.servlet.jsp.*;
    import java.io.*;
    
    public class HelloTag extends SimpleTagSupport {
    
      public void doTag() throws JspException, IOException {
        JspWriter out = getJspContext().getOut();
        out.println("Hello Custom Tag!");
      }
    }
    
    Above code has simple coding where doTag() method takes the current JspContext object using getJspContext() method and uses it to send "Hello Custom Tag!" to the current JspWriter object.
    Let us compile above class and copy it in a directory available in environment variable CLASSPATH. Finally create following tag library file: webapps\ROOT\WEB-INF\custom.tld.
    
      1.0
      2.0
      Example TLD
      
        Hello
        com.tutorialspoint.HelloTag
        empty
      
    
    
    Now it's time to use above defined custom tag Hello in our JSP program as follows:
    <%@ taglib prefix="ex" uri="WEB-INF/custom.tld"%>
    
      
        A sample custom tag
      
      
        
      
    
    
    Try to call above JSP and this should produce following result:
    Hello Custom Tag!
    

    Accessing the Tag Body:

    You can include a message in the body of the tag as you have seen with standard tags. Consider you want to define a custom tag named and you want to use it in the following fashion with a body:
    
       This is message body
    
    
    Let us make following changes in above our tag code to process the body of the tag:
    package com.tutorialspoint;
    
    import javax.servlet.jsp.tagext.*;
    import javax.servlet.jsp.*;
    import java.io.*;
    
    public class HelloTag extends SimpleTagSupport {
    
       StringWriter sw = new StringWriter();
       public void doTag()
          throws JspException, IOException
        {
           getJspBody().invoke(sw);
           getJspContext().getOut().println(sw.toString());
        }
    
    }
    
    In this case, the output resulting from the invocation is first captured into a StringWriter before being written to the JspWriter associated with the tag. Now accordingly we need to change TLD file as follows:
    
      1.0
      2.0
      Example TLD with Body
      
        Hello
        com.tutorialspoint.HelloTag
        scriptless
      
    
    
    Now let us call above tag with proper body as follows:
    <%@ taglib prefix="ex" uri="WEB-INF/custom.tld"%>
    
      
        A sample custom tag
      
      
        
            This is message body
        
      
    
    
    This will produce following result:
    This is message body
    

    Custom Tag Attributes:

    You can use various attributes along with your custom tags. To accept an attribute value, a custom tag class needs to implement setter methods, identical to JavaBean setter methods as shown below:
    package com.tutorialspoint;
    
    import javax.servlet.jsp.tagext.*;
    import javax.servlet.jsp.*;
    import java.io.*;
    
    public class HelloTag extends SimpleTagSupport {
    
       private String message;
    
       public void setMessage(String msg) {
          this.message = msg;
       }
    
       StringWriter sw = new StringWriter();
    
       public void doTag()
          throws JspException, IOException
        {
           if (message != null) {
              /* Use message from attribute */
              JspWriter out = getJspContext().getOut();
              out.println( message );
           }
           else {
              /* use message from the body */
              getJspBody().invoke(sw);
              getJspContext().getOut().println(sw.toString());
           }
       }
    
    }
    
    The attribute's name is "message", so the setter method is setMessage(). Now let us add this attribute in TLD file using element as follows:
    
      1.0
      2.0
      Example TLD with Body
      
        Hello
        com.tutorialspoint.HelloTag
        scriptless
        
           message
        
      
    
    
    Now let us try following JSP with message attribute as follows:
    <%@ taglib prefix="ex" uri="WEB-INF/custom.tld"%>
    
      
        A sample custom tag
      
      
        
      
    
    
    This will produce following result:
    This is custom tag
    
    Hope above example makes sense for you. It would be worth to note that you can include following properties for an attribute:
    Property Purpose
    nameThe name element defines the name of an attribute. Each attribute name must be unique for a particular tag.
    requiredThis specifies if this attribute is required or optional. It would be false for optional.
    rtexprvalueDeclares if a runtime expression value for a tag attribute is valid
    typeDefines the Java class-type of this attribute. By default it is assumed as String
    descriptionInformational description can be provided.
    fragmentDeclares if this attribute value should be treated as a JspFragment.
    Following is the example to specify properties related to an attribute:
    .....
        
          attribute_name
          false
          java.util.Date
          false
        
    .....
    
    If you are using two attributes then you can modify your TLD as follows:
    .....
        
          attribute_name1
          false
          java.util.Boolean
          false
        
        
          attribute_name2
          true
          java.util.Date
        
    .....
    

     


     JSP Interview Questions and Answers:

    Q: What are the advantages of jsp over servlet?
    A: The advantage of JSP is that they are document-centric. Servlets, on the other hand, look and act like programs. A Java Server Page can contain Java program fragments that instantiate and execute Java classes, but these occur inside an HTML template file and are primarily used to generate dynamic content.
    Some of the JSP functionality can be achieved on the client, using JavaScript. The power of JSP is that it is server-based and provides a framework for Web application development.
    Q: What is the life cycle of jsp?
    A: Life cyle of jsp:
    • Translation
    • Compilation
    • Loading the class
    • Instantiating the class
    • jspInit()
    • _jspService()
    • jspDestroy()
    Q: What is the jspInit() method?
    A: The jspInit() method of the javax.servlet.jsp.JspPage interface is similar to the init() method of servlets. This method is invoked by the container only once when a JSP page is initialized. It can be overridden by a page author to initialize resources such as database and network connections, and to allow a JSP page to read persistent configuration data.
    Q: What is the _jspService ()?
    A: The _jspService() method of the javax.servlet.jsp.HttpJspPage interface is invoked every time a new request comes to a JSP page. This method takes the HttpServletRequest and HttpServletResponse objects as its arguments. A page author cannot override this method, as its implementation is provided by the container.
    Q: What is the jspDestroy ()?
    A: The jspDestroy() method of the javax.servlet.jsp.JspPage interface is invoked by the container when a JSP page is about to be destroyed. This method is similar to destroy() method of servlets. It can be overridden by a page author to perform any cleanup operation such as closing a database connection.
    Q: What jsp life cycle method can I override?
    A: You cannot override the _jspService() method within a JSP page. You can however, override the jspInit() and jspDestroy() methods within a JSP page. JspInit() can be useful for allocating resources like database connections, network connections, and so forth for the JSP page. It is good programming practice to free any allocated resources within jspDestroy().
    Q: What are implicit objects in jsp?
    A: Implicit objects in JSP are the Java objects that the JSP Container makes available to developers in each page. These objects need not be declared or instantiated by the JSP author. They are automatically instantiated by the container and are accessed using standard variables; hence, they are called implicit objects.
    Q: How many implicit objects are available in jsp?
    A: These implicit objects are available in jsp:
    • Request
    • Response
    • PageContext
    • session
    • application
    • Out
    • config
    • page
    • exception
    Q: What are jsp directives?
    A: JSP directives are messages for the JSP engine. i.e., JSP directives serve as a message from a JSP page to the JSP container and control the processing of the entire page.
    They are used to set global values such as a class declaration, method implementation, output content type, etc. They do not produce any output to the client.
    Q: What is page directive?
    A: Page Directive is:
    • A page directive is to inform the JSP engine about the headers or facilities that page should get from the environment.
    • The page directive is found at the top of almost all of our JSP pages.
    • There can be any number of page directives within a JSP page (although the attribute – value pair must be unique).
    • The syntax of the include directive is: <%@ page attribute="value">
    Q: What are the attributes of page directive?
    A: There are thirteen attributes defined for a page directive of which the important attributes are as follows:
    • Import: It specifies the packages that are to be imported.
    • Session: It specifies whether a session data is available to the JSP page.
    • ContentType: It allows a user to set the content-type for a page.
    • IsELIgnored: It specifies whether the EL expressions are ignored when a JSP is translated to a servlet.
    Q: What is the include directive?
    A: Include directive is used to statically insert the contents of a resource into the current JSP. This enables a user to reuse the code without duplicating it, and includes the contents of the specified file at the translation time.
    Q: What are the jsp standard actions?
    A: The JSP standard actions affect the overall runtime behaviour of a JSP page and also the response sent back to the client. They can be used to include a file at the request time, to find or instantiate a Java Bean, to forward a request to a new page, to generate a browser-specific code, etc.
    Q: What are the standards actions available in jsp?
    A: The standards actions include:
    Q: What is the standard action?
    A: The standard action is used to locate an existing Java Bean or to create a Java Bean if it does not exist. It has attributes to identify the object instance, to specify the lifetime of the bean, and to specify the fully qualified class path and type.
    Q: What is the scope available in ?
    A: Scope includes:
    • Page scope
    • Request scope
    • application scope
    • session scope
    Q: What is the standard action?
    A: The standard action forwards a response from a servlet or a JSP page to another page. The execution of the current page is stopped and control is transferred to the forwarded page.
    Q: What is the standard action?
    A: The standard action enables the current JSP page to include a static or a dynamic resource at runtime. In contrast to the include directive, include action is used for resources that change frequently. The resource to be included must be in the same context.
    Q: What is the difference between include directive and include action?
    A: The difference is:
    • Include directive, includes the content of the specified file during the translation phase–when the page is converted to a servlet. Include action, includes the response generated by executing the specified page (a JSP page or a servlet) during the request processing phase–when the page is requested by a user.
    • Include directive is used to statically insert the contents of a resource into the current JSP. Include standard action enables the current JSP page to include a static or a dynamic resource at runtime.
    Q: What is the difference between pageContext.include () and ?
    A: The standard action and the pageContext.include() method are both used to include resources at runtime. However, the pageContext.include () method always flushes the output of the current page before including the other components, whereas flushes the output of the current page only if the value of flush is explicitly set to true.
    Q: What is the action?
    A: You use jsp: setProperty to give values to properties of beans that have been referenced earlier.
    Q: What is the action?
    A: The action is used to access the properties of a bean that was set using the action. The container converts the property to a String as follows:
    If it is an object, it uses the toString() method to convert it to a String. If it is a primitive, it converts it directly to a String using the valueOf() method of the corresponding Wrapper class.
    The syntax of the method is:
    Q: What is the standard action?
    A: The standard action is used with or to pass parameter names and values to the target resource.
    Q: What is the action?
    A: This action lets you insert the browser-specific OBJECT or EMBED element needed to specify that the browser run an applet using the Java plugin.
    Q: What is the scripting element?
    A: JSP scripting elements let you insert Java code into the servlet that will be generated from the current JSP page.
    • Expressions
    • Scriptlet
    • Declarations
    • comment
    Q: What is the scriptlet?
    A: A scriptlet contains Java code that is executed every time a JSP is invoked. When a JSP is translated to a servlet, the scriptlet code goes into the service() method.
    Hence, methods and variables written in scriptlet are local to the service() method. A scriptlet is written between the <% and %>tags and is executed by the container at request processing time.
    Q: What is the jsp declaration?
    A: JSP declarations are used to declare class variables and methods in a JSP page. They are initialized when the class is initialized. Anything defined in a declaration is available for the whole JSP page. A declaration block is enclosed between the <%! and %>tags. A declaration is not included in the service() method when a JSP is translated to a servlet.
    Q: What is the jsp expression?
    A: A JSP expression is used to write an output without using the out.print statement. It can be said as a shorthand representation for scriptlet. An expression is written between the <%= and %> tags. It is not required to end the expression with a semicolon, as it implicitly adds a semicolon to all the expressions within the expression tags.
    Q: How is scripting disabled?
    A: Scripting is disabled by setting the scripting-invalid element of the deployment descriptor to true. It is a subelement of jsp-property-group. Its valid values are true and false.
    Q: Why is _jspService () start with ‘_’?
    A: _jspService() method will be written by the container hence any methods which are not to be overridden by the end user are typically written starting with a '_'. This is the reason why we don't override _jspService() method in any JSP page.
    Q: How to pre-compile jsp?
    A: Add jsp_precompile as a request parameter and send a request to the JSP file. This will make the jsp pre-compile. http://localhost:8080/jsp1/test.jsp?jsp_precompile=true
    It causes execution of JSP life cycle until jspInit() method without executing _jspService() method.
    Q: What is the benefit of pre-compile jsp page?
    A: It removes the start-up lag that occurs when a container must translate a JSP page upon receipt of the first request.
    Q: What is the difference between variable declared inside the declaration tag and variable declared in scriptlet?
    A: Variable declared inside declaration part is treated as a instance variable and will be placed directly at class level in the generated servlet. Variable declared in a scriptlet will be placed inside _jspService () method of generated servlet. It acts as local variable.
    Q: What are the three kind of comment in jsp?
    A: These are the three types of commenst in jsp:
    • JSP Comment: <%-- this is jsp comment -- %>
    • HTML Comment: <!-- this is HTMl comment -- >
    • Java Comments: <% // single line java comment /* this is multiline comment */ %>
    Q: What is the output comment?
    A: The comment which is visible in the source of the response is called output comment. <!-- this is HTMl comment -- >
    Q: What is a hidden comment?
    A: This is also known as JSP comment and it is visible only in the JSP and in rest of phases of JSP life cycle it is not visible. <%-- this is jsp comment -- %>
    Q: How does jsp handle the run time exception?
    A: You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page.
    Q: How can I implement the thread safe jsp page?
    A: You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive in the JSP. <%@ page isThreadSafe="false" %>
    Q: Is there a way to reference the “this” variable within the jsp?
    A: Yes, there is. The page implicit object is equivalent to "this", and returns a reference to the generated servlet.
    Q: Can you make the use of servletOutputStream object within jsp?
    A: Yes. By using getOutputStream () method on response implicit object we can get it.
    Q: What is autoflush?
    A: This command is used to autoflush the contents. If a value of true is used it indicates to flush the buffer whenever it is full. In case of false it indicates that an exception should be thrown whenever the buffer is full. If you are trying to access the page at the time of conversion of a JSP into servlet will result in error.
    Q: What is the different scope available in jsp?
    A:The different scopes are:
    • Page: Within the same page.
    • Request: After forward or include also you will get the request scope data.
    • Session: After sendRedirect also you will get the session scope data. All data stored in session is available to end user till session closed or browser closed.
    • Application: Data will be available throughout the application. One user can store data in application scope and other can get the data from application scope.
    Q: When to use application scope?
    A: If we want to make our data available to the entire application then we have to use application scope.
    Q: Can a jsp page instantiate a serialized bean?
    A: No problem! The use Bean action specifies the bean Name attribute, which can be used for indicating a serialized bean.
    Q: In which situation we can use the static include and dynamic include?
    A: If the target resource won’t change frequently, then it is recommended to use include directives. If the target resource will change frequently, then it is recommended to use include action.

                     

No comments:

Post a Comment