JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy
  • Contact Us

ServletConfig in Servlet

February 1, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • Servlets Tutorials
  • Servlets Interview Questions

In this article we will see about ServletConfig Interface and how it works. The config object is created by the web container based on the initialization parameters specified in the deployment descriptor. It is used to send information to a servlet during initialization.

Now let see the methods of ServletContext interface, which are listed the following table:

Name Description
String getInitparameter(String Name) It returns the Servlet initialization parameter of the given name and if the requested parameter is not available then it returns null.
Enumeration getInitparameter Names( ) It returns names of all Servlet initialization parameters defined in web.xml file.
String getServletName() Returns the servlet name as defined in the deployment descriptor .
ServletContext getServletContext() Returns the ServletContext object reference.

ServletConfig Example

Let us try out simple example to understand the working of the ServletConfig. Create a class named ServletconfigExample. This class shall create an object of ServletConfig and fetch the init-param from the deployment descriptor and print on the screen.

Listing 1: ServletconfigExample

[code lang=”java”]
package javabeat.net.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletconfigExample extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

ServletConfig config = getServletConfig();
String S1 = config.getInitParameter("websitename");
out.print("I’m : " + S1 + "website!!!!");

out.close();
}
}
[/code]

Listing 2: web.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">

<servlet>
<servlet-name>ServletconfigExample</servlet-name>
<servlet-class>javabeat.net.servlets.ServletconfigExample</servlet-class>
<init-param>
<param-name>websitename</param-name>
<param-value>Javabeat</param-value>
</init-param>
</servlet>

<servlet-mapping>
<servlet-name>ServletconfigExample</servlet-name>
<url-pattern>/ServletconfigExample</url-pattern>
</servlet-mapping>

</web-app>
[/code]

Here we have defined the <init-param> which defines a param-name as websitename and param-value as Javabeat.

Now execute the ServletconfigExample, right click select Run>Run As and the following output appears:
ServletConfig

Previous Tutorial : sendRedirect in Servlet  || Next Tutorial : Difference Between JSP and Servlet

Filed Under: Java EE Tagged With: Servlets Tutorials

sendRedirect in Servlet

February 1, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • Servlets Tutorials
  • Servlets Interview Questions

In this article we shall see how to redirect your current page to some other page. The easiest way to achieve this is by using the sendRedirect() method of class javax.servlet.http.HttpServletResponse.

sendRedirect() method redirects your current page to another servlet or jsp page. This method is used to redirect response to another resource. This method accepts relative as well as absolute URL.
Using sendRedirect() method whenever the client makes any request it goes to the container, then the container decides whether servlet can handle request or not. If it is not handled then that request cab be handled by other servlets.

Some important points on sendRedirect() method:

  • In the sendRedirect method existing request and response objects are lost.
  • sendRedirect methods happens on the client side.
  • In this method request gets transferred to resource outside the application.
  • sendRedirect method works on response object.
  • sendRedirect method is transfer to another resource to different domain.
  • In the sendRedirect method it call old request and response object is list because it is treated as new request.
  • sendRedirect method is slower because extra round trip is required because completely new request is created and old object request is lost.

sendRedirect Example

Now let us try an example as below. In this exmaple the sendRedirect() method would take you to the URL mentioned https://javabeat.net

Listing 1: SendRedirectExample

[code lang=”java”]
package javabeat.net.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SendRedirectExample extends HttpServlet {

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

response.sendRedirect("https://javabeat.net");
}
}
[/code]

Listing 2:web.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">

<servlet>
<servlet-name>SendRedirectExample</servlet-name>
<servlet-class>javabeat.net.servlets.SendRedirectExample</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>SendRedirectExample</servlet-name>
<url-pattern>/SendRedirectExample</url-pattern>
</servlet-mapping>

</web-app>
[/code]

Previous Tutorial : Request Dispatcher in Servlet  || Next Tutorial : ServletConfig in Servlet

Filed Under: Java EE Tagged With: Servlets Tutorials

Request Dispatcher In Servlet

