Showing posts with label Servlet API. Show all posts
Showing posts with label Servlet API. 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

Servlet Filter - Hello World Example

1) Create a MyFilter.java filter class in the src folder of the Web Application

package info.icontraining.filters;

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

public class MyFilter implements Filter {

   private FilterConfig filterConfig;
 
   public void init(FilterConfig filterConfig) throws ServletException {
      this.filterConfig = filterConfig;
   }
 
   public void destroy() {
      System.out.println("Clean-up code in Filter");
   }

   public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  
      System.out.println("Filter processing request");
      chain.doFilter(request, response);
      System.out.println("Filter processing response");
   }
}

2) Configure the filter in the web.xml deployment description in the WebContent/WEB-INF folder, as follows,

<filter>
   <filter-name>myFilter</filter-name>
   <filter-class>info.icontraining.filters.MyFilter</filter-class>
</filter>
<filter-mapping>
   <filter-name>myFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

This filter will intercept requests to all URLs (of servlets, JSPs, etc.) in the Web Application

3) Test the filter by accessing any valid URL (servlet URL or JSP) of the Web Application, and check the server console log,

http://localhost:8080/WebAppName/anyValidURL

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

July 5, 2011

Accessing Servlet API objects in a Struts2 action

Accessing through the ActionContext object

The ActionContext object can be procured anywhere within a Struts2 application by invoking a static method on the ActionContext class as follows,

ActionContext context = ActionContext.getContext();

The ActionContext object does not give direct access (references) to the Servlet API objects such as HttpServletRequest, HttpSession or ServletContext - instead it exposes the relevant attributes/parameters as plain Map objects. This prevents the binding of the Struts2 action classes to the Servlet API.

Accessing through the servlet-config interceptor

The servlet-config interceptor can cleanly inject the Servlet API objects into the action classes. The action class must implement certain interfaces and therefore contain implementation of the setter methods from the interfaces.

Following are the interfaces that the action classes can implement in order to get hold of the Servlet API objects,

interface ServletContextAware - sets the ServletContext
interface ServletRequestAware - sets the HttpServletRequest
interface ServletResponseAware - sets the HttpServletResponse
interface ParameterAware - sets a map of the request parameters
interface RequestAware - sets a map of the request attributes
interface SessionAware - sets a map of the session attributes
interface ApplicationAware - sets a map of the application attributes

For example, in the following action class, this is how the ServletContext can be injected.

package info.icontraining.struts2;

import javax.servlet.ServletContext;
import org.apache.struts2.util.ServletContextAware;

public class HelloWorld implements ServletContextAware {
 
   public String execute()  {
      // some code here
      return "success";
   }
     private ServletContext sc;
  
   public void setServletContext(ServletContext sc) {
      this.sc = sc;
   }
}