Showing posts with label Servlets. Show all posts
Showing posts with label Servlets. Show all posts

September 28, 2011

Upload a text/binary file to the server using a Servlet

1) Create the UploadFile.html file in the WebContent folder of the web application.

<html>
<head>
<title>Upload File</title>
</head>
<body>

<form action="uploadServlet" enctype="multipart/form-data" method="post">
Specify a file to upload <br/>
<input type="file" name="datafile" size="40">
<br/>
<input type="submit" value="Upload">
</form>

</body>
</html>

2) Create the UploadServlet.java servlet class in the src folder of the web application.

package info.icontraining.servlets;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class UploadServlet extends HttpServlet {

   public void doPost(HttpServletRequest request, HttpServletResponse response) 
                     throws ServletException, IOException {
  
      PrintWriter out = response.getWriter();
      String contentType = request.getContentType();
  
      if ((contentType != null) 
               && (contentType.indexOf("multipart/form-data") >= 0)) {

         DataInputStream in = new DataInputStream(request.getInputStream());

         InputStream is = request.getInputStream();
         int formDataLength = request.getContentLength();
   
         // copy incoming bytes into a byte array
         byte dataBytes[] = new byte[formDataLength];
         int byteRead = 0;
         int totalBytesRead = 0;

         while (totalBytesRead < formDataLength) {
            byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
            totalBytesRead += byteRead;
         } 

         // retrieve uploaded filename
         String file = new String(dataBytes);
         String saveFile = file.substring(file.indexOf("filename=\"") + 10);
         saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
         saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,
                                          saveFile.indexOf("\""));
   
         // clip off the file content
         int lastIndex = contentType.lastIndexOf("=");
         String boundary = contentType.substring(lastIndex + 1, 
                                          contentType.length());
         int pos;
         pos = file.indexOf("filename=\"");
         pos = file.indexOf("\n", pos) + 1;
         pos = file.indexOf("\n", pos) + 1;
         pos = file.indexOf("\n", pos) + 1;
         int boundaryLocation = file.indexOf(boundary, pos) - 4;
         int startPos = ((file.substring(0, pos)).getBytes()).length;
         int endPos = ((file.substring(0, 
                              boundaryLocation)).getBytes()).length; 

         String outputfile = this.getServletContext().getRealPath(saveFile);
         FileOutputStream os = new FileOutputStream (outputfile);

         os.write(dataBytes, startPos, (endPos - startPos));
         os.flush();
         os.close();

         out.println("You have successfully uploaded the file");
      }
   }
}

3) Configure the servlet in the web.xml deployment descriptor present in the WebContent/WEB-INF folder of the web application

<servlet>
   <servlet-name>uploadServlet</servlet-name>
   <servlet-class>info.icontraining.servlets.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>uploadServlet</servlet-name>
   <url-pattern>/uploadServlet</url-pattern>
</servlet-mapping>

4) Test the code with the following URL in the browser. The file will be uploaded to the context root (folder) of the web application.

http://localhost:8080/WebAppName/UploadFile.html

Retrieve Request Headers in a Servlet

1) Create a Java Servlet class - HeaderTest.java - in the src folder of the Web Application

package info.icontraining.servlets;

import java.io.*;
import java.util.Enumeration;
import javax.servlet.*;
import javax.servlet.http.*;

public class HeaderTest extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response)
                     throws ServletException, IOException {
  
      PrintWriter out = response.getWriter();

      Enumeration e = request.getHeaderNames();
      String headerName = null;

      while(e.hasMoreElements()) {
         headerName = (String) e.nextElement();
         out.println(headerName + ": "); 
         out.println(request.getHeader(headerName) + "\n");
      }
  
      out.close();
   }
}

2) Configure the servlet in the web.xml deployment descriptor in the WebContent/WEB-INF folder

<servlet>
   <servlet-name>headerTest</servlet-name>
   <servlet-class>info.icontraining.servlets.HeaderTest</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>headerTest</servlet-name>
   <url-pattern>/headerTest</url-pattern>
</servlet-mapping>

3) Test the servlet with the following URL in the browser,

http://localhost:8080/WebAppName/headerTest

August 28, 2011

HttpSessionBindingListener Event Handler Implementation

The HttpSessionBindingListener interface is part of the Servlet API and lets us create an event-handler class that listens to events on an object that is bound to the session object as an attribute, namely, the binding and un-binding of the attribute object to the session.

The HttpSessionBindingEvent object that is passed as an argument to the listener methods provides a handle to the HttpSession object as well as access to the name and value object of the attribute.