January 31, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • Servlets Tutorials
  • Servlets Interview Questions

Request Dispatcher

While developing web applications we need to distribute the request processing and response generation to multiple servlet objects. So we need to dispatch requests from one component to another component. This can be done by using RequestDispatcher interface.

RequestDispatcher interface is implemented by servlet container to dispatch or to pass the request to a web resource such as Servlet, HTML page or JSP page.

To dispatch the request from Servlet or JSP to web resource using RequestDispatcher we need to perform following steps:

  • Get a RequestDispatcher object reference
  • Using include () and forward () methods of RequestDispatcher.

Getting a RequestDispatcher object

RequestDispatcher object can be obtained by using following methods.

  • The getRequestDispacther () method of ServletContext.
  • The getNamedDispacther () method of ServletContext.
  • The getRequestDispacther () method of ServletRequest.

The getRequestDispacther () method of ServletContext

This method takes String argument to locate the resource to which request is to be dispatched. When this method is called, the container locates given path. Path should start with the / character. If given path does not start with / character it throws IllegalArgumentException.

The getNamedDispacther () method of ServletContext

This method takes String argument used to locate Servlet to which request is to be dispatched. When this method is called, the container locates the Servlet with given name in the context.

The getRequestDispacther () method of ServletRequest

This method obtains the RequestDispatcher object using path to the current request. The Servlet container builds complete path and locates the resource provided in the getRequestDispacther() method of ServletContext.

Using include () and forward () methods of RequestDispatcher

The include() method: This method includes the response of another Servlet into the calling Servlet. This method can be invoked from calling Servlet while servicing the request. It includes contents of resource such as Servlet, JSP page or HTML page in the response. If we want generate response in the source servlet then we should make use of include () method.

The forward() method: This method is used to forward requests to resource such as Servlet, JSP file or HTML page on the server. This method checks whether servlet has obtained the response and output in the response buffer. If buffer is not committed, the content is cleared. However if the buffer is already committed, it throws IllegalStateException. It implies that after invoking forward () method, the Servlet cannot add any response content.

Request Dispatcher Example

Now let us write an example to see how RequestDispatcher works. First write an HTML file called hello.html. This file will contain a form, to enter some text.

Listing 1:hello.html

[code lang=”html”]
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="Simple" method="get">
Name: <input type="text" name="uname"><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
[/code]

Now on submit of the the data, an action Simple.java which is a servlet would be called. In this servlet we are checking if the entered String equals “Javabeat”. If true, then the request is dispatched to another servlet Welcome. Else and error message is displayed and the request dispatcher calls the hello.html again.

Listing 2: Simple.java servlet

[code lang=”java”]
package javabeat.net.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Simple extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String str = request.getParameter("uname");
if (str.equals("Javabeat")) {
RequestDispatcher rd = request.getRequestDispatcher("Welcome");
rd.forward(request, response);

} else {
out.print("Sorry username error–redirecting to login page!");
RequestDispatcher rd = request.getRequestDispatcher("hello.html");
rd.include(request, response);
}

}
}
[/code]

Listing 2: Welcome.java servlet

[code lang=”java”]
package javabeat.net.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Welcome extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String uname = request.getParameter("uname");
out.print("Welcome " + uname);
}
}

[/code]

Now that everything is ready, execute the hello.html. Right mouse click on hello.html select Run > Run As and output would appear as below:
servlet_reqdis_1

Now enter data as “Javabeat” and click on submit button:
servlet_reqdis_2

servlet_reqdis_3

Now enter data as “somename” and click on submit button:

servlet_reqdis_4

servlet_reqdis_5

Previous Tutorial : Servlet Context  || Next Tutorial : sendRedirect in Servlet

Filed Under: Java EE Tagged With: Servlets Tutorials

Servlet Context

January 30, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • Servlets Tutorials
  • Servlets Interview Questions

Servlet Context is used to communicate with the servlet container to get the details of web application. It is created at the time of deploying the project. There is only one Servlet Context for entire web application. Servlet Context parameter uses <context-param> tag in web.xml file.

