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

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

  • « Previous Page
  • 1
  • 2
  • 3

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