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

Jsp Declaration:

  • Jsp declaration is one of the three scripting elements.
  • it is used to embed java code into the jsp
  • A Jsp declration starts with "<%!" and ends with "%>".
  • <%! int a%>.
  • Instance variables, instance methods, static methods can be declared and defined in ajsp declaration.
  • During translation time of jsp they became members of container generated servlate/page implementation class.

Jsp Expression:

  • Jsp Expression is one of the three scripting elements.
  • it is used to embed java code into the js.
  • A jsp expression starts with "<%=" and ends with "%>".
  • <%=a+b%>
  • within a Jsp expression only one java expression that too without semicolon is placed.
  • When Jsp expression is evaluated two thing will happen in the backend
    1. Java expression is evaluated
    2. The result is sent to the browser stream.
  •  we can have any number of jsp expressions in ajsp.
  • During translation phase each java expression of a jsp expression is placed in into _jspService()
    method of page implemented class


Jsp Scriplet:

  • Jsp scriplet is one of the three scripting elements.
  • it is used to embed java code into the js.
  • A jsp scriplet starts with "<%" and ends with "%>".
  • <% java code%>
  • To serve the client request what ever java code required that is placed in servlet.
  • In servlet programming whatever code we write in the service() method of user defined servlet all that code can be placed in a jsp scriplet.
  • During the translation phase java code placed in the scriplet is written in to _jspService() method of page implementation class.
  • in jsp we can have any number of scriplets.

JSP in java

  • Java Server Pages is a java based web technology
  • Jsp ia J2EE technology.
  • JSP is a specification for web container manufacturers.
  • JSP is an API.
  • JSP is aweb component
  • JSP is a dynamic web resource of a web application.
  • JSP is web server side piece of code that extends functionality of web server.
  • Jsp engine is a software written in java technology according to JSP specification.

General duties of JSP:

  • Capturing user input
  • communicating with DB
  • Processing the data
  • Producing the response

JSP API:

  • Javax.ei
  • javax.servlet.jsp
  • javax.servlet.jsp.el
  • javax.servlet.jsp.targext

Interfaces present in javax.servlet.jsp:

  • HttpJspPage
  • JspApplicationContext
  • JspPage

  Classes present in javax.servlet.jsp:

  • ErroeData
  • JspContext
  • JspEngineInfo
  • JspFactory
  • JspWriter
  • PageContext
check below links for more details

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.
  • ServletContext is an interface. this interface implemented by the container by the container provider.
  • The implemented class allows all servlets in the web application to communicate with the container.
  • We can store common data into this application and also we can share that data even after request response objects deletion in the memory.

ServletContext

 Configure Context parameters in web.xml file

ServletContext


Methods of ServletContext interface:

  1. public String getInitParameter(String name): Returns a String containing a value of the method context-wide initialization  parameter, or null if if parameter does not exist.
  2. public Enumeration getInitParameterNames():Returns the names of the context's initialization parameters as enumeration of string objects , or empty enumeration if context has no initialization parameters.
  3. public void setAttribute(String name,Object object):sets the given object in the application scope.
  4. public Object getAttribute(String name):Returns the servlet container attribute with the given name , or null if there is no attribute by that name.
  5. public Enumeration getInitParameterNames():Returns the names of the context's initialization parameters as an Enumeration of String objects.
  6. public void removeAttribute(String name):Removes the attribute with the given name from the servlet context.
  7. public int getMajorVersion(): Returns the major version of the Java Servlet API that is servlet container supports.
  8. public int getMinorVersion(): Returns the minor version of the Java Servlet API that is servlet container supports.
  9. public void log(Java.lang.String msg): Writes specified message to a servlet log file, usually an event log.

How to get the object of ServletContext interface:

       ServletContext application=getServletConfig().getServletContext();   
          String driverName=application.getInitParameter("name");  


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.
ServletConfig

Configure  Initialization parameters in Web.xml file:

ServletConfig

ServletConfig Methods :

  1. public String getInitParameter(String name): Returns a String containing value of the named parameter, or null if the parameter does not exist.
  2. public Enumeration getInitParameterNames(): Returns names of the servlets initialization parameters as an enumeration of String objects, or an empty enumeration if servelt has no initialization
  3. public String getServletName():Returns the name of the servlet.
  4. public ServletContext getServletContext():Returns an object of ServletContext.

 

How to get Initialization parameters:

  • To access initialization parameters of a servlet we use servelt config object.
  • ServletConfig is an interface defined by javax.servlet package and this interface is implemented by container.
  • ServletConfig is the object of the class that implements ServletConfig interface and this object is created by servlet conatainer with servlet init() method parameters.
  • For each servlet One ServletConfig object is created by the container.
        ServletConfig sc=getServletConfig();
        String s=sc.getInitParameter("email");
     