Methods of ServletContext interface:

Name Description
String getInitParameter(String) It returns the Servlet initialization parameter of the given name and if the requested parameter is not available then it returns null.
Enumeration getInitParameterNames() It returns names of all Servlet initialization parameters defined in web.xml file.
void setAttribute(String, Object) Sets an attribute with the current request.
Object getAttribute(string) Returns the value of an attribute located with the given name or returns null value if an attribute with the given name is not found.
Enumeration getAttributeNames() Returns all the attribute names in the current request.
void removeAttribute(String) Removes an attribute identified by the given name from the request.
getRequestDispatcher( ) This method takes a string argument describing the path to located the resource to which the request is to be dispatched..

Servlet Context Example

Following example shows use of ServletContext:

[code lang=”java”]
package javabeat;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletExample extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException
{

PrintWriter pw = response.getWriter();
pw.println(getServletContext().getInitParameter(&amp;quot;Welcome&amp;quot;));

}
}
[/code]

Here getInitParameter() is used to initialize the parameter from the web.xml file.

web.xml file:

[code lang=”xml”]
<web-app>
<servlet>
<servlet-name>ServletExample</servlet-name>
<servlet-class>javabeat. ServletExample</servlet-class>
</servlet>

<context-param>
<param-name>Welcome</param-name>
<param-value>Welcome to javabeat!!!!!!!!!</param-value>
</context-param>

<servlet-mapping>
<servlet-name>ServletExample</servlet-name>
<url-pattern>/ServletExample</url-pattern>
</servlet-mapping>
</ web-app>
[/code]

Here <context-param > tag contains two tags namely <param-name> and <param-value> which is used to initialize the attributes of the servlet.

The output of the following program is:
Servlet Context output

Previous Tutorial : Web.xml  || Next Tutorial :  Request Dispatcher

Filed Under: Java EE Tagged With: Servlets Tutorials

Web.xml

January 30, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • Servlets Tutorials
  • Servlets Interview Questions

To understand web.xml, first let us uderstand what is xml?

  • xml stands Extensible Markup Language.
  • xml is markup language much like html.
  • Xml defines set of rules for encoding document in a format that readable by both as human and machine.
  • Xml was designed to carry and store data, not to display data. Xml is designed to be self-descriptive.

Web.xml defines mapping between URL paths and servlets that handle requests with those paths. The web.xml file provides configuration and deployment deployment information for the Web components that comprise a Web application. The web.xml descriptor files represents the core of the java application. The web.xml file is located in WEB-INF directory of web application.

Example of web.xml File:

