Java Jsp Interview Questions

1.Explain JSP life Cycle methods?

  • jsp engine controls the life cycle of jsp
  • Jsp life cycle is described by three life cycle methods and six life cycle phases


Jsp life cycle methods :

  • jspInit()
  • _jspService()
  • jspDestroy()


  • Jspinit() method is invoked when JSP page is initialized.
  • The _jspService() method corresponds to the body of the jsp page.
  • This method is defined automatically by the JSp container and should never be defined y the JSP page author.

Jsp Life cycle Phases: 

  • Translation phase
  • Compilation phase
  • Instantiation phase
  • initialization phase
  • Servicing phase
  • Destruction phase

Read More at : JSP Life Cycle

2. What are the Jsp Implicit Objects?


  • Implicit objects in jsp are the objects that are created by the container automatically and the container makes all these 9 implicit objects to the developer.
  • We do not need to create them explicitly, since these objects are created and automatically by container and are accessed using standard variables(objects) are called implicit objects.
  • The following are of implicit variables available in the JSP.  


  1. out
  2. request
  3. response
  4. config
  5. application
  6. session
  7. pagecontext
  8. page
  9. exception
Read More at: 9 Jsp Impicit Objects in java

3. Explain Jsp Scripting Elements?

  • Jsp scripting elements are used to embed jva code in to the jsp.
  • Jsp scripting elements are three types
    1. Declaration
    2. Expression
    3. Scriplet
Read More at: Jsp Scripting Elements



4. What are the Directives in Jsp?

  • A jsp directive is a translation time instruction to the jsp engine.
  • we have three kinds of directives.
  1. Page directive
  2. Include directive
  3. Taglib directive

 Read More at: Jsp Directive Elements


 5. What are the differences between include directive and include action?


Java Jsp interview Questions

 

6. How to disable session in JSP?

  • By using page directive
  • <%@ page session="false" %> 

7. How can we handle exceptions in a JSP page?

  • We can handle exception in jsp by using error page element of page directive 
  • The errorPage attribute tells the JSP engine which page to display if there is an error while the current page runs.
    The value of the errorPage attribute is a relative URL.
    The following directive displays MyErrorPage.jsp when all uncaught exceptions are thrown

    Syntax:

    errorPage="url"

    Example:

    <%@ page errorPage="error.jsp"%>

8.How can we override jspInit() and jspDestroy() methods in a jsp?

  • Both methods are executed once in a life cycle of a jsp.
  • We can override these two method as shown below.
  • <%!
        public void jspInit() {
            . . .
        }
    %>
  • <%!    
        public void jspDestroy() {
            . . .   
        }
    %>

9.Can a JSP extend a java class?

  • Yes we can extend a java class in jsp
  • <%@ include page extends="classname" %>
  • We can do this because jsp will convert to a servlet so a servlet can extend a class its fine

10.How can we pass information from one jsp to included jsp page?

  • <jsp:include page="employeedetail.jsp" flush="true">
  • <jsp:param name="name" value="abc"/>
  • <jsp:param name="id" value="220"/>

Java Servlet Interview Questions

 

1.Explain Servlet life cycle in java.

  • Servlet engine controls the life cycle of servlet
  • Servlet life cycle is described by three life cycle methods under 5 life cycle phases
  • life cycle methods are
  1. init(ServletConfig obj)
  2. service(servletRequest, servletResponse)
  3. destroy() 

  • When ever somethings happens in the life of servlet. servlet engine calls these methods on the servlet instance and hence the name.

Read more here: Servlet Life Cycle


2.What is ServletConfig ?

  • Request parameters are used by the servlet to receive data from client to process the request.
  • Some specific data must be supplied to the servlet at the time of initialization of the servlet and this data is specific to the client.But data is not supplied by the client via request parameters
  • Use initialization parameters to supply the data to the servlet at the time of initialization of the servlet. initialization parameters are set in deployment descriptor   (Web.xml).
  • Servlet can access these parameters during the run time
  • Request parameters change form Request to request 
  • Initialization parameters change from servlet to servlet.