1) Create an attribute class that implements the HttpSessionBindingListener interface methods, valueBound() and valueUnbound()

package info.icontraining.servlets;

import javax.servlet.http.*;

public class MyAttribute implements HttpSessionBindingListener {

   String id;
 
   public MyAttribute(String id) {
      this.id = id;
   }
 
   public String getId() {
      return this.id;
   }
 
   public void valueBound(HttpSessionBindingEvent hsbe) {
      HttpSession session = hsbe.getSession();
      System.out.println("Attribute added to session. Id = " + ((MyAttribute)hsbe.getValue()).getId());
   }

   public void valueUnbound(HttpSessionBindingEvent hsbe) {
      System.out.println("Attribute removed from session. Id = " + ((MyAttribute)hsbe.getValue()).getId());
   }
}

2) For the HttpSessionBindingListener class, configuration in the web.xml with the <listener> element is not required.

3) Create a servlet class that adds and removes the attribute to and from the session,

package info.icontraining.servlets;

import java.io.*;
import javax.servlet.http.*;

public class SessionServlet extends HttpServlet {

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

        HttpSession session = request.getSession();
        
        session.setAttribute("newAttr", new MyAttribute("20"));
        session.removeAttribute("newAttr");
   }
}

4) Configure the servlet in the web.xml deployment descriptor,

<servlet>
   <servlet-name>sessionServlet</servlet-name>
   <servlet-class>info.icontraining.servlets.SessionServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>sessionServlet</servlet-name>
   <url-pattern>/sessionServlet</url-pattern>
</servlet-mapping>

5) Test the example with the following URL in the browser, and check the server/console log

http://localhost:8080/WebAppName/sessionServlet

ServletRequestAttributeListener Event Handler Implementation

The ServletRequestAttributeListener interface is part of the Servlet API and lets us create an event-handler class that listens to events on the ServletRequest object, namely, the addition, removal and replacement of attributes on the request object.

The ServletRequestAttributeEvent Event object that is passed as an argument to the listener methods provides a handle to the ServletRequest object and the name and value object of the attribute.

1) Create a class that implements the ServletRequestAttributeListener interface methods, attributeAdded(), attributeRemoved() and attributeReplaced()

package info.icontraining.servlets.listeners;

import javax.servlet.*;
import javax.servlet.http.*;

public class MyRequestAttributeListener implements ServletRequestAttributeListener {

   public void attributeAdded(ServletRequestAttributeEvent srae) {
      System.out.println("New request attribute added");
      HttpServletRequest request = (HttpServletRequest) srae.getServletRequest();
      System.out.println("Name of Attribute added: " + srae.getName());
      System.out.println("Value of Attribute added: " + srae.getValue());
   }

   public void attributeRemoved(ServletRequestAttributeEvent srae) {
      System.out.println("Request attribute Removed");
      System.out.println("Name of Attribute removed: " + srae.getName());
      System.out.println("Value of Attribute removed: " + srae.getValue());
   }

   public void attributeReplaced(ServletRequestAttributeEvent srae) {
      System.out.println("Request attribute Replaced");
      System.out.println("Name of Attribute replaced: " + srae.getName());
      System.out.println("Value of Attribute replaced: " + srae.getValue());
   }
}

2) Configure the listener in the web.xml deployment descriptor,

<listener>
   <listener-class>    
      info.icontraining.servlets.listeners.MyRequestAttributeListener
   </listener-class>
</listener>

3) Create a servlet class that handles a request,

package info.icontraining.servlets;

import java.io.*;
import javax.servlet.http.*;

public class RequestListenerServlet extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
      request.setAttribute("attr1", "value1");
      request.setAttribute("attr1", "value2");
      request.removeAttribute("attr1");
   }
}

4) Configure the servlet in the web.xml deployment descriptor,

<servlet>
   <servlet-name>requestListenerServlet </servlet-name>
   <servlet-class>info.icontraining.servlets.RequestListenerServlet </servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>requestListenerServlet </servlet-name>
   <url-pattern>/RequestListenerServlet </url-pattern>
</servlet-mapping>

5) Test the example with the following URL in the browser, and check the server/console log

http://localhost:8080/WebAppName/requestListenerServlet

ServletRequestListener Event Handler Implementation

The ServletRequestListener interface is part of the Servlet API and lets us create an event-handler class that listens to events on the ServletRequest object, namely, the request object creation and destruction.