[code lang=”xml”]
<web-app>
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>servletexample.createHelloWorlExample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloworldExample/*</url-pattern>
</servlet-mapping>
</web-app>
[/code]

Elements in Web.xml

Description of elements Used in web.xml file:

  1. <web-aap>: This element represents whole application of web.xml file
  2. <servlet>: This is the sub element of and represents the servlet
  3. <servlet-name>: This is the sub element of servlet and used to represents the name of servlet
  4. <servlet-class>: This is the sub element of servlet and used to represents the class of servlet
  5. <servlet-mapping>: This is the sub element of and used to map the servlet
  6. <url-pattern>: This is the sub element of servlet-mapping and used to client side to invoke the servlet

Web.xml Tags

Tags used in web.xml file are:

  1. Welcome-file-list tag; This tag is used to specify the default page of web application if none is specified.
    Example:
    [code lang=”xml”]
    <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    [/code]

    In the above example index.jsp used as web page for web application

  2. Session config tag: This tag is used to specify the session configuration parameter
    Example:
    [code lang=”xml”]
    <session-config>
    <session-timeout>
    15
    </session-timeout>
    </session-config>[/code]

    In the above example session-config tag contains another tag session-timeout which specifies the http session timeout. The time specify in minutes.

  3. Error page tag: This tag is used to specify the error occurred in the while weblogic server is responding ti a HTTP request, returns an HTML page that displays either the HTTP error code.
    [code]
    <error-page>
    <error-code>105</error-code>
    <location>/jsp/error/PageNotFound.jsp</location>
    </error page>[/code]

    In the above example error-page tag specify the error code as 105 and location describes the location of the jsp page.

Advantages of web.xml file

  • The first benefit of the xml is we can write it in our won markup language. There is a no restricted to limited sets of tags. By defining our own tag we can create a markup language in terms of specific problem.
  • Searching the data is easy and efficient.
  • Completely compatible with Java™ and 100% portable.

Previous Tutorial : Servlet Example  || Next Tutorial : Servlet Context

Filed Under: Java EE Tagged With: Servlets Tutorials

Servlet Example

January 30, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • Servlets Tutorials
  • Servlets Interview Questions

Let us create a simple servlet example using Eclipse IDE. To create servlet application we need to use following steps:

    • Environment used:
      • JDK
      • Eclipse IDE
      • Apache Tomcat Server
      • Java-api
    • Open the Eclipse IDE and Go to File Menu ->New->Select Dynamic Web Project.
      Servlet Example 1
    • Enter Project Name click on Next.
    • Click on Generate web.xml deployment descriptor and click Finish.
    • Now under the project, click on Java Resources ->select src, right mouse click and select New->Package and type the name as javabeat.net.servlets
      Servlet Example 2
    • Now click on the package javabeat.net.servlets and New ->select Servlet
      Servlet Example 3
      Type the class name as ServletDemo and click Finish.
    • Now to add servlet-api jar to project we need to do following steps.
      • Right mouse click on Project name, select -> Properties ->select Java Build Path->Click on Add External JAR’s.
      • Select servlet-api.jar from Apache Tomcat directory.
      • Click on Open and click OK.

      Servlet Example 4

    • Add the following content to the ServletDemo.java:
      [code lang=”java”]
      package javabeat.net.servlets;

      import java.io.IOException;
      import java.io.PrintWriter;

      import javax.servlet.ServletException;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;

      /**
      * Servlet implementation class ServletDemo
      */
      public class ServletDemo extends HttpServlet {

      /**
      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
      */
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();

      out.println("<html>");
      out.println(" <head>");
      out.println(" <title>SimpleServlet</title>");
      out.println(" </head>");
      out.println(" <body>");
      out.println(" Hello, World");
      out.println(" </body>");
      out.println("</html>");
      }
      public void destroy(){
      System.out.println("shutting down….");
      }
      [/code]

      Details of the above code:

      • doGet method is used to sent specific amount of data.
      • ServletRequest is used to collect data which is available with client requested data.
      • ServletResponse object is used to generate the output content.
      • ServletException is used to intimate container that request has generated error. IOException is used if input and output error is detected when servlet handles GET request.
      • destroy () is used to clean up the resources that servlet have initialized.
    • Edit the web.xml and include the following content to it:
      [code lang=”xml”]
      <?xml version="1.0" encoding="UTF-8"?>
      <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
      <servlet>
      <servlet-name>ServletDemo</servlet-name>
      <servlet-class>javabeat.net.servlets.ServletDemo</servlet-class>
      </servlet>

      <servlet-mapping>
      <servlet-name>ServletDemo</servlet-name>
      <url-pattern>/ServletDemo</url-pattern>
      </servlet-mapping>
      </web-app>
      [/code]

    • Select the class ServletDemo right mouse click->Run As and select Run on Server, an output as shown below should be achieved:

Servlet Example 5

Previous Tutorial : Generic Servlet and Http Servlet  || Next Tutorial : Web.xml

Filed Under: Java EE Tagged With: Servlets Tutorials

Generic Servlet and Http Servlet

January 30, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • Servlets Tutorials
  • Servlets Interview Questions

Generic Servlet

GenericServlet is an abstract class defined in the Servlet API. For implementing class we need to implement all the methods in javax.servlet.Servlet Interface. Most of the Servlet objects do not need initializing and destroying operations but still we need to implement all the methods in javax.servlet.Servlet interface. To solve this problem, Servlet API provides javax.servlet.GenericServlet which implements ServletConfig interface and provides the implementation for the methods in this interface except the service method.