Read more at : ServletConfig

3. What is ServletContext?

  • We can deploy multiple web applications in a servlet container.
  • Each web application contains its own resources in a separate  environment. This environment called ad Web Application context or ServletContext.
  • The resources belongs to the one web application context are not available to the other web application context.
  • A Servlet context contains zero or more number of servlets. For every servlet object the container creates separate ServletConfig object.
Read More at : ServlectContext


4. Can we define a Constructor in servlet?

  • Yes we can define a constructor in servlet but we can not call the constructor explicitly because servlet container will create the object of servlet so it will be called by the servlet container.

5. Can we call destroy() method inside init() method of a servlet. If yes what will happen?

  • Yes we can call destroy() method inside a init() method.
  • Actually container will call destroy() method if we call that method explicitly nothing will happen.
  • If we override destroy() method and called from init(). method will be called and code will be executed.

6.What are the difference between GenericServlet and HttpServlet?

GenericServlet HttpServlet
Abstract Class Abstract Class
Protocol Independent Http Protocol Dependent
Subclass of Servlet Subclass of GenericServlet
public void service(ServletRequest req,ServletResponse res ). Supports public void service() and protected void service(), doGet(),doPost(),doPut(),doDelete(),doHead(),doTrace(),doOptions()etc.


7.What are the differences between doGet() and doPost()?



doGet() doPost()
protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, java.io.IOException Protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
handles client's GET request handles client's POST request
Request parameters appended to the URL and sent along with header information Request parameters are submitted via form.
Request Parameters are not encrypted Request Parameters are encrypted
Maximum size of data that can be sent using doget() method is 240 bytes There is no maximum size for data.




8. Can we call a servlet from another servlet?

  • Yes. We can call a servlet from another servlet this is known as inter servlet communication.
  • By using RequestDispatcher object we can do this.
  • RequestDispatcher rd=request.getRequestDispatcher("other servlet url name");
  • rd.forward(req, res);
Read more at : RequestDipatcher in java

9. What are the differences between forward() and sendRedirect() methods?

 


forward() sendRedirect()
request.getRequestDispathcer("example.jsp").
forward(request, response);
response.sendRedirect
("http://www.instanceofjava.com");
Used to forward the Request to resources available in within the server Used to redirect the Request to other resources or domains

10.How can you get the information about one servlet context in another servlet?

  • By using setAttribut() method we can set the data in one servlet and get in another
  • Context.setAttribute (“name”,” value”)
  • Context.getAttribute (“name”)

11.Explain Servlet architecture?

  • Frequently asking java interview question in servlets you may get questions like
  • explain the architecture of java servlet?
  • explain the architecture of java servlet with diagram?
  • define the servlet architecture?
  • servlet architecture overview?
  • Servlets read the explicit data sent by the clients (browsers). This includes an HTML form on a Web page or it could also come from an applet or a custom HTTP client program.
  • Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media types and compression schemes the browser understands, and so forth.
The Servlet architecture in Java is a Java-based framework for building web applications. It is a specification defined by the Java Community Process (JCP) and is implemented by various web containers such as Apache Tomcat, Jetty, and GlassFish.

The Servlet architecture consists of several components, including:

Servlets: These are the core components of the Servlet architecture. They are Java classes that handle HTTP requests and responses. Servlets are executed by a web container, which is responsible for managing their lifecycle, threading, and security.

Web Containers: Also known as servlet engines, web containers are responsible for managing the lifecycle of servlets, providing services such as request handling, thread management, and security.

JSP (JavaServer Pages): These are Java-based pages that are used to create dynamic web content. JSPs are compiled into servlets by the web container and executed by the servlet engine.

JSP Tag Libraries: These are collections of custom tags that can be used in JSP pages to simplify the creation of dynamic web content.

JavaBeans: These are Java classes that encapsulate business logic and data. They can be used in JSP pages to create dynamic web content.

Filters: These are Java classes that can intercept and modify the requests and responses sent to and from servlets. They can be used to implement security, logging, and other common functionality.