TheServletRequest Event object that is passed as an argument to the 2 listener methods provides a handle to the ServletRequest object.

1) Create a class that implements the ServletRequestListener interface methods, requestInitialized() and requestDestroyed()

package info.icontraining.servlets.listeners;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;

public class MyServletRequestListener implements ServletRequestListener{

   public void requestDestroyed(ServletRequestEvent sre) {
      System.out.println("Request serviced & object destroyed by container");
   }

   public void requestInitialized(ServletRequestEvent sre) {
      System.out.println("New Request received and object created");
      HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
      // do something when a new request arrives
   }
}
2) Configure the listener in the web.xml deployment descriptor,

<listener>
   <listener-class>    
      info.icontraining.servlets.listeners.MyServletRequestListener
   </listener-class>
</listener>

3) Create a servlet class that handles a request,

package info.icontraining.servlets;

import java.io.*;
import javax.servlet.http.*;

public class RequestListenerServlet extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
      request.setAttribute("attr1", "value1");
      request.setAttribute("attr1", "value2");
      request.removeAttribute("attr1");
   }
}

4) Configure the servlet in the web.xml deployment descriptor,

<servlet>
   <servlet-name>requestListenerServlet </servlet-name>
   <servlet-class>info.icontraining.servlets.RequestListenerServlet </servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>requestListenerServlet </servlet-name>
   <url-pattern>/RequestListenerServlet </url-pattern>
</servlet-mapping>

5) Test the example with the following URL in the browser, and check the server/console log

http://localhost:8080/WebAppName/requestListenerServlet

HttpSessionAttributeListener Event Handler Implementation

The HttpSessionAttributeListener interface is part of the Servlet API and lets us create an event-handler class that listens to events on the HttpSession object, namely, the addition, removed and replacement of attributes on the HttpSession object.

The HttpSessionBindingEvent object that is passed as an argument to the 2 listener methods provides a handle to the HttpSession object as well as access to the name and value object of the attribute.

1) Create a class that implements the HttpSessionAttributeListener interface methods, attributeAdded(), attributeRemoved() and attributeReplaced()

package info.icontraining.servlets.listeners;

import javax.servlet.http.*;

public class MySessionAttrListener implements HttpSessionAttributeListener {

   public void attributeAdded(HttpSessionBindingEvent hsbe) {
      System.out.println("New Session attribute added");
      HttpSession session = hsbe.getSession();
      System.out.println("Name of Attribute added: " + hsbe.getName());
      System.out.println("Value of Attribute added: " + hsbe.getValue());
   }

   public void attributeRemoved(HttpSessionBindingEvent hsbe) {
      System.out.println("Session attribute Removed");
      System.out.println("Name of Attribute removed: " + hsbe.getName());
      System.out.println("Value of Attribute removed: " + hsbe.getValue());
   }

   public void attributeReplaced(HttpSessionBindingEvent hsbe) {
      System.out.println("Session attribute replaced");
      System.out.println("Name of Attribute replaced: " + hsbe.getName());
      System.out.println("Value of Attribute replaced: " + hsbe.getValue());
   } 
}
2) Configure the listener in the web.xml deployment descriptor,

<listener>
   <listener-class>    
      info.icontraining.servlets.listeners.MySessionAttrListener
   </listener-class>
</listener>

3) Create a servlet class that starts a session and adds, replaces and removes a session attribute,

package info.icontraining.servlets;

import java.io.*;
import javax.servlet.http.*;

public class SessionServlet extends HttpServlet {

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

      HttpSession session = request.getSession();
      session.setAttribute("attr1", "value1");
      session.setAttribute("attr1", "value2");
      session.removeAttribute("attr1");
      session.invalidate();
   }
}

4) Configure the servlet in the web.xml deployment descriptor,

<servlet>
   <servlet-name>sessionServlet</servlet-name>
   <servlet-class>info.icontraining.servlets.SessionServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>sessionServlet</servlet-name>
   <url-pattern>/sessionServlet</url-pattern>
</servlet-mapping>

5) Test the example with the following URL in the browser, and check the server/console log

http://localhost:8080/WebAppName/sessionServlet

HttpSessionListener Event Handler Implementation

The HttpSessionListener interface is part of the Servlet API and lets us create an event-handler class that listens to events on the HttpSession object, namely, the HttpSession object creation and destruction.

The HttpSessionEvent object that is passed as an argument to the 2 listener methods provides a handle to the HttpSession object in order to set any attributes.

1) Create a class that implements the HttpSessionListener interface methods, sessionCreated() and sessionDestroyed()