Methods of GenericServlet class

  • public void init (): This method is invoked by init (ServletConfig) method of GenericServlet. It is used to provide custom initializations without disturbing the initializations performed by GenericServlet in the init (ServletConfig) method.
  • public void init (ServletConfig) : It is used to initialize the servlet. It indicates Servlet instance in being placed into the service.
  • public abstract void service (ServletRequest request, ServletResponse response) : It is used to process user request. It is called by servlet container to intimate servlet about client request. It carries out single request from the client. ServletRequest object is used to collect data which is available with client requested data. ServletResponse object is used to generate the output content.
  • public void destroy (): It indicates servlet instance is being taken out of service. It is used to clean up any resources that servlet might have initialized.
  • public ServletConfig getServletConfig (): It returns ServletConfig interface reference. It is used to get configuration information from web.xml file.
  • public ServletContext getServletContext (): It returns ServletContext object reference. It is used to get configuration information from web.xml file. It is also used to set, get or remove attribute from web.xml file. If information is changed then there is no need to modify the servlet. So it is easy to maintain.
  • public String getInitParameter (String name): It returns the Servlet initialization parameter of the given name and if requested parameter is not available then it returns null.
  • public Enumeration String getInitParameternames (): It returns names of all Servlet initialization parameters defined in web.xml file.
  • public String getServletInfo (): It returns information about the respective servlet. For e.g. version, copyright.
  • public String getServletName (): It returns the Servlet instance name defined in Deployment Descriptor (web.xml).
  • public void log (String msg): It writes class name of servlet and specified message to a servlet log file.
  • public void log (String msg, Throwable t): It writes explanatory message and stack trace for a given Throwable exception to the servlet log file.

Http Servlet

HttpServlet is an abstract class defined in the Servlet API. It is abstract class with no abstract methods. Servlet container provides support for the Http protocol. It creates HttpServletRequest and HttpServletResponse objects if HTTP protocol is used for the sending request.
HttpServletRequest extends ServletRequest interface to provide request information for servlets. HttpServletResponse extends ServletResponse interface which provides functionality in sending response. HttpServlet is subtype of GenericServlet and does not override init, destroy and other methods. However, it implements the service () method which is abstract method in GenericServlet.

Methods of HttpServlet class

  • public void service (ServletRequest request, ServletResponse response): This method is used to process the user request. For each request the web container will issue unique request and response to the service method.
  • public void service (HttpServletRequest request, HttpServletResponse response): This method receives requests from the service () method. It dispatches requests depending on the request type.
  • protected void doGet (HttpServletRequest request, HttpServletResponse response): By using doGet () method we can send specific amount of data. If we use doGet () method data is shown in address bar. We must override doGet () method depending on type of request.
  • protected void doPost (HttpServletRequest request, HttpServletResponse response): We can send large amount of data by using doPost () method. By using this method data is not viewable in address bar. When we want to send secure data like passwords and other things doPost () method is used. We must override doPost () method depending on type of request.
  • protected void doDelete (HttpServletRequest request, HttpServletResponse response): It is used to delete files, web pages or documents from the server. If requests are formatted incorrectly then it will return HTTP “Bad Request” error.
  • protected void doPut (HttpServletRequest request, HttpServletResponse response): This method is used to put files, web pages or documents in the server means for uploading files on the server. If requests are formatted incorrectly then it will return HTTP “Bad Request” error.
  • protected void doTrace (HttpServletRequest request, HttpServletResponse response): This method is used for logging and debugging purpose. It can be used for testing the requested message. There is no need to override this method.
  • protected void doOptions (HttpServletRequest request, HttpServletResponse response): This method handles OPTIONS request. There is no need to override this method. It determines which HTTP method supported by server and returns correct header.
  • protected long getLastModified (HttpServletRequest request, HttpServletResponse response): It returns the time when request was last modified. This method should override GET request to return modification time of object.
  • protected void doHead (HttpServletRequest request, HttpServletResponse response): This method request header part of the GET request without the GET response body. It receives request from service method and handles the request. If HEAD requests are formatted incorrectly then it will return HTTP “Bad Request” error.