Listeners: These are Java classes that are notified of certain events that occur within the web container, such as a servlet being initialized or a session being created.

In summary, the Servlet architecture provides a powerful and flexible framework for building web applications in Java, by providing a set of components and services to handle HTTP requests and responses, providing a powerful and flexible way to handle web content, and providing a set of components to handle security, logging, and other common functionality.
Read More : servlet architecture with diagram

Servlet example programs in eclipse

1.Run eclipse.File -> new -> dynamic web project

Servlet Example in exclipse


2. Give project name : example MyFirstApp and click on next



Servlet Example in exclipse


3. Please check Generate web.xml deployment descriptor to auto generate web.xml file


Servlet Example in exclipse




interview Servlet Example in exclipse

4.click on finish. now project structure will be created.

Servlet Example program  in exclipse

5.Go to webcontent and create a folder with name Jsp to place jsp files and create a index.jsp.


Servlet Example program  in exclipse




Servlet Example program  in exclipse


Servlet Example program  in exclipse





Servlet Example program  in exclipse


6. index.jsp will have an error because it is not having servlet jar. file so we need to include servler-apt.jar file.

Servlet Example program  in exclipse


Servlet Example program  in exclipse



Servlet Example program  in exclipse



now its fine. modify index.jsp with one text box and submit button.


Servlet Example program  in exclipse




  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1
  2.     pageEncoding="ISO-8859-1"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org
  4. /TR/html4/loose.dtd">
  5. <html>
  6. <head>
  7. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  8.  
  9. <title>Login</title>
  10.  
  11. </head>
  12. <body>
  13.  
  14. <form action="/MyFirstApp/hello" method="post">
  15.  
  16.        Name:<input type="text" name="name" value="">
  17.         <input type="submit" name="name" value="submit">
  18.  
  19.  </form>
  20.  
  21. </body>
  22.  
  23. </html>


7. create a servlet


Servlet Example program  in exclipse






Servlet Example program  in exclipse


Servlet Example program  in exclipse


  1. package com.instanceofjava;
  2.  
  3. import java.io.IOException;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8.  
  9. public class Hello extends HttpServlet{
  10.  
  11.   private static final long serialVersionUID = 1L;
  12.  
  13. public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException,
  14. ServletException{
  15.  
  16.         String str= (String) req.getParameter("name");
  17.         req.setAttribute("name", str);
  18.  
  19.         req.getRequestDispatcher("/Jsp/welcome.jsp").forward(req, res);
  20.  
  21.     }
  22. }

8. create a welcome.jsp page.


Servlet Example program  in exclipse


Servlet Example program  in exclipse








  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 
  2. pageEncoding="ISO-8859-1"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org
  4. /TR/html4/loose.dtd">
  5. <html>
  6. <head>
  7. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  8.  
  9. <title>welcome</title>
  10. </head>
  11.  
  12. <body>
  13.  
  14. <%
  15. String str=null;
  16.  
  17. try{
  18.  
  19.     str=(String)request.getAttribute("name");
  20.  
  21. }catch(Exception e){
  22.  
  23. }
  24.  
  25. %>
  26.  
  27. <p>Welcome: <%=str %></p>
  28.  
  29. </body>
  30.  
  31. </html>


8. go to we.xml and include our servlet




Servlet Example program  in exclipse



  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns
  4. /javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  5.  <display-name>MyFirstApp</display-name>
  6.  <welcome-file-list>
  7.  
  8.     <welcome-file>/Jsp/index.jsp</welcome-file>
  9.  
  10.   </welcome-file-list>
  11.  
  12.   <servlet>  
  13.  
  14.    <servlet-name>HelloServlet</servlet-name>  
  15.    <servlet-class>com.instanceofjava.Hello</servlet-class> 
  16.  
  17.   </servlet>  
  18.  
  19. <servlet-mapping>
  20.  
  21.         <servlet-name>HelloServlet</servlet-name>
  22.         <url-pattern>/hello</url-pattern>
  23.     </servlet-mapping>
  24.  
  25. </web-app>