package info.icontraining.servlets.listeners;

import javax.servlet.http.*;

public class MySessionListener implements HttpSessionListener {

   public void sessionCreated(HttpSessionEvent se) {
      System.out.println("Created new session with client");
      HttpSession session = se.getSession();
      System.out.println("Printing Session Id: " + session.getId());
   }

   public void sessionDestroyed(HttpSessionEvent se) {
      System.out.println("Session "+ se.getSession().getId() +" ended");
   }
}

2) Configure the listener in the web.xml deployment descriptor,

<listener>
   <listener-class>    
      info.icontraining.servlets.listeners.MySessionListener
   </listener-class>
</listener>

3) Create a servlet class that starts a session

package info.icontraining.servlets;

import java.io.*;
import javax.servlet.http.*;

public class SessionServlet extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
      HttpSession session = request.getSession();
      session.invalidate();
   }
}

4) Configure the servlet in the web.xml deployment descriptor,

<servlet>
   <servlet-name>sessionServlet</servlet-name>
   <servlet-class>info.icontraining.servlets.SessionServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>sessionServlet</servlet-name>
   <url-pattern>/sessionServlet</url-pattern>
</servlet-mapping>

5) Test the example with the following URL in the browser, and check the server/console log

http://localhost:8080/WebAppName/sessionServlet

ServletContextAttributeListener Event Handler Implementation

The ServletContextAttributeListener interface is part of the Servlet API and lets us create an event-handler class that listens to events on the ServletContext object, namely, addition, removal and replacement of attributes on the ServletContext.

The ServletContextAttributeEvent object that is passed as an argument to the 2 listener methods provides a handle to the ServletContext object and the name and value object of the attribute.

1) Create a class that implements the ServletContextAttributeListener interface methods, attributeAdded(), attributeReplaced() and attributeRemoved()

package info.icontraining.servlets.listeners;

import javax.servlet.*;

public class MyContextAttributeListener implements ServletContextAttributeListener {

   public void attributeAdded(ServletContextAttributeEvent scae) {
      System.out.println("New Context attribute added");
      ServletContext sc = scae.getServletContext();
      System.out.println("Name of Attribute added: " + scae.getName());
      System.out.println("Value of Attribute added: " + scae.getValue());
   }

   public void attributeRemoved(ServletContextAttributeEvent scae) {
      System.out.println("Context attribute removed");
      System.out.println("Name of Attribute removed: " + scae.getName());
      System.out.println("Value of Attribute removed: " + scae.getValue());
   }

   public void attributeReplaced(ServletContextAttributeEvent scae) {
      System.out.println("Context attribute replaced");
      System.out.println("Name of Attribute replaced: " + scae.getName());
      System.out.println("Value of Attribute replaced: " + scae.getValue());
   }
}


2) Configure the listener in the web.xml deployment descriptor,

<listener>
   <listener-class>    
      info.icontraining.servlets.listeners.MyContextAttributeListener
   </listener-class>
</listener>

3) Create a servlet class that adds, replaces and removes an attribute from the ServletContext

package info.icontraining.servlets;

import java.io.*;

import javax.servlet.ServletContext;
import javax.servlet.http.*;

public class ContextAttribute extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
      ServletContext sc = getServletContext();
      sc.setAttribute("attr1", "value1");
      sc.setAttribute("attr1", "value2");
      sc.removeAttribute("attr1");  
   }
}

4) Configure the servlet in the web.xml deployment descriptor,

<servlet>
   <servlet-name>contextAttribute</servlet-name>
   <servlet-class>info.icontraining.servlets.ContextAttribute</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>contextAttribute</servlet-name>
   <url-pattern>/contextAttribute</url-pattern>
</servlet-mapping>

5) Test the example with the following URL in the browser, and check the server/console log

http://localhost:8080/WebAppName/contextAttribute

ServletContextListener Event Handler Implementation

The ServletContextListener interface is part of the Servlet API and lets us create an event-handler class that listens to events on the ServletContext object, namely, the ServletContext object creation/initialization and the ServletContext object destruction.

The ServletContextEvent object that is passed as an argument to the 2 listener methods provides a handle to the ServletContext object in order to set any attributes.

1) Create a class that implements the ServletContextListener interface methods, contextInitialized () and contextDestroyed()

package info.icontraining.servlets.listeners;

import javax.servlet.*;