Previous Tutorial : Servlet LifeCycle  || Next Tutorial : Servlet Example

Filed Under: Java EE Tagged With: Servlets Tutorials

Servlet API

January 28, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • Servlets Tutorials
  • Servlets Interview Questions

The Servlet API is supported by all Servlet containers, such as Tomcat and Weblogic, etc. The Application Programming Interface (API) contains interface and classes to write a servlet program. The servlet API contains two packages as listed below:

  • javax.servlet
  • javax.servlet.http

Package javax.servlet

javax.servlet contains a number of classes and interface that allows the servlet to access the basic services provided by the servlet container. Following table lists the classes and interface of javax.servlet package:

Name Description Type
Servlet Defines methods that a servlet class must implement Interface
ServletConfig During initialization it allows the servlet container to pass information to a servlet. Interface
ServletContext Servlet Context is used to communicate with the servlet container to get the details of web application. Interface
ServletContextListener Receive notification about the changes made to the servlet context of the Web application. Interface
ServletRequest It is used to request client information to the servlet Interface
ServletResponse It is used by servlet to write the response content to the client. Interface
SingleThreadModel It uses the servlet instance to process only one request at a time. Interface
ServletRequestListener In the web component it receives a notification of the particular request that is coming in or out Interface
ServletRequestAttributeListener Notifies the changes in request attribute Interface
ServletContextAttributeListener The servlet context receives notification of the changes to be made on attribute list. Interface
Filter It is a reusable code that can transform the content of request, responses and the header information from one format to another. Interface
FilterChain Stores information about a chain of filters. Interface
FilterConfig It is used during the initialization. Interface
RequestDispatcher It is used to dispatch the request from one component to another. Interface
ServletContextEvent It gives the details of the life cycle events of the ServletContext object. Class
ServletRequestEvent Indicates that the request that is about to come in or go out of the web component. Class
ServletRequestWrapper Provides implementation of the ServletRequest interface to receive the request from a servlet. Class
ServletResponseWrapper Provides implementation of the ServletResponse interface to send response to the servlet. Class
ServletRequestAttributeEvent Servlet container invokes this method to indicate whether the attribute is to be added into the request, removed or replaced from the request. Class
ServletContextAttributeEvent Servlet container invokes this method to indicate whether the attribute is to be added into the context, removed or replaced from the context. Class
ServletInputStream Provides an input stream for reading a client requests. Class
ServletOutputStream Provides an output stream for writing servlet response to client. Class
GenericServlet Implements javax.servlet.Servlet interface and provides the basic implementation for the methods in this interface. Class
ServletException It is used to indicate that the request has generate an error. Class
UnavailableException Indicates that the servlet is currently unavailable to the process. Class

Package javax.servlet.http

The servlets using HTTP protocol are supported by the package javax.servlet.http. The list of classes and interface of javax.servlet.http package are listed in the following table:

Name Description Type
HttpServletRequest The web container provides implementation to this interface and encapsulates all HTTP based request information. Interface
HttpServletResponse Provide HTTP- specific functionality while sending a response. Interface
HttpSession It is a mechanism for storing client data across multiple HTTP requests. Interface
HttpSessionBindingListener Notifies when the objects of its implementation class is added or removed from the session. Interface
Cookie It is a file containing the information that is sent by web server to a client. Class
HttpSessionBindingEvent This method is used to indicate whether the object is added into the HttpSession object or removed from the HttpSession object. Class
HttpServlet Provides convenient methods for implementing for handling HTTP request. Class

Previous Tutorial : Introduction to Servlet  || Next Tutorial : Servlet LifeCycle

Filed Under: Java EE Tagged With: Servlets Tutorials

Introduction to Servlet

January 28, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • Servlets Tutorials
  • Servlets Interview Questions