9. run the project , select tomcat 7 from apache.

Servlet Example program  in exclipse


10. Enter your name and click on submit.

Servlet Example program  in exclipse


Servlet Example program  in exclipse


JSP Implicit Objects

  • Implicit objects in jsp are the objects that are created by the container automatically and the container makes all these 9 implicit objects to the developer.
  • We do not need to create them explicitly, since these objects are created and automatically by container and are accessed using standard variables(objects) are called implicit objects.
  • The following are of implicit variables available in the JSP.  

9 Jsp implicit Objects

1.out
2.request
3.response
4.config
5.application
6.session
7.pagecontext
8.page
9.exception



1.out:

  •  out is one the implicit object to write the data to the buffer and send output to the client in response.
  • out object allows us to access the servlets output stream and has a pagescope.
  • out.print("");
  • out is the object of javax.servlet.jsp.JspWriter class.
  • While working with servlet we need printWriter object
  • PrintWriter out=response.getWriter();   
  • In servlet we are used PrintWriter to send the output to the client. In JSP we use JSPWriter. 

Difference between JspWriter and PrintWriter:

  • Every JSPWriter is associated with 8KB of internal Buffer. Where as PrintWriter doesn’t associated with any Buffer.
  • The methods of the JspWriter class are designed to throw java.io.IOException where as the methods of PrintWriter class are not throw Exception.
  • JspWriter is an abstract class present in javax.servlet package.
  • PrintWriter is a class defined in java.io package.
  1. public class PrintWriter extends Writer { 
  2. // .....
  3. }
  4.  
  5. public abstract class JspWriter extends Writer {
  6. //....
  7. }

JspWriter out object in jsp:

  1. <html> 
  2. <body> 
  3. <%
  4.     int a = 10;
  5.     int b = 20;
  6.     out.print(“A value is:”+a);
  7.     out.write(“B value is:”+b);
  8. %>
  9. </body> 
  10. </html> 



Printwriter object in servlet:

  1. PrintWriter out=response.getWriter();  

2.request:

  • request implicit object is the object of  type  HttpServletRequest.
  • request object will be created by the container for every request.
  • It will be used to get request information like parameter , header information ,server name server port etc.
  • By using request object we can able to set ,get and remove attributes from request scope.
  • It uses the getPareameter() method to access request parameter.
  • The container passes this object to the _jspService() method.


  1. <form action="welcome.jsp">  
  2. <input type="text" name="username">  
  3. <input type="submit" value="submit"><br/>  
  4. </form> 

  1. <%   
  2. String name=request.getParameter("userid");  
  3. out.print("welcome "+name);  
  4. %> 

  1. out.println(request.getMethod()+”<br>”);
  2. out.println(request.getRequestURI()+”<br>”);
  3. out.println(request.getProtocol()+”<br>”);
  4. out.println(request.getHeader(“User Agent”)+”<br>”);
  5. out.println(request.getHeader(“Accept-language”)+”<br>”);

3.response:

  • response is an instance of class which implements the HttpServletResponse interface.
  • Container generates this object and passes to the _jspService() method as parameter.
  • response object will be created by the container for each request.
  • It represents the response that to be given to the client. 
  • The response implicit object is  used to content type, add cookie and redirect the response to another resource.

1.set content type.

  1. response.setContextType(“text/xml”);
  2. out.println(“<employee>”);
  3. out.println(“<eno>|</eno>”);
  4. out.println(“</employee>”);

2.Redirect response:

  1. <%  
  2.     response.sendRedirect("http://www.instanceofjava.com"); 
  3. %>

3. To send the error message directly to the client:

  1. <%  response.sendError(537,”xyz”); %>