public class MyServletContextListener implements ServletContextListener {
   public void contextInitialized(ServletContextEvent sce) {
      System.out.println("Servlet Context created");

      // code to acquire resource, to set as 
      // attr in application scope

      ServletContext sc = sce.getServletContext();
      sc.setAttribute("attr-name", "attr-value");
   }

   public void contextDestroyed(ServletContextEvent sce) {
      // any clean-up code
      System.out.println("Servlet Context destroyed");
   }
}

2) Configure the listener in the web.xml deployment descriptor,

<listener>
   <listener-class>    
      info.icontraining.servlets.listeners.MyServletContextListener
   </listener-class>
</listener>

3) Deploy the application to the Application Server/ Web Container and check in the server/console log for the following output,

INFO  [STDOUT] Servlet Context created

June 18, 2011

Difference between addHeader and setHeader methods on the HttpServletResponse

Note: To test this example, use the Firefox browser with the 'Live HTTP Headers' add-on of Mozilla installed in firefox. Access this link from firefox - https://addons.mozilla.org/en-US/firefox/addon/live-http-headers/

The setHeader() method on the HttpServletResponse object allows setting a new header/value pair in the HTTP Response message. If a header with the same name already exists, the method will overwrite the value with the new value passed in the method.

The addHeader() method, however, will not overwrite an existing header value if a header with the same name already exists. It instead just associates this value with the header as an additional value making the header have multiple values. If the header does not already exist, the addHeader() works just like the setHeader().

1) Create the HeaderTest.java servlet class within the src folder of the web application

package info.icontraining.servlets;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HeaderTest extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
  
      PrintWriter out = response.getWriter();
      response.setHeader("h1", "Hello");
      response.addHeader("h1", "Bye");
        
      response.setHeader("h2", "Hello");
      response.addHeader("h2", "Bye");
      response.setHeader("h2", "Hi");

      out.close();
   }
}


2) Configure the servlet in the web.xml file of the web application present in the WebContent/WEB-INF folder

<servlet>
   <servlet-name>headerTest</servlet-name>
   <servlet-class>info.icontraining.servlets.HeaderTest</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>headerTest</servlet-name>
   <url-pattern>/headers</url-pattern>
</servlet-mapping>


3) Test the code by accessing the following URL in the browser. Check the response headers in the screen for the Live HTTP Headers add-on for firefox.

http://localhost:8080/WebAppName/headers

Context or Application attributes on the ServletContext object

Context attributes, also called Application attribute (since context attributes are said to have applicaiton scope) are set on the ServletContext object of the Servlet API.

1) Create a Servlet class, ServletOne.java in the src folder of the web application. This Servlet contains code to set an attribute in the Application scope.

package info.icontraining.servlets;

import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;

public class ServletOne extends HttpServlet {
 
   public void doGet (HttpServletRequest req, HttpServletResponse res)
     throws ServletException, IOException {
   
      ServletContext sc = getServletContext();
      sc.setAttribute("testAttribute", "testValue");
   
      PrintWriter out = res.getWriter();
   
      out.println("<html><body>");
      out.println("Context Attribute Set. <br/>");
      out.print("<a href=\"two\">");
      out.println("Click to access ServletTwo</a>");
      out.println("</body></html>");
   }
}


2) Create a second Servlet Class, ServletTwo.java also in the src folder of the web application. This servlet procures the attribute set in the Application scope and prints its value.

package info.icontraining.servlets;

import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;

public class ServletTwo extends HttpServlet {
 
   public void doGet (HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
   
      ServletContext sc = getServletContext();
      String value = (String) sc.getAttribute("testAttribute");
   
      PrintWriter out = res.getWriter();
   
      out.println("Context Attribute procured");
      out.println("Value is = " + value);
   }
}


3) Configure both servlets in the web.xml file present within the WebContent/WEB-INF folder of the web application

<servlet>
   <servlet-name>servletOne</servlet-name>
   <servlet-class>info.icontraining.servlets.ServletOne</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>servletOne</servlet-name>
   <url-pattern>/one</url-pattern>
</servlet-mapping>
  
<servlet>
   <servlet-name>servletTwo</servlet-name>
   <servlet-class>info.icontraining.servlets.ServletTwo</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>servletTwo</servlet-name>
   <url-pattern>/two</url-pattern>
</servlet-mapping>


4) Test the code by typing the following URL in the browser

http://localhost:8080/WebAppName/one

Redirect request with the sendRedirect() method on HttpServletResponse

The sendRedirect() method on the response object (HttpServletResponse) redirects a request received by the Servlet / web component to another Servlet / web component or URL. The URL may be for a component within the same web application or outside it.