To get all values:

       ServletConfig config=getServletConfig(); 
       Enumeration<String> e=config.getInitParameterNames(); 
       String names=""; 
       while(e.hasMoreElements()){ 
       str=e.nextElement(); 
       out.print("<br>Name: "+str); 
       out.print(" value: "+config.getInitParameter(names)); 
    }








RequestDispatcher in servlet


  • One servlet delegating request processing duty to other servlet is known as request dispatching.
  • To implement inter-servlet communication and servlet -jsp communication we need request dispatching.
  • When servlet receives a simple client request it need to communicate with any other servlet. if the incoming client request is complex one.
  • A servlet process some portion of the request and remaining portion it need to communicate with other servlet known as inter-servlet communication.

Implementing Request dispatching:

Step 1: Creating RequestDispatcher object.
    
   RequestDispatcher rd=request.getRequestDispatcher("other servlet url name");

Step 2: Dispatching the request to the other servlet.
         
  RequestDispatcher having two methods to switch the control from one servelt to other
  1. public void include(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException:Includes the content of a resource (servlet, JSP page, or HTML file) in the response.
  2. public void forward(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException:Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.
By calling any of the above two methods request dispatching is implemented

           rd.forward(req, res) or rd.include(req, res)

forward();

  • In case of forward mechanism of  request dispatching one servlet receives the control , performs a portion of processing and switches the control to another servlet for the remaining portion of the processing
  •  That second servlet performs remaining portion of the request processing , produces the response page and handle over to the same web server.

Include():



  • In case of include mechanism of  request dispatching one servlet receives the control , performs a portion of processing and switches the control to another servlet for the remaining portion of the processing. gets control back from the next servlet and produces the dynamic web page on the web server.



Servlet Life Cycle


Servlet life cycle Methods:

  • 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.

Life cycle phases :

  1. Does not exist phase
  2. Instantiation phase
  3. Initialization phase
  4. Servicing  phase
  5. Destruction phase


Doesn't Exist:

  • Servlet class is made available to the servlet engine but not yet its instance is created.
  • It is known as doesn't exist phase of a servlet.

Instatiation:

  • The process of creating the object of a class is known as instantiation.
  • 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

Servlet Architecture


  • 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.
  • Process the data and generate the results. This process may require talking to a database, executing an RMI or CORBA call, invoking a Web service, or computing the response directly.
  • Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.
  • Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or other clients what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks.

Servlet API:

  • Servelt API contains three packages 
  • javax.servlet: Package contains a number of classes and interfaces that describe the contract
    between a servlet class and the runtime environment provided for an instance of such a class a
    conforming servelt container.
  • javax.servlet.aanotation: Package contains a number of annotations that allow users to use
    annotations to declare servlets , filters, listeners and specify the metadata for the declared component
  • javax.servlet.http: Package contains a number of classes and interfaces that describe and define the contract between a servlet class rnning under the HTTP protocal and the runtime environment provided for an instance of such class by a confirming servlet container.

Interfaces present in javax.servlet:

  • AsyncContext
  • AsyncListener
  • Filter
  • FilterChain
  • FilterConfig
  • RequestDispatcher
  • Servlet
  • ServletConfig
  • ServletContext
  • ServletContextAttributeListener
  • ServletContextListener
  • ServletRequest
  • ServletRequestAttributeListener
  • ServletRequestListener
  • ServletResponse
  • SingleThreadModel

Classes present in javax.servlet:

  • AsyncEvent
  • ServletInputStream
  • ServletOutputStream
  • GenericServlet
  • ServletContextEvent
  • ServletContextAttributeEvent
  • ServletRequestAttributeEvent
  • ServeltRequestEvent
  • ServletRequestWrapper
  • ServeletResponseWrapper
  • SessionCookieConfig

Exceptions:

  • ServletException
  • UnavilableException

 Interfaces present in javax.servlet.http:  

  • HttpServletRequest 
  • HttpServletResponse
  • HttpSession
  • HttpSessionBindingListener
  • HttpSessionContext
  • HttpSessionListener
  • HttpSessionActivationListener
  • HttpSessionAttributeListener

Classes present in javax.servlet.http:

  • Cookie
  • HttpServlet
  • HttpServletRequestWrapper
  • HttpServletResponseWrapper
  • HttpSessionBindingEvent
  • HttpSessionEvent
  • HttpUtils

Annotation types declared in javax.servlet.annotation package

  • InitParam
  • ServletFilter
  • WebServlet
  • WebservletContextListener
Servlet







    Select Menu