4.config

  • config is one of the implicit object of type javax.servlet.ServletConfig.
  • config object is created by the web container for each jsp page.
  • config object used to get initialization parameters from web.xml file.


  1. <web-app>
  2.  
  3. <servlet>  
  4. <servlet-name>instanceofjava</servlet-name>  
  5. <jsp-file>/welcome.jsp</jsp-file>  
  6. <init-param>  
  7. <param-name>dname</param-name>  
  8. <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>  
  9. </init-param>  
  10. </servlet>  
  11.  
  12. <servlet-mapping>  
  13. <servlet-name>instanceofjava</servlet-name>  
  14. <url-pattern>/welcome</url-pattern>  
  15. </servlet-mapping>  
  16.  
  17. </web-app> 

  1. <%   
  2. String driver=config.getInitParameter("dname");  
  3. out.print("driver name="+driver);  
  4. %> 

  • servletConfig is an object used by servlet container to pass the information during initialization.
  • Once if we get the ServletConfig object, we can find the name of the servlet which is configured in web.xml file by using a method getServletName() method.

  1. <%
  2. String name = config.getServletName();
  3. oput.println(name);
  4. %>


5.application:

  • application is one of the implicit object of type javax.servlet.ServletContext.
  • application object is created by the web container one per application when the application gets deployed.
  • application object used to get context parameters from web.xml file.
  • ServletContext object contains set of methods which are used to interact with ServletContainer. By using these methods we can find the information about ServletContainer.
  • When ever sun micro system releases a new version of API. It is the responsibility of server vender to provide the implementation to the latest API. 
  • For example when servlet 2.5 is released Tomcat guys has provided the implementation and integrated it in Tomcat 6.0 the latest version of servlet API is 3.0 this version is integrated in Tomcat 7.0.
     

  1. <web-app>
  2.  
  3. <servlet>  
  4. <servlet-name>instanceofjava</servlet-name>  
  5. <jsp-file>/index.jsp</servlet-class>  
  6. </servlet>  
  7.  
  8. <servlet-mapping>  
  9. <servlet-name>instanceofjava</servlet-name>  
  10. <url-pattern>/index</url-pattern>  
  11. </servlet-mapping> 
  12.  
  13. <context-param>  
  14. <param-name>dname</param-name>  
  15. <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>  
  16. </context-param>  
  17.  
  18. </web-app>

  1. <%   
  2. String driver=application.getInitParameter("dname");  
  3. out.print("driver name="+driver);  
  4. %> 

6.session

  • session implicit object is holding HttpSession object.
  • session object used to set, get, and remove attributes to the session scope and also used to get session information.

index.html

  1. <html>  
  2. <body>  
  3. <form action="/welcome">  
  4. <input type="text" name="uname">  
  5. <input type="submit" value="submit"><br/>  
  6. </form>  
  7. </body>  
  8. </html>   

welcome.jsp

  1. <html>  
  2. <body>  
  3. <%   
  4. String name=request.getParameter("uname");  
  5. out.print("Welcome "+name);  
  6. session.setAttribute("user",name);  
  7. <a href="showuserinfo.jsp">showuser details</a>  
  8. %>  
  9. </body>  
  10. </html>   

showuserinfo.jsp

  1. <html>  
  2. <body>  
  3.  
  4. <%   
  5. String name=(String)session.getAttribute("user");  
  6. out.print("Hello "+name);  
  7. %>  
  8.  
  9. </body>  
  10. </html> 
  11. %> 

7.pagecontext:

  • pagecontext implicit object is type of  PageContext.
  • pagecontext object used to set , get and remove attributes in particular scope
  1. page scope
  2. request scope
  3. session scope
  4. application scope

  1. pageContext.setAttribute("user",name,PageContext.SESSION_SCOPE);
  2.  String name=(String)pageContext.getAttribute("user",PageContext.SESSION_SCOPE); 

8.page

  • Page implicit variable hold the currently executes Servlet object for the corresponding JSP.
  • Acts as this object for current jsp page
  1.  <%=page.getClass().getName() %>
  2.   <%=page.getServlestInfo()%> 

9.exception

  • The implicit variable can be used only in Error pages. When we try to use this variable in a JSP which is not an Error page we get an Error message.

  1.  <%@ page isErrorPage="true" %>  
  2. <html>  
  3. <body>   
  4.  
  5. <%= exception %>  
  6.  
  7. </body>  
  8. </html> 