What is Servlet ?

  • Servlets are an important component of a J2EE application. Servlets along with JavaServer Pages (JSP) and EJB modules can be termed as server-side J2EE component types.
  • Servlet is a Java Programming Language.
  • Servlets are used to create web applications.
  • Servlets are used to extend the applications hosted by web servers. Servlet runs in a J2EE application server

Common Gateway Interface (CGI) technology was used for dynamic content prior to introduction of Servlets.

Servlet Architecture

Following diagram shows the process of Servlets in a Web Application.
Servlet Architecture
The process can be summarized as follows:

  • A client sends a request to a Web Server, through a Web Browser.
  • The Web Server searches for the required Servlet and initiates it.
  • The Servlet then processes the client request and sends the response back to the server, which is then forwarded to the client.

Advantages of a Servlet

  • Servlets provide component based and platform-independent methods for building Web based applications.
  • Each Request is run in a separate thread ,so servlet request processing is faster than CGI.
  • Servlets overcomes the limitations of CGI program.
  • Servlets run on Java Virtual Machine and in any platform and it is simple to write.
  • Servlet are more powerful and the performance is better.
  • Servlets are platform-independent.
  • Servlet technology, in addition to improved performance, offers security, robustness, object orientation, and platform independence.
  • As mentioned in the definition of servlets are fully integrated with the Java language and its standard APIs. Hence JDBC for Java database connectivity is also integrated in it.
  • A servlet handles concurrent requests
  • Handling HTTP requests and send text and data back to the client is made easy by servlet request and response objects.

Disadvantages of a Servlet

  • Servlets often contain both business logic and presentation logic so it makes application difficult to understand.
  • You would need JRE to be installed to run a servlet program.

Next Tutorial : Servlet API

Filed Under: Java EE Tagged With: Servlets Tutorials

Exception Handling in JSP

January 25, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • JSP Tutorials
  • Recommended Books for Java Server Pages (JSP)

An exception is problem that occurs during the execution of any program. Exception can be categorized as:

  • Runtime Exception – It is an exception that occurs during running (executing) the program.
  • Checked Exception – It is a user error in the code. It cannot be necessarily detected by testing.
  • Errors – This cannot be handled either at compile time or runtime. It’s problem beyond the control of the user.

Exception Object is an instance of class java.lang.Throwable. Following are methods in the java.lang.Throwable class:

Code Description
public void printStackTrace() This method is used to print the http exception and its stack trace to the standard error stream.
public StackTraceElement[] getStackTrace This method returns an array of stack elements, each represent one stack frame. The zeroth element of the array will be present at the top of the stack.
public String toString() This method returns the textual representation of String object.
public Throwable getCause() This method returns the cause of exception if the cause is unknown.
public String getMessage() This method returns the detail message about the exception.

We need to use the tag to make JSP page exception handler. In the following example we have link to an error page as errorpage.jsp to set the exception that occurs during execution of the program.

Listing 1: example.jsp

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" errorPage="errorpage.jsp" import="java.util.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Calculation</title>
</head>
<body>
<% int a,b;
a=6;
b=4;

if(a<=b)
out.print("a is less then b");
else
{
throw new RuntimeException("Error condition!!!");
}

%>
</body>
</html>
[/code]

We have written an errorpage.jsp program. In which it include tag isErrorPage=”true”.

[code lang=”html”]
<%@ page language="java” pageEncoding="ISO-8859-1" import="java.util.*";
isErrorPage="true" %>

<html>
<head>
<title>Error Handling</title>
</head>
<body>
<h1>Hey some error occurred !!!</h1>

<p>Your page generates an exception</p>
<% exception.printStackTrace(response.getWriter()); %>
</body>
</html>
[/code]

Execute the JSP file example.jsp in Eclipse by selecting Run As > Run On Server and output would be as seen below:

jsp_exceptionhandling_demo

Previous Tutorial : Cookies Handling in JSP

Filed Under: Java EE Tagged With: JSP Tutorials

  • « Previous Page
  • 1
  • …
  • 9
  • 10
  • 11
  • 12
  • 13
  • …
  • 21
  • Next Page »

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved