Showing posts with label Servlet. Show all posts
Showing posts with label Servlet. Show all posts

Monday, 18 July 2016

How to return errors from servlet ?


Return HTTP error from Servlet using :
  • HttpServletResponse.sendError
  • HttpServletResponse.setStatus

Error pages declaration
We can defines a list of error page descriptions in web.xml mapped with status code or exception.
A specific error page can be returned in case of servlet sets a status code or throws a Java exception.

In case of status code set in response or exception (Runtime exceptions, ServletExceptions or IOExceptions) is thrown, container consults the list of status-code or exception-type elements under error page declarations and attempts a match.
If there is a match, it returns the resource declared as location entry.


Friday, 1 July 2016

What are different main elements of deployment descriptor ?


Servlet

servlet 
  • servlet-name 
    • Unique name of servlet for the Web application
  • servlet-class 
    • Fully qualified class name of the servlet
  • init-param 
    • Key / value pair as an initialization param of the servlet
servlet-mapping (servlet-name , url-pattern)
  • Mapping between a servlet and a URL pattern 
  • servlet-name 
    • Unique name of servlet 
  • url-pattern 
    • URL pattern of the mapping
Example
<servlet>
    <servlet-name>
MyFrontControllerServlet</servlet-name>
    <display-name>
MyFrontControllerservlet</display-name>
    <description>The main servlet</description>
    <servlet-class>
         com.demo.
MyFrontControllerServlet 
    </servlet-class>
    <init-param>
         <param-name>xml</param-name>
         <param-value>/WEB-INF/conf/myapp.xml</param-value>
    </init-param>
    <load-on-startup>0</load-on-startup>

</servlet>
 
<servlet-mapping>
    <servlet-name>