Filters in java


  • Filters are used to pre process the request and post process the response.
  • This concept has introduced in servlet 2.3 version.
  • Preprocessing involves authentication , logging ,authorization , change request information.
  • Post processing involves encrypting response compressing response.
Filters in java



Application areas of Filter:

  • To implement logging mechanism.
  • To perform authentication.
  • To perform authorization.
  • To alter request information.
  • To alter response information.
  • Encrypting response.
  • Compressing response.

Interfaces present in Filter API: 

  • Javax.servlet.Filter
  • Javax.servlet.FilterConfig
  • Javax.servlet.FilterChain

 Filter:

  • Every filter class should implement filter interface either directly or indirectly.
  • Filter interface defines the most common which can be applicable for any Filter object.
  • Filter interface defines following methods
    1. init()
    2. doFilter()
    3. destroy()

  • public abstract void init(FilterConfig config) Throws ServletException:
    This method is used to perform initialization activities.
    This method will be executed just after filter object is created.
  • public abstract void doFiletr(ServletRequest req, ServletResponse res, FilterChain ch) throws
    IOException, ServletException
    .
    This method will be executed for every request to perform filter activities.
    In this method only we have to implement entire Filter logic
    This method takes filterChain object as argument and by using that we can forward the request
    to the nest level. Next level can be again filter or servlet.
  • public abstract void destrroy();
    this method will be executed only once to perform cleanup activities just before taking filter from out of service .





Jsp Directive Elements

  • A jsp directive is a translation time instruction to the jsp engine.
  • we have three kinds of directives.
  1. Page directive
  2. Include directive
  3. Taglib directive


Page Directive:

  • Page directive is one of the three translation time instructions to the jsp engine.
  • Page directive has 13 attributes.
  • Mostly page directive used to import java packages in to jsps
    <% @ page import="java.sql.*, java.util,*"%>

Jsp Page directive attributes:

  1. import
  2. session
  3. isErrorPage
  4. errorPage
  5. ContentType
  6. isThreadSafe
  7. extends
  8. info
  9. language
  10. autoflush
  11. buffer

import:

This attribute defines the list of packages,each separated by comma.

Syntax:

import="package.class"

Example:

<%@page import="java.util.*,java.io.*"%>

Session:

The session attribute indicates that  whether or not the JSP page uses HTTP sessions. If it is tree means that the JSP page has access to a
existing session object and it is false means that the JSP page cannot access the built-in session object.

Syntax:

session="true|false"

Example:

<%@ page session="true"%>

isErrorPage:

In JSp Page IsErrorPage indicates that whether or not the current page can act as a error page or not.If it is true it is Supposed to handle the Errors..

Syntax:

isErrorPage="true|false"

Example:

<%@ page isErrorPage="false"%>

errorPage:

The errorPage attribute tells the JSP engine which page to display if there is an error while the current page runs.
The value of the errorPage attribute is a relative URL.
The following directive displays MyErrorPage.jsp when all uncaught exceptions are thrown

Syntax:

errorPage="url"

Example:

<%@ page errorPage="error.jsp"%>

contentType :

The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type of the HTTP response.

Syntax:

contentType="MIME-Type"

Example:

<%@ page contentType="text/html; charset=ISO-8859-1"%>

isThreadSafe:

isThreadSafe option tells that a page as being thread-safe. By default, all JSPs are considered thread-safe.
If you set the isThreadSafe is false, the JSP engine makes sure that only one thread at a time is executing your JSP.

Syntax:

isThreadSafe="true|false"

Example:

<%@ page isThreadSafe="true"%>

extends:

Indicates the superclass of servlet when jsp translated in servlet.

Syntax:

extends="package.class"

Example:

<%@ page extends="com.Connect"%>

info:

This attribute simply sets the information of the JSP page which is retrieved later by using getServletInfo() method of Servlet interface.

Syntax:

info="message"

Example:

<%@ page info="created by instanceofjava" %>