This is in contrast to the RequestDispatcher 's request dispatching that can only internally dispatch a request from one servlet / web component to another one within the same web application.

1) Create a servlet class that contains the re-direction code, in the src folder of the web application

package info.icontraining.servlets;

import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;

public class YahooServlet extends HttpServlet {

   public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    
      res.sendRedirect("http://www.yahoo.com");
   }
}


2) Configure the servlet within the web.xml file present in the WebContent/WEB-INF folder of the web application

<servlet>
   <servlet-name>yahooServlet</servlet-name>
   <servlet-class>info.icontraining.servlets.YahooServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>yahooServlet</servlet-name>
   <url-pattern>/yahoo</url-pattern>
</servlet-mapping>


3) Test the code by typing the following URL in the browser,

http://localhost:8080/WebAppName/yahoo

June 12, 2011

Writing binary content to the HTTP response from a Servlet

The getWriter() method on the HttpServletResponse object returns a PrintWriter object which is used for writing text data to the response. When binary data has to be returned in the response (for example, a file download), the getOutputStream() method may be invoked on the response object. The following code example demonstrates the same.

1) Create the Servlet class in the src folder of the web application as follows,

package info.icontraining.servlets;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class BinaryResponseServlet extends HttpServlet{

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

      response.setContentType("application/pdf");

      InputStream is = getServletContext().getResourceAsStream("/WEB-INF/test.pdf");
      OutputStream outs = response.getOutputStream();

      int inByte = 0;
      while ((inByte = is.read()) != -1) {   
         outs.write(inByte);
      }

      outs.flush();
      outs.close();
      is.close();
   }
}


2) Configure the servlet in the web.xml file present in the WebContent/WEB-INF folder of the web application

<servlet>
    <servlet-name>binaryResponse</servlet-name>
    <servlet-class>info.icontraining.servlets.BinaryResponseServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>binaryResponse</servlet-name>
    <url-pattern>/downloadFile</url-pattern>
</servlet-mapping>


3) Add the binary file (in this case any pdf file renamed as test.pdf) to the WebContent/WEB-INF folder of the web application.

4) Test the servlet by typing the following URL in the browser

http://localhost:8080/WebAppName/downloadFile

April 10, 2011

Set a Cookie in a Servlet

1) Create the CookieDemo.java Servlet class with code to set a cookie header in the response

package info.icontraining.servlets;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class CookieDemo extends HttpServlet {
 
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  
      Cookie cookie = new Cookie("cookiedemo","cookievalue");
      response.addCookie(cookie);
      PrintWriter out = response.getWriter();
      response.setContentType("text/html");
      out.println("Sending response with Cookie<br/>");
      out.println("<a href=\"cookieDemo2\">Click Link</a>");
   }
}


2) Create the CookieDemo2.java Servlet class with code to retrieve from the request that was set/sent in the previous Servlet.

import javax.servlet.http.*;
import java.io.*;

public class CookieDemo2 extends HttpServlet {
 
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  
      PrintWriter out = response.getWriter();
      Cookie[] cookies = request.getCookies();
  
      for (Cookie c: cookies) {
         out.println("Cookie Name is " + c.getName() + "<br/>");
         out.println("Cookie Value is " + c.getValue() + "<br/><br/>");
      }

      response.setContentType("text/html");
   }
}


3) Configure both servlets in the web.xml

<servlet>
   <servlet-name>CookieDemo</servlet-name>
   <servlet-class>info.icontraining.servlets.CookieDemo</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>CookieDemo</servlet-name>
   <url-pattern>/cookieDemo</url-pattern>
</servlet-mapping>

<servlet>
   <servlet-name>CookieDemo2</servlet-name>
   <servlet-class>info.icontraining.servlets.CookieDemo2</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>CookieDemo2</servlet-name>
   <url-pattern>/cookieDemo2</url-pattern>
</servlet-mapping>


4) Test the code with the following URL in the browser

http://localhost:8080/WebAppName/cookieDemo

Forwarding request from Servlet with RequestDispatcher

The RequestDispatcher object is used to forward a request from one web component (Servlet or JSP) to another web component. The forward() method in the RequestDispatcher class does the actual forwarding.

1) Write the code for setting the request attribute and request forward in the FirstServlet.java

package info.icontraining.servlets;

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.servlet.*;

public class FirstServlet extends HttpServlet {

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