MyFrontControllerServlet</servlet-name>
    <url-pattern>/myapp/*</url-pattern>

</servlet-mapping>


Servlet context
Servlet Context init parameters
context-param (param-name, param-value, description) 

  • Key / value pair as an initialization param associated with the web application 
  • Each parameter name must be unique in the web application 
  • These can be accessed in servlet by : 
    • ServletContext.getInitParameter
    • ServletContext.getInitParameterNames
Example
<web-app>
  <context-param>
     <param-name>Webmaster</param-name>
     <param-value>webmaster@mycorp.com</param-value>
  </context-param>
</web-app>

 


Filter
filter
  • filter-name 
    • Unique name of filter for the Web application
  • filter-class 
    • Fully qualified class name of the filter
  • init-param 
    • Key / value pair as an initialization param of the filter

filter-mapping (servlet-name , url-pattern)
  • Mapping between a filter and resource (servlet / JSP)
  • filter-name 
    • Unique name of filter
  • servlet-name
    • Name of servlet to be wrapped by the filter
Example
<filter>
  <filter-name>HibernateSessionFilter</filter-name>
  <description>

      Close Hibernate session after each request
  </description>
  <filter-class>
      com.demo.HibernateSessionFilter
  </filter-class>

</filter>

<filter-mapping>
   <filter-name>HibernateSessionFilter</filter-name>
   <servlet-name>MyFrontControllerServlet</servlet-name>

</filter-mapping>


Listeners
ServletContextListener

  • Its implementations receives notifications about changes to the servlet context of the web application.
  • contextInitialized(ServletContextEvent sce)
    • called when web application is ready to process requests
  • contextDestroyed(ServletContextEvent sce)
    • called when servlet context is about to be shut down

ServletContextAttributeListener
  • Its implementation receives notifications of changes to the attribute list on the servlet context of a web application 
  • attributeAdded(ServletContextAttributeEvent scab)
    • called after a new attribute is added to the servlet context
  • attributeRemoved(ServletContextAttributeEvent scab)
    • called after an existing attribute has been removed from the servlet context
  • attributeReplaced(ServletContextAttributeEvent scab)
    • called after an attribute on the servlet context has been replaced

HttpSessionAttributeListener
  • It can be used to get notifications of changes to the attribute lists of sessions within this web application.
  • attributeAdded(ServletContextAttributeEvent scab)
    • called after a new attribute was added to the servlet context.
  • attributeRemoved(ServletContextAttributeEvent scab)
    • called after an existing attribute has been removed from the servlet context.
  • attributeReplaced(ServletContextAttributeEvent scab)
    • called when an attribute on the servlet context has been replaced

HttpSessionListener
  • notifies for the changes to the list of active sessions in a web application.
  • sessionCreated(HttpSessionEvent se)
    • called when a session is created
  • sessionDestroyed(HttpSessionEvent se)
    • called when a session is invalidated

HttpSessionActivationListener
  • Objects that are bound to a session may listen to container events notifying them that sessions will be passivated and that session will be activated.
  • It can be used when a container that migrates session between VMs or persists sessions and it is required to notify all attributes bound to sessions.

HttpSessionBindingListener 
  • Object is notified when it is bound to or unbound from a session.
Example
<listener>
   <listener-class>
        com.francetelecom.csrtool.gui.init.StartupListener
   </listener-class>

</listener>


display-name
  • Display name of web application
Example
<display-name>My App</display-name>


Icon
  • small-icon
  • large-icon
Example
<icon>
    <small-icon>/resource/icons/
demoSmall.gif</small-icon>
    <large-icon>/resource/icons/demoBig.gif</large-icon>

</icon>




welcome-file-list
  • Default file or URL pattern to redirect at entering context root
Example
<welcome-file-list>
   <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

Thursday, 30 June 2016

What is the structure of Modern Servlet Web Applications ?


A web application exists as a structured hierarchy.
The root of this hierarchy serves as a document root.

WEB-INF
  • This directory contains all things related to the application that aren’t in the document root of the application.
  • No file contained in the WEB-INF directory may be served directly to a client by the container.
  • But, A servlet can access contents of WEB-INF using :
    • ServletContext.gerResource()
    • ServletContext.getResourceAsStream()

Contents under WEB-INF
  • /WEB-INF/web.xml
    Deployment descriptor
  • /WEB-INF/classes/*
    Directory for servlet and utility classes
    The classes in this directory are available to the application class loader.
  • /WEB-INF/lib/*.jar
    contains JAR files (Java ARchive)
    • JAR contain servlets, beans, and utility classes useful to the web application.
    • The web application class loader
      • can load class from any of these JAR files.
      • loads classes from the WEB-INF/classes first, and then from JARs in the WEB-INF/lib directory

forward vs. include


Forward
  • Forwards a request from a Servlet to another resource (Servlet, JSP file, or HTML file) on the server.
  • forward should be called before the response has been committed to the client (before response body output has been flushed)

Include
  • Includes the content of a resource (servlet, JSP page, HTML file) in the response.
  • The included servlet cannot change the response status code or set headers.

Tuesday, 28 June 2016

What will happen if forward is called after the response already has been committed ?


forward should be called before the response has been committed to the client
(before response body output has been flushed)


If the response already has been committed, this method throws an IllegalStateException

How to use RequestDispatcher to include or forward to a web resource ?


ServletContext.getRequestDispatcher(String path)
  • A RequestDispatcher object can be used to forward a request to the resource or to include the resource in a response.
  • The resource can be dynamic or static.
  • The path must begin with a "/" and is interpreted as relative to the current context root.

ServletRequest.getRequestDispatcher(String path)
  • The pathname specified may be relative, although it cannot extend outside the current servlet context.
  • If the path begins with a "/" it is interpreted as relative to the current context root.

Monday, 27 June 2016

How and when life cycle methods are invoked ?


Servlet interface provide life-cycle methods.

1. init() : The servlet is constructed, and then initialized with the init method.
2. service() : Any calls from clients to the service method are handled.
3. destroy() : The servlet is taken out of service, then destroyed with the destroy method.
    Then garbage collected and finalized.

It also provides :
4. getServletConfig() : used to get any startup information
5. getServletInfo() : allows the servlet to return basic information like, author, version, and copyright

How to access values and resources and to set object attributes within 3 scopes ?


Request scope

Methods in ServletRequest interface
  • Object getAttribute(String name)
    Returns the value of an attribute from request or null if attribute is not present
  • Enumeration getAttributeNames()
    Returns an Enumeration containing the names of the attributes
  • ServletInputStream getInputStream()
    Retrieves the body of the request as binary data
  • setAttribute(String name, Object o)
    Stores an attribute in current request
    Most often used in conjunction with RequestDispatcher
  • removeAttribute(String name)
    Removes an attribute from current request
    Not needed as attributes only persist as long as the request is being handled.


Session scope
Methods in HttpSession interface 
Works same way as ServletRequest but associated to Session
  • Object getAttribute(String name)
  • Enumeration getAttributeNames()
  • setAttribute(String name, Object o)
  • removeAttribute(String name)



Context scope
Methods in ServletContext interface
Works same way as ServletRequest but associated to the entire Application
  • Object getAttribute(String name)
  • Enumeration getAttributeNames()
  • setAttribute(String name, Object o)
  • removeAttribute(String name)

ServletContext also provides direct access to the hierarchy of static content documents that are part of the web application, including HTML, GIF, and JPEG files.
  • getResource(String resource)
    Example : getResource("/index.jsp") will return JSP source code
  • getResourceAsStream(String resource)

What will happen if you call sendRedirect after committing the response ?


After using sendRedirect() method, the response should be considered to be committed.

If the response has already been committed, this method throws an IllegalStateException.

How to redirect an HTTP request to another URL ?


Method in HttpServletResponse interface
  • sendRedirect(String location)
    sends a temporary redirect response to the client using the specified redirect location URL
    .
    It can accept relative URLs ( without a leading '/'
    ) which must converted to the absolute URL by Servlet container
After using this method, the response should be considered to be committed.
If the response has already been committed, this method throws an IllegalStateException.

How to acquire a binary stream for the response ?


Method of ServletResponse interface
  • ServletOutputStream getOutputStream()
    Returns ServletOutputStream for writing binary data in the response.


    Calling flush() on the ServletOutputStream commits the response.

How to acquire a text stream for the response ?


Method of ServletResponse interface
  • PrintWriter getWriter()
    Returns a PrintWriter object that can send character text to the client


    Calling flush() on the PrintWriter commits the response.

How to set the content type of the response ?


Method of ServletResponse interface
  • setContentType(String) 
    • Sets the content type of the response being sent to the client 
    • It may include character encoding as well. 
    • Example : text/html; charset=ISO-8859-4

What will happen if headers are set after the response is committed ?


Headers must be set before the response is committed.

If headers are set after the response is committed, that will be ignored by the servlet container. 

How to set a HTTP response header ?


Methods of the HttpServletResponse interface
  • setHeader : sets a header with a given name and value
    If header name already exists, it will replace all the n existing values with 1 new value
  • addHeader : adds a header value to a given name
  • setIntHeader : sets a int type header
  • setDateHeader : sets a Date type header
  • addIntHeader : adds a int type header
  • addDateHeader : adds a Date type header

* Headers must be set before the response is committed.

How to retrieve HTTP request header information ?


Methods of HttpServletRequest interface
  • getHeader : returns a header value by given header name
    If there are multiple headers with the same name, it returns the first head in the request.
  • getHeaders : returns all the header values associated with the given header name (Enumeration of Strings)
  • getHeaderNames : returns names of all the headers
  • getIntHeader : returns header value (String) into int format
    If it cannot translate the header value to an int, a NumberFormatException is thrown.
  • getDateHeader : returns header value (String) into Date format
    If it cannot translate the header to a Date object, an IllegalArgumentException is thrown.

Sunday, 26 June 2016

How to retrieve a servlet initialization parameter ?


Methods of ServletConfig interface
  • public String getInitParameter(String)returns a String containing the value of the named initialization parameter, or null if the parameter does not exist.
     
  • public Enumeration getInitParameterNames()returns the names of the servlet’s initialization parameters as an Enumeration of String objects.

How to retrieve HTML form parameters from the request ?


All form data from both the query string + post body are aggregated into the request parameter set.
The parameters sent in URI query string are stored by the servlet container as a set of name/value pairs.


Multiple parameter values can exist for any given parameter name. (Like, a=123&a=567)
 

Methods in ServletRequest interface
  • getParameter : returns value for a given parameter
  • getParameterNames : returns array of all names of parameters (No value)
  • getParameterValues : returns an array of String objects containing all the parameter values associated with a parameter name

Scenario : If a request is made with :

  • A query string of a=hello
    and
  • A post body of a=goodbye&a=world
The resulting parameter set would be ordered a=(hello, goodbye, world)

What are the triggers that cause a browser to use a HTTP method ?


HTTP POST
  • Allows the client to send data of unlimited length to server
  • Usage : Useful when sending sensitive information like, Credit card numbers

HTTP GET

  • Retrieves whatever information sent in Request URI

HTTP HEAD

  • It is a GET request that returns no body in the response, on the request header fields.
  • The client sends a HEAD request when it wants to see only the headers of a response, such as Content Type or Content-Length.
    • This method counts the number of output bytes in the response to set the Content-Length header accurately.
  • Usage :
    • can be used for obtaining meta-information about the entity implied by the request without transferring the entity-body itself.
    • often used for testing hypertext links for validity, accessibility, and recent modification.

What methods I should ovveride in a servlet ?


For creating a website, create a HTTP servlet.
  • Extend HttpServlet (an Abstract class)
  • Override at least one method (usually one of the following) :
    • doGet : to support HTTP GET requests
    • doPost :  for HTTP POST requests
    • doPut :  for HTTP PUT requests
Don't override service method, as it handles HTTP requests by dispatching them to handler methods for each type of HTTP request.