language:

language tells the server about the language to be used in the JSP file.
Presently the only valid value for this attribute is java.

Syntax:

language="java"

Example:

<%@ page language="java"%>

autoflush:

autoflush attribute true indicates that the buffer should be flushed when it is full and false indicates that an exception should be thrown
when the buffer overflows.

Syntax:

autoflush="true|false"

Example:

<%@ page autoFlush="true"%>

Buffer:

The buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP page.The default size of the buffer is 8Kb.

Syntax:

buffer="sizekb|none"

Example:

<%@ page buffer="8kb"%>

include Directive:

The include directive is used to include the contents of any resource it may be jsp file, html file or text file.
It allows a JSP developer to include source code of a file inside jsp file at the specified place at a translation time.

Advantage of Include directive:

Code Reusability

Syntax:

<%@ include file="sourceName"%>

Example:

<%@ include file="/foldername/fileName"%>

taglib Directive:

The taglib directive makes custom actions available in current page through the use of tag library.
TLD (Tag Library Descriptor) is used for file to define the tags.

Syntax:

<%@ taglib uri="path" prefix="prefix"%>

Example:


<%@ taglib uri="http://www.instanceofjava/tags" prefix="mytag"%>




Jsp life cycle


     
  • jsp engine controls the life cycle of jsp
  • Jsp life cycle is described by three life cycle methods and six life cycle phases

Jsp life cycle methods :

  • jspInit()
  • _jspService()
  • jspDestroy()
Jsp Life Cycle

  • Jspinit() method is invoked when JSP page is initialized.
  • The _jspService() method corresponds to the body of the jsp page.
  • This method is defined automatically by the JSp container and should never be defined y the JSP page author.

Jsp Life cycle Phases: 

  • Translation phase
  • Compilation phase
  • Instantiation phase
  • initialization phase
  • Servicing phase
  • Destruction phase

Jsp Life Cycle methods




  • Jsp engine calls jspInit() method only once during the initialization phase of a jsp.
  • similarly during destruction phase jsp engine calls jspDestory() method only once
  • For each client request Jsp container calls _jspService() method once.

Jsp Translation phase:

  • When client request comes for a jsp for the first time , jsp engine makes a full read of the jsp verifies the syntactical corectness of the jsp elements and converts code into a servlet source code .
  • The process of JSP engine translating jsp into servlet nothing but translation phase of JSP.
  • Therefore , we say that Jsp development is another style of development  asking container to develop the servlet is nothing but JSP developement
  • Container generated servlet class is also known as page implementation class.

Jsp Compilation phase:

  • The process of jsp engine compiling the page implementation class is nothing but compilation phase of jsp.
  • Jsp engine uses JASPER compiler to compile the container generated servlet class source code.
  • In the life of the Jsp Translation and compilation happens only once unless jsp source code modified.

Jsp Instantiation phase:

  • Container creating the instance of generated servelt class is nothing but instantialtion phase of jsp
  • actually now we have a servelt object.
  • Servlet engine loads user user defined servlet class file from secondary memory into
    primary memory dynamically

    class c= class.forName("name");
    c.newInstance();
  • Servlet engine creates the instance of loaded servlet class.
  • Servlet engine uses the following piece of code to load the servlet clas  dynamically to instantiate it.
    Class c= class.forName("Servlet class name");
    c.newInstance();


Initialization:

  • Servlet engine creates servletConfig object
  • Servlet engine calls the init() method on the servlet instance by supplying servletconfig object
    as argument.
  • Once init method completely executed servlet is ready to serve the client request.

Servicing : 

  • Servlet engine creates servlet request and servlet response object based on the web server
    provided client information.
  • Servlet engine calls service method on the servlet instance by supplying two object reference as arguments
  • Once service method is completely executed , client request is served and request-response cycle is complete.
  • Within the service method request object is used to capture the user input
  • Response object is used to build the dynamic page and hand over the same to the web server

Destruction:

  • Destruction phase of servlet represents servlet being removed from use by container
Select Menu