      System.out.println("Received request in FirstServlet");
      System.out.println("Setting  attribute in FirstServlet");
      request.setAttribute("test-attribute", "test-attribute-value");

      RequestDispatcher rd = request.getRequestDispatcher("/secondServlet");
      System.out.println("Forwarded request to SecondServlet");
      
      rd.forward(request, response);
   }
}


2) Write the code to retrieve the request attribute in the code for SecondServlet.java

package info.icontraining.servlets;

import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;

public class SecondServlet extends HttpServlet implements Servlet {
   
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

      System.out.println("Received request in SecondServlet");
      String value = (String) request.getAttribute("test-attribute");
      PrintWriter out = response.getWriter();
      out.println("Retrieving attribute in Second Servlet: " + value);
   }
}


3) Configure both the servlets in the web.xml

<servlet>
   <servlet-name>FirstServlet</servlet-name>
   <servlet-class>info.icontraining.servlets.FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>FirstServlet</servlet-name>
   <url-pattern>/firstServlet</url-pattern>
</servlet-mapping>

<servlet>
   <servlet-name>SecondServlet</servlet-name>
   <servlet-class>info.icontraining.servlets.SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>SecondServlet</servlet-name>
   <url-pattern>/secondServlet</url-pattern>
</servlet-mapping>


4) Access the following URL through the browser to test the code

http://localhost:8080/WebAppName/firstServlet

February 27, 2011

Servlets - Session Management with URL Rewriting

Enable session management through URL rewriting by encoding all the response URLs for the exercise posted at this link - http://www.javaissues.com/2011/02/servlets-session-management-example.html

1) Servlet 1 - Code here: http://www.javaissues.com/2011/02/servlets-handling-get-request.html

2) Servlet 2

package info.icontraining.servlets;

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

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

public class PostServlet extends HttpServlet {
 
   public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {

      PrintWriter out = response.getWriter();
       
      String username = request.getParameter("user");
      String passwd = request.getParameter("pass");
      out.println("<html>");
      out.println("<head><title>Post Servlet Example</title></head>"); 
      out.println("<body><h1>");
       
      if (username.equals("dinesh") && passwd.equals("dinesh")) {

         out.println("Welcome " + username +"!<br/><br/>");
         HttpSession session = request.getSession();
         session.setAttribute("username",username);
         out.println("<a href=\"" + response.encodeURL("linkedServlet") + "\">Click here</a>");

      } else {
         out.println("Invalid username/passwd. Go back and try again.");
      }
       
      out.println("</h1></body></html>");
      out.close();
   }
}


3) Servlet 3 - Code here (of Servlet 3): http://www.javaissues.com/2011/02/servlets-session-management-example.html


web.xml configuration for all 3 servlets same as for the example at this link - http://www.javaissues.com/2011/02/servlets-session-management-example.html


To test Session Management with URL rewriting disable cookies in your browser and access the servlets starting with Servlet 1. Observe URL in browser address bar for re-written URL

Servlets - Session Management Example

After user authentication, start a session. Display "Welcome [username]" as the response along with a link that hits another Servlet. From this other servlet, send the response "You are [username]" by retrieving the username information from the session as an attribute.


1) Servlet 1: Code here - http://www.javaissues.com/2011/02/servlets-handling-get-request.html


2) Servlet 2 - PostServlet.java

package info.icontraining.servlets;

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

import javax.servlet.http.*;

public class PostServlet extends HttpServlet {
 
   public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
      PrintWriter out = response.getWriter();
       
      String username = request.getParameter("user");
      String passwd = request.getParameter("pass");
      out.println("<html>");
      out.println("<head><title>Post Servlet Example</title></head>"); 
      out.println("<body><h1>");
       
      if (username.equals("dinesh") && passwd.equals("dinesh")) {

         out.println("Welcome " + username +"!<br/><br/>");
         HttpSession session = request.getSession();
         session.setAttribute("username",username);
         out.println("<a href=\"linkedServlet\">Click here</a>");

      } else {
         out.println("Invalid username/passwd. Go back and try again.");
      }
       
      out.println("</h1></body></html>");
      out.close();
   }
}


3) Servlet 3 - LinkedServlet.java

package info.icontraining.servlets;

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

import javax.servlet.http.*;

public class LinkedServlet extends HttpServlet {
 
   public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
      PrintWriter out = response.getWriter();
       
      out.println("<html>");
      out.println("<head><title>Session Management Example</title></head>"); 
      out.println("<body><h1>");
             
      HttpSession session = request.getSession();
      String username = (String)session.getAttribute("username");
      out.println("You are " + username +"!");
       
      out.println("</h1></body></html>");
      out.close();
   }
}


web.xml configuration for Servlets 2 & 3 (for configuration of Servlet 1, go to link specified above)

<servlet>
    <servlet-name>postServlet</servlet-name>
    <servlet-class>info.icontraining.servlets.PostServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>postServlet</servlet-name>
    <url-pattern>/formurl</url-pattern>
</servlet-mapping>
 
<servlet>
    <servlet-name>linkedServlet</servlet-name>
    <servlet-class>info.icontraining.servlets.LinkedServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>linkedServlet</servlet-name>
    <url-pattern>/linkedServlet</url-pattern>
</servlet-mapping>

Servlet Initialization Parameters & Context Initialization Parameters

In one of the servlets' configuration, configure a Servlet Initialization parameter and retrieve this parameter value in the servlet code. Configure a Context Initialization parameter and retrieve it in any servlet.

package info.icontraining.servlets;

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 InitParametersDemoServlet extends HttpServlet {
 
   public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
      PrintWriter out = response.getWriter();
       
      String servletInitParam = getServletConfig().getInitParameter("initParam");
      String contextInitParam = getServletContext().getInitParameter("contextParam");
       
      out.println("<html><body>");
       
      out.println("<p>Servlet Init Parameter Value = ");
      out.println(servletInitParam + "<br/><br/>");
       
      out.println("Context Init Parameter Value = ");
      out.println(contextInitParam + "<br/><br/>");
       
      out.println("</p></body></html>");
      out.close();
   }
}


Configuration for the servlet (along with Servlet Initialization Parameter) and the Context Initialization parameter,

<servlet>
   <servlet-name>initParametersDemoServlet</servlet-name>
   <servlet-class>info.icontraining.servlets.InitParametersDemoServlet</servlet-class>
   <init-param>
      <param-name>initParam</param-name>
      <param-value>initValue</param-value>
   </init-param>
</servlet>
<servlet-mapping>
   <servlet-name>initParametersDemoServlet</servlet-name>
   <url-pattern>/initParameters</url-pattern>
</servlet-mapping>
 
<context-param>
   <param-name>contextParam</param-name>
   <param-value>contextValue</param-value>
</context-param>


URL in browser:

http://localhost:8080/WebAppName/initParameters

February 26, 2011

Servlets - Overriding init & destroy methods

Override the init() and destroy() methods of a Java Servlet program

package info.icontraining.servlets;

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 InitDemoServlet extends HttpServlet {
 
   public void init() {
      System.out.println("Inside init method");
   }
 
   public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
      System.out.println("Inside doGet");
   }
 
   public void destroy() {
      System.out.println("Inside destroy method");
   }
}


Adding Servlet configuration in the web.xml

<servlet>
    <servlet-name>initDemoServlet</servlet-name>
    <servlet-class>info.icontraining.servlets.InitDemoServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>initDemoServlet</servlet-name>
    <url-pattern>/initDemo</url-pattern>
</servlet-mapping>


How to test:

1) Open URL: http://localhost:8080/WebAppName/initDemo

2) Check Server console log, it should show "Inside Init method" and "Inside doGet".

3) Refresh browser screen, now server console should show only "Inside doGet". Refresh several more times.

4) Stop the server, search through the server log for "Inside destroy method".

Servlets - Handling a POST request

Write a servlet to handle a POST request. This request should procure the form data on the server side and send an HTML response that prints "Welcome [username]" or "Incorrect username/password" based on whether login was successful or a failure.

package info.icontraining.servlets;

import java.io.*;
import javax.servlet.http.*;

public class PostServlet extends HttpServlet {
 
   public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
      PrintWriter out = response.getWriter();
       
      String username = request.getParameter("user");
      String passwd = request.getParameter("pass");
      out.println("<html>");
      out.println("<head><title>Post Servlet Example</title></head>"); 
      out.println("<body><h1>");
       
      if (username.equals("dinesh") && passwd.equals("dinesh")) {
         out.println("Welcome " + username);
      } else {
         out.println("Incorrect username/password.");
      }
       
      out.println("</h1></body></html>");
      out.close();
   }
}

Add the following configuration to the web.xml,

<servlet>
   <servlet-name>postServlet</servlet-name>
   <servlet-class>info.icontraining.servlets.PostServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>postServlet</servlet-name>
   <url-pattern>/formurl</url-pattern>
</servlet-mapping>


The servlet can be accessed through the GET Servlet at this URL