Tag: JSP/Servlets

Simplified FileUpload using Servlet3.0 in JBoss AS7

Hi,

Uploading files through web applications is one of the most important job of most of the applications. Earlier to servlet3.0 specification we used to do it manually, But now from Servlet 3.0 specification a very useful feature of file upload is associated. Servlet3.0 specification introduced annotation @javax.servlet.annotation.MultipartConfig and the API javax.servlet.http.Part to simplify the file upload.

Here “javax.servlet.http.Part” represents a part or form item that was received within a multipart/form-data POST request. And the @MultipartConfig indicating that instances of the Servlet expect requests that conform to the multipart/form-data MIME type. Servlets annotated with MultipartConfig may retrieve the Part components of a given multipart/form-data request by calling getPart or getParts.

In this example we will see how to uload files using the @MultipartConfig annotation and how to use the javax.servlet.http.Part API.

Step1). Our application is going to upload the files inside the server location “${jboss.server.base.dir}/upload” directory so make sure that we create a directory with name “upload” inside “${jboss.server.base.dir}”, Which means the following path should exist: “/home/userone/jboss-as-7.1.0.CR1b/standalone/upload”

Step2). Create a Directory somewhere inside your file system where we can create our web application. Suppose i am creating a directory as “/home/userone/EE6_FileUpload_Servlet” and the create a subdirectory with name “src” inside “/home/userone/EE6_FileUpload_Servlet”

Step3). We will place a simple “index.jsp” file inside “/home/userone/EE6_FileUpload_Servlet/src” directory which will present a html form to the user so that user can browse & upload the desired file.

<html>
    <head>
        <title>FileUpload Demo</title>
    </head>
    <body bgcolor="maroon" text="white">
      <center>
        <h1>FileUpload Demo Using Servlet3.0 in JBoss AS7</h1>
        <form id="formId" action="FileUploadServlet" enctype="multipart/form-data" method="post">
          <input type="file" id="FileUploadId" name="***Upload***"  /> 
          <input type="submit" id="uploadButtonId" value="Upload Now" />
        </form>   
      </center>
    </body>
</html>

Step4). Now we will write the “FileUploadServlet.java” program inside the “/home/userone/EE6_FileUpload_Servlet/src” directory which will be responsible for uploading the file provided by end user on the JBoss Server box.

package servlets;

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

//IOStream
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

//Servlet3.0 specific annotations 
import javax.servlet.annotation.WebServlet;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.Part;

@WebServlet(description = "FileUploadServlet Description", urlPatterns = { "/FileUploadServlet" })
@MultipartConfig(location="/home/userone/EE6_FileUpload_Servlet")

public class FileUploadServlet extends HttpServlet {
 
    private static final long serialVersionUID = 1L;
    public FileUploadServlet()
        {
          super();
          System.out.println("FileUploadServlet Initialized & Instantiated.");
        }
 
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
        {
          PrintWriter out=response.getWriter();
          out.println("<html><head><body>");
          for (Part part : request.getParts()) 
              {
                  String fileName = "";
                  String partHeader = part.getHeader("content-disposition");
                  long partSize = part.getSize();
                  out.println("<BR>Part Name = "+part.getName());
                  out.println("<BR>Part Header = " + partHeader);
                  out.println("<BR>Part Size = " + partSize);
                  System.out.println("part.getHeader("content-disposition") = " + part.getHeader("content-disposition"));
               }
           out.println("<center><h1>File Upload Completed Successfully</h1></center></body></html>");


           //**** Custom Option ****//
           System.out.println("Custom Way To Upload File with Actual FileName.");
           fileUploadWithDesiredFilePathAndName(request);
           System.out.println("File Uploaded using custom Way.");
        }

    

     /* Following method allows us to place the uploaded file in a desired Location on the server along with the desired fileName */
     public void fileUploadWithDesiredFilePathAndName(HttpServletRequest request) throws IOException,ServletException
        {
          /******** Following part of code is not needed ********/
          InputStream inputStream = null;
          FileOutputStream outputStream =null;
          try
           {
             for (Part part : request.getParts()) 
               {
                  System.out.println(part.getName());
                  inputStream = request.getPart(part.getName()).getInputStream();
                  int i = inputStream.available();
                  byte[] b  = new byte[i];
                  inputStream.read(b);
                  System.out.println("Length : " + b.length);

                // Finding the fileName //
                  String fileName = "";
                  String partHeader = part.getHeader("content-disposition");
                  System.out.println("Part Header = " + partHeader);
                  System.out.println("part.getHeader("content-disposition") = " + part.getHeader("content-disposition"));

                  for (String temp : part.getHeader("content-disposition").split(";")) 
                     {
                       if (temp.trim().startsWith("filename")) 
                        {
                           fileName=temp.substring(temp.indexOf('=') + 1).trim().replace(""", "");
                        }
                     }

                  // Writing contents to desired FilePath & FileName //
                  String uploadDir=System.getProperty("jboss.server.base.dir")+"/upload";
                  System.out.println("File will be Uploaded at: " +uploadDir+"/"+fileName);                  
                  outputStream = new FileOutputStream(uploadDir +"/"+fileName);
                  outputStream.write(b);
                  inputStream.close();
               }
            }
          catch(Exception e)
            {
               System.out.println("Unable to Upload File: "+e);
               e.printStackTrace();
            }
          finally
            {
                if(inputStream!=null)
                   {   
                      try{ inputStream.close(); } catch(Exception e){ e.printStackTrace(); } 
                   }
                if(outputStream!=null)
                   {   
                      try{ outputStream.close(); } catch(Exception e){ e.printStackTrace(); } 
                   }
            }
        }
   }

NOTE:
The above servlet represents two ways to upload the file. One is purely using @MultipartConfig(location=”/home/userone/EE6_FileUpload_Servlet”) in this case the upload file location is specified but the uploaded file will have some random name, which is quite confusing some time.

So the above Servlet also has a separate method “fileUploadWithDesiredFilePathAndName(HttpServletRequest)” which extract the actual file name and places it in a desired location on the server box.

Step5). Now we will write a simple ant “build.xml” file in order to build and deploy our web application on JBoss AS7. So write the following “build.xml” file inside “/home/userone/EE6_FileUpload_Servlet” as following:

<project name="Servlet3FileUploadProject" default="deploy">
<property name="jboss.home" value="/home/userone/jboss-as-7.1.0.CR1b" />
<property name="jboss.module.dir" value="${jboss.home}/modules" />
<property name="basedir" value="." />
<property name="tmp.dir" value="tmp" />
<property name="output.dir" value="build" />
<property name="src.dir" value="src" />
<property name="war.name" value="Servlet3FileUploadDemo.war" />

        <path id="jboss.classpath">
           <fileset dir="${jboss.module.dir}">
              <include name="**/*.jar"/>
           </fileset>  
        </path>

        <target name="init">
           <delete dir="${output.dir}" />
           <mkdir dir="${output.dir}" />
           <delete dir="${tmp.dir}" />
           <mkdir dir="${tmp.dir}" />
        </target>
	 
        <target name="build" depends="init">
           <mkdir dir="${tmp.dir}/WEB-INF/classes"/>
           <copy file="${src.dir}/index.jsp" todir="${tmp.dir}"/>
           <javac srcdir="${src.dir}" destdir="${tmp.dir}/WEB-INF/classes"  includes="*.java" classpathref="jboss.classpath"/> 

           <copy todir="${tmp.dir}/WEB-INF">
                <fileset dir="${src.dir}/">
                      <include name="web.xml"/> 
                </fileset>
           </copy>          
           <jar jarfile="${tmp.dir}/${war.name}" basedir="${tmp.dir}" compress="true" />
      
           <!-- Clean up -->
           <copy file="${tmp.dir}/${war.name}" tofile="${output.dir}/${war.name}"/>
           <delete includeEmptyDirs="true">
              <fileset dir="${tmp.dir}"/>
           </delete> 
        </target>

        <target name="deploy" depends="build">
            <echo message="*******************  Deploying the WAR file ${war.name} *********************" />  
            <echo message="********** ${output.dir}/${war.name} to ${jboss.home}/standalone/deployments **********" />  
            <copy todir="${jboss.home}/standalone/deployments/">
                <fileset dir="${output.dir}/">
                  <include name="${war.name}"/> 
                </fileset>
            </copy>
            <echo message="*******************  Deployed Successfully   *********************" />  
        </target>
</project>

NOTE: The only change in the above file you need to do is to change the “jboss.home” directory path in the second line of the above script is to point to your own JBoss AS7 directory home directory.

Step6). Now before running your ANT script to build and deploy the above webapplication you should have the ANT as well as JAVA set in the $PATH variable of the Shell / command prompt as following:

For Unix Based OS:
export PATH=/home/userone/jdk1.6.0_21/bin:/home/userone/apache-ant-1.8.2/bin:$PATH

For Windows Based OS:
set PATH=C:/jdk1.6.0_21/bin;C:/apache-ant-1.8.2/bin;%PATH%

Step7). Now run the ant file from the directory where you have placed the “build.xml” file as following:

[userone@localhost httpOnlyDemo]$ ant

Buildfile: build.xml

init:
   [delete] Deleting directory /home/userone/EE6_FileUpload_Servlet/build
    [mkdir] Created dir: /home/userone/EE6_FileUpload_Servlet/build
    [mkdir] Created dir: /home/userone/EE6_FileUpload_Servlet/tmp

build:
    [mkdir] Created dir: /home/userone/EE6_FileUpload_Servlet/tmp/WEB-INF/classes
     [copy] Copying 1 file to /home/userone/EE6_FileUpload_Servlet/tmp
    [javac] Compiling 1 source file to /home/userone/EE6_FileUpload_Servlet/tmp/WEB-INF/classes
      [jar] Building jar: /home/userone/EE6_FileUpload_Servlet/tmp/Servlet3FileUploadDemo.war
     [copy] Copying 1 file to /home/userone/EE6_FileUpload_Servlet/build

deploy:
     [echo] *******************  Deploying the WAR file Servlet3FileUploadDemo.war *********************
     [echo] ********** build/Servlet3FileUploadDemo.war to /home/userone/jboss-as-7.1.0.CR1b/standalone/deployments **********
     [copy] Copying 1 file to /home/userone/jboss-as-7.1.0.CR1b/standalone/deployments
     [echo] *******************  Deployed Successfully   *********************

BUILD SUCCESSFUL
Total time: 3 seconds

Step8). Now access the application like following: “http://localhost:8080/Servlet3FileUploadDemo/index.jsp

NOTE: We will need to make sure that whatever upload directory we have choosen for this demo, Must already exist.
.
.
Thanks
MiddlewareMagic Team


CDI Injection inside a HttpServlet with JBoss AS7

Hi,

As JBoss AS7 is very new And most powerful application server with many changes in it. JBossAS7 web profile is fully EE6 Certified however the JBoss AS7 full profile will be released soon with the full EE6 capabilities. CDI (Conextual Dependency Injection) is one of the most attractive feature of EE6. Managed beans are a key concept introduced in Java EE6. More details on CDI specification can be found in the following link: http://jcp.org/en/jsr/detail?id=299

So here we are going to see a very simple demo in which we will create our own Bean using “@javax.inject.Named” annotation and we will define it’s scope as “@javax.enterprise.context.SessionScoped”. Then we will try to inject this Plain Bean inside our HttpServlets using annotation “@javax.inject.Inject”. We will also see how we can develop, build, deploy and test this simple WAR file.

Features To Discuss.

In this example we will mainly focus on following points

Point-1). Here we are using JBoss AS7 latest build “jboss-as-7.1.0.Beta1” which can be downloaded from the following link: http://www.jboss.org/jbossas/downloads

Point-2). How to use and develop Servlets3.0 annotations without writing “web.xml” file.

Point-3). How to create our own Managed Beans using annotations @Named.

Point-4). Also we will see how to define the scope of our Beans using annotation @SessionScope.

Point-5). How to inject a Named Bean inside a Servlet using @Inject Annotation.

Point-6). For creating and using Named beans we must create at least one empty “beans.xml” file inside our applications “WEB-INF” directory, If it is a Web Application. For EJB Based application it can be placed inside the “META-INF” directory. For Plain Jar files it can be placed inside the jars present inside the “lib” directory.

Developing TestCase

Step1). Create a directory somewhere in your filesystem like “/home/userone/CDI_Demo” where we will place our application build related stuff. Then create another directory “src” inside “/home/userone/CDI_Demo” where we will be placing our source codes and JSPs.
Just place an empty “beans.properties” file inside “/home/userone/CDI_Demo/src”

Step2). Create Bean class “TestBean.java” as following inside the “/home/userone/CDI_Demo/src” directory.

package beans;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;

@Named
@SessionScoped
public class TestBean implements Serializable 
   {
	private static final long serialVersionUID = 1L;
	private String beanParam="Hi MiddlewareMagic !!!";

        public TestBean()
         {
    	   System.out.println("nt TestBean which is CDI Bean instentiated.");
         }
    
	public String getBeanParam() 
         {
	    System.out.println("nt getBeanParam() called.");
	    return beanParam;
	 }

	public void setBeanParam(String beanParam) 
         {
	    System.out.println("nt setBeanParam("+beanParam+") called.");
	    this.beanParam = beanParam;
	 }	
   }

Step2-A) Make sure that at least one empty file “beans.xml” need to be placed inside the “WEB-INF” directory of your application in order to web beans work.
So create an empty file with name “beans.xml” and then place it inside “/home/userone/CDI_Demo/src” then later while Build phase of the application we will put this file inside “WEB-INF” directory of our web application.

Step3). Now we will create a Simple HttpServlet class “TestServlet.java” inside “/home/userone/CDI_Demo/src” directory as following:

package 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.ServletException;

import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.annotation.WebServlet;

@WebServlet(description = "TestServlet Description", urlPatterns = { "/TestServlet" })
public class TestServlet extends HttpServlet {
	
	@Inject 
	private beans.TestBean testBean;
	
	private static final long serialVersionUID = 1L;
        public TestServlet() 
        {
          super();
          System.out.println("TestServlet Initialized & Instentiated.");
        }

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
        {
          PrintWriter out=response.getWriter(); 
	  out.println("testBean.getBeanParam() = "+testBean.getBeanParam());
          testBean.setBeanParam("Hello, MiddlewareMagic");
          out.println("testBean.getBeanParam() = "+testBean.getBeanParam());
	}
}

Step4). Now we will write another simple Servlet “TestServletTwo.java” to check whether the Named Bean is present inside the SesionScope or not? Place this file as well inside the “/home/userone/CDI_Demo/src” directory as following:

package 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.ServletException;

import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.annotation.WebServlet;

@WebServlet(description = "TestServletTwo Description", urlPatterns = { "/TestServletTwo" })
public class TestServletTwo extends HttpServlet {
	
	@Inject 
	private beans.TestBean testBean;
	
	private static final long serialVersionUID = 1L;
        public TestServletTwo() 
        {
          super();
          System.out.println("TestServletTwo Initialized & Instentiated.");
        }

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
        {
          PrintWriter out=response.getWriter(); 
	  out.println("testBean.getBeanParam() = "+testBean.getBeanParam());
	}
}

Step5). Now we will write a simple “index.jsp” page to just provide a link to access the “TestServlet” , Place this file as well inside the “/home/userone/CDI_Demo/src” directory as following:

<html>
  <head> 
    <title>CDI Demo</title>
  </head>
  <body>
      <a href="TestServlet">Click Here !!!</a>
  </body>
</html>

Step6). Now the most important part, here we are going to develop “build.xml” ANT file, which will build, deployour webapplication on the JBoss AS7.1 Beta Server, so write the following “build.xml” file inside “/home/userone/CDI_Demo” directory.

<project name="CDI_Demo" default="deploy">
<property name="jboss.home" value="/home/userone/jboss-as-7.1.0.Beta1" />
<property name="jboss.module.dir" value="${jboss.home}/modules" />
<property name="basedir" value="." />
<property name="tmp.dir" value="tmp" />
<property name="output.dir" value="build" />
<property name="src.dir" value="src" />
<property name="war.name" value="EE6Feature_CDIDemo.war" />

   <path id="jboss.classpath">
     <fileset dir="${jboss.module.dir}">
        <include name="**/*.jar"/>
     </fileset>  
   </path>

        <target name="init">
           <delete dir="${output.dir}" />
           <mkdir dir="${output.dir}" />
           <delete dir="${tmp.dir}" />
           <mkdir dir="${tmp.dir}" />
        </target>
	 
        <target name="build" depends="init">
           <mkdir dir="${tmp.dir}/WEB-INF/classes"/>
           <javac srcdir="${src.dir}" destdir="${tmp.dir}/WEB-INF/classes"  includes="*.java" classpathref="jboss.classpath" />
           <copy file="${src.dir}/index.jsp" tofile="${tmp.dir}/index.jsp"/>
           <copy file="${src.dir}/TestServlet.java" todir="${tmp.dir}/WEB-INF/classes"/>
           <copy file="${src.dir}/TestServletTwo.java" todir="${tmp.dir}/WEB-INF/classes"/>
           <copy file="${src.dir}/TestBean.java" todir="${tmp.dir}/WEB-INF/classes"/>

           <!-- Need to place at lease one empty "beans.xml" file inside WEB-INF -->
           <copy file="${src.dir}/beans.xml" todir="${tmp.dir}/WEB-INF"/>
   
           <jar jarfile="${tmp.dir}/${war.name}" basedir="${tmp.dir}" compress="true" />
           <copy file="${tmp.dir}/${war.name}" tofile="${output.dir}/${war.name}"/>

           <delete includeEmptyDirs="true">
              <fileset dir="${tmp.dir}"/>
           </delete> 
        </target>

        <target name="deploy" depends="build">
            <echo message="*******************  Deploying the WAR file ${war.name} *********************" />  
            <echo message="********** ${output.dir}/${war.name} to ${jboss.home}/standalone/deployments **********" />  
            <copy todir="${jboss.home}/standalone/deployments/">
                <fileset dir="${output.dir}/">
                  <include name="${war.name}"/> 
                </fileset>
            </copy>
            <echo message="*******************  Deployed Successfully   *********************" />  
        </target>
</project>

NOTE: The only change in the above file you need to do is to change the “jboss.home” directory path in the second line of the above script to point to your own JBoss AS7 directory.

Step7). Now before running your ANT script to build and deploy the above webapplication you should have the ANT as well as JAVA set in the $PATH variable of the Shell / command prompt as following:

For Unix Based OS:
export PATH=/home/userone/jdk1.6.0_21/bin:/home/userone/org.apache.ant_1.6.5/bin:$PATH

For Windows Based OS:
set PATH=C:/jdk1.6.0_21/bin;C:/org.apache.ant_1.6.5/bin;%PATH%

Step8). Now once the PATH is set In the command/Shell prompt you can move inside the directory “/home/userone/CDI_Demo” and then run the ant to build the webservice. by running the command “ant build”

[userone@localhost EE6_Async_Servlet_Demo]$ ant deploy
Buildfile: /home/userone/CDI_Demo/build.xml

init:
   [delete] Deleting directory /home/userone/CDI_Demo/build
    [mkdir] Created dir: /home/userone/CDI_Demo/build
    [mkdir] Created dir: /home/userone/CDI_Demo/tmp

build:
    [mkdir] Created dir: /home/userone/CDI_Demo/tmp/WEB-INF/classes
    [javac] /home/userone/CDI_Demo/build.xml:25: warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds
    [javac] Compiling 3 source files to /home/userone/CDI_Demo/tmp/WEB-INF/classes
     [copy] Copying 1 file to /home/userone/CDI_Demo/tmp
     [copy] Copying 1 file to /home/userone/CDI_Demo/tmp/WEB-INF/classes
     [copy] Copying 1 file to /home/userone/CDI_Demo/tmp/WEB-INF/classes
     [copy] Copying 1 file to /home/userone/CDI_Demo/tmp/WEB-INF/classes
     [copy] Copying 1 file to /home/userone/CDI_Demo/tmp/WEB-INF
      [jar] Building jar: /home/userone/CDI_Demo/tmp/EE6Feature_CDIDemo.war
     [copy] Copying 1 file to /home/userone/CDI_Demo/build

deploy:
     [echo] *******************  Deploying the WAR file EE6Feature_CDIDemo.war *********************
     [echo] ********** build/EE6Feature_CDIDemo.war to /home/userone/jboss-as-7.1.0.Beta1/standalone/deployments **********
     [copy] Copying 1 file to /home/userone/jboss-as-7.1.0.Beta1/standalone/deployments
     [echo] *******************  Deployed Successfully   *********************

BUILD SUCCESSFUL
Total time: 2 seconds

Step9). Now you will see the following kind of output on your JBoss AS7.1 console which means the application is deployed successfully:

11:41:27,741 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-2) Starting deployment of "EE6Feature_CDIDemo.war"
11:41:27,760 INFO  [org.jboss.weld] (MSC service thread 1-5) Processing CDI deployment: EE6Feature_CDIDemo.war
11:41:27,770 INFO  [org.jboss.weld] (MSC service thread 1-3) Starting Services for CDI deployment: EE6Feature_CDIDemo.war
11:41:27,775 INFO  [org.jboss.weld] (MSC service thread 1-3) Starting weld service
11:41:27,859 INFO  [org.jboss.web] (MSC service thread 1-2) registering web context: /EE6Feature_CDIDemo
11:41:27,898 INFO  [org.jboss.as.server.controller] (DeploymentScanner-threads - 1) Replaced deployment "EE6Feature_CDIDemo.war" with deployment "EE6Feature_CDIDemo.war"

Step10). Now access the WebApplication like following :
http://localhost:8080/EE6Feature_CDIDemo/TestServlet
AND then
http://localhost:8080/EE6Feature_CDIDemo/TestServletTwo

You will notice that the TestBean is injected inside these servlets using Session Scope.

.
.
Thanks
Middleware Magic Team


httpOnly Cookies using web.xml servlet 3.0 in JBoss AS7

Hi,

Securing our Applications is one of the most important task while moving to the production environment. Securing HttpSession is one of them. In this demonstration we will see how to use the HttpOnly cookies in “web.xml” using the tag “httpOnly”, Yes, this is a new feature added as part of Servlet3.0 Specification that we cna specify the httpOnly cookies directly using web.xml file.

The HttpOnly cookie is supported by most modern browsers. On a supported browser, an HttpOnly session cookie will be used only when transmitting HTTP (or HTTPS) requests, thus restricting access from other, non-HTTP APIs (such as JavaScript). This restriction mitigates but does not eliminate the threat of session cookie theft via Cross-site scripting. It means on client side the cookies can not be accessed using java script or some other scripting utilities. This feature applies only to session-management cookies, and not other browser cookies.

Earlier in JBoss AS6 we had a feature called as “context.xml” using which we could define the cookies as “httpOnly” by either editing the “${PROFILE}/deploy/jbossweb.sar/context.sar/context.xml” file or by creating “conntext.xml” file inside our application “${YOUR_APP}/WEB-INF/context.xml” file as following:

<Context cookies="true" crossContext="true" useHttpOnly="true">
   <SessionCookie httpOnly="true"/> 
</Context>

In this demonstration we will be using JBoss AS7 ( jboss-as-7.1.0.Beta1 ) which can be downloaded from the following link: http://www.jboss.org/jbossas/downloads
And we will see how we can specify httpOnly cookies using the standard web descriptor “web.xml” file using servlet 3.0 specification.

Step1). Create a Directory somewhere inside your file system where we can create our web application. Suppose i am creating a directory as “/home/userone/httpOnlyDemo” and the create a subdirectory with name “src” inside “/home/userone/httpOnlyDemo”

Step2). Now place the following kind of “web.xml” inside the “/home/userone/httpOnlyDemo/src” directory.

<?xml version="1.0"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee web-app_3_0.xsd"
      version="3.0">
    
      <!-- Make sure that your web.xml is pointing the version="3.0" as above -->
      <session-config>
        <cookie-config>
           <http-only>true</http-only>
        </cookie-config>
      </session-config>
    
</web-app>

NOTE: The only thing here you need to kiip in mind that you are using the “web-app_3_0.xsd” in your “web.mxl” file pointing to version=”3.0″.

Step3). Now we will write a simple JSP Page in order to display the JSESSIONID cookie value in the browser with the help of Java Script. (Ideally the code should not be able to display the JSESSIONID cookie value with the help of java script here because we have marked out Cookie as “httpOnly”…so you can try both ways by enabling and disabling the http-only tag inside your web.xml to see what different you see while hitting the JSP Page.)

<%
   System.out.println("nt index.jsp is called...request="+request);
%>
<html>
    <head>
        <title>Hi HttpOnly</title>
        <script type="text/javascript">
          function ReadCookie(cookieName) 
           {
              var theCookie=""+document.cookie;
              var ind=theCookie.indexOf(cookieName);
              if (ind==-1 || cookieName=="") return ""; 
                 var ind1=theCookie.indexOf(';',ind);
              if (ind1==-1) ind1=theCookie.length; 
                 return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
           }
       </script>
    </head>
    <body bgcolor="maroon" text="white">
            <center>
            <h1>Hello CookieDemo "HttpOnly" !!!

	<form name="getCookie">
	    <table border=0 cellpadding=3 cellspacing=3>
	     <tr><td>Cookie Name:&nbsp;</td><td><input name=t1 type=text size=20 value="JSESSIONID"></td></tr>
             <tr><td><input name=b1 type=button value="Read Cookie Value" onClick="this.form.t2.value=ReadCookie(this.form.t1.value)">&nbsp;</td>    <td><input name=t2 type=text size=20 value=""></td></tr>
           </table>
        </form>
       <b>NOTE: when you click on this button you should not be able to see the JSESSIONID cookie value in the textField if the http-only cookie is enabled.</b>
   </center>
    </body>
</html>

Step4). Now we will write a simple ant “build.xml” file in order to build and deploy our web application on JBoss AS7. So write the following “build.xml” file inside “/home/userone/httpOnlyDemo” as following:

<project name="httpOnlyCookieDemo" default="deploy">
<property name="jboss.home" value="/home/userone/jboss-as-7.1.0.Beta1" />
<property name="jboss.module.dir" value="${jboss.home}/modules" />
<property name="basedir" value="." />
<property name="tmp.dir" value="tmp" />
<property name="output.dir" value="build" />
<property name="src.dir" value="src" />
<property name="war.name" value="httpOnlyDemo.war" />

        <path id="jboss.classpath">
           <fileset dir="${jboss.module.dir}">
              <include name="**/*.jar"/>
           </fileset>  
        </path>

        <target name="init">
           <delete dir="${output.dir}" />
           <mkdir dir="${output.dir}" />
           <delete dir="${tmp.dir}" />
           <mkdir dir="${tmp.dir}" />
        </target>
	 
        <target name="build" depends="init">
           <mkdir dir="${tmp.dir}/WEB-INF"/>
           <copy file="${src.dir}/index.jsp" tofile="${tmp.dir}/index.jsp"/>
           <copy todir="${tmp.dir}/WEB-INF">
                <fileset dir="${src.dir}/">
                  <include name="web.xml"/> 
                </fileset>
           </copy>          
           <jar jarfile="${tmp.dir}/${war.name}" basedir="${tmp.dir}" compress="true" />
           <copy file="${tmp.dir}/${war.name}" tofile="${output.dir}/${war.name}"/>
           <delete includeEmptyDirs="true">
              <fileset dir="${tmp.dir}"/>
           </delete> 
        </target>

        <target name="deploy" depends="build">
            <echo message="*******************  Deploying the WAR file ${war.name} *********************" />  
            <echo message="********** ${output.dir}/${war.name} to ${jboss.home}/standalone/deployments **********" />  
            <copy todir="${jboss.home}/standalone/deployments/">
                <fileset dir="${output.dir}/">
                  <include name="${war.name}"/> 
                </fileset>
            </copy>
            <echo message="*******************  Deployed Successfully   *********************" />  
        </target>
</project>

NOTE: The only change in the above file you need to do is to change the “jboss.home” directory path in the second line of the above script is to point to your own JBoss AS7 directory home directory.

Step5). Now before running your ANT script to build and deploy the above webapplication you should have the ANT as well as JAVA set in the $PATH variable of the Shell / command prompt as following:

For Unix Based OS:
export PATH=/home/userone/jdk1.6.0_21/bin:/home/userone/apache-ant-1.8.2/bin:$PATH

For Windows Based OS:
set PATH=C:/jdk1.6.0_21/bin;C:/apache-ant-1.8.2/bin;%PATH%

Step6). Now run the ant file from the directory where you have placed the “build.xml” file as following:

[userone@localhost httpOnlyDemo]$ ant
Buildfile: /home/userone/httpOnlyDemo/build.xml

init:
   [delete] Deleting directory /home/userone/httpOnlyDemo/build
    [mkdir] Created dir: /home/userone/httpOnlyDemo/build
    [mkdir] Created dir: /home/userone/httpOnlyDemo/tmp

build:
    [mkdir] Created dir: /home/userone/httpOnlyDemo/tmp/WEB-INF
     [copy] Copying 1 file to /home/userone/httpOnlyDemo/tmp
     [copy] Copying 1 file to /home/userone/httpOnlyDemo/tmp/WEB-INF
      [jar] Building jar: /home/userone/httpOnlyDemo/tmp/httpOnlyDemo.war
     [copy] Copying 1 file to /home/userone/httpOnlyDemo/build

deploy:
     [echo] *******************  Deploying the WAR file httpOnlyDemo.war *********************
     [echo] ********** build/httpOnlyDemo.war to /home/userone/jboss-as-7.1.0.Beta1/standalone/deployments **********
     [copy] Copying 1 file to /home/userone/jboss-as-7.1.0.Beta1/standalone/deployments
     [echo] *******************  Deployed Successfully   *********************

BUILD SUCCESSFUL
Total time: 0 seconds

Step7). Now access the application like following: “http://localhost:8080/httpOnlyDemo/index.jsp” and then see whether you are able to see the JSESSIONID value or not? Also try removing the http-only tag from your web.xml file and then redeploy the application and then again try to access the application to check whether you are able to see the JSESSIONID cookie value or not .

Some more useful tags from Servlet 3.0 Specifications

You can get more details on these tags from the following link: http://java.sun.com/xml/ns/javaee/web-common_3_0.xsd
Also we can use some more useful tags in order to secure our WebAppications with the help of servlet3.0 tags present inside “web.xml” file like following

secure cookie: A secure cookie is only used when a browser is visiting a server via HTTPS, ensuring that the cookie is always encrypted when transmitting from client to server. This makes the cookie less likely to be exposed to cookie theft via eavesdropping.

<session-config>
  <cookie-config>
    <secure>true</secure>
  </cookie-config>
</session-config>

tracking-mode cookie: tracking-mode element in the Servlet 3.0 specification allows you to define whether the JSESSIONID should be stored in a cookie or in a URL parameter. If the session id is stored in a URL parameter it could be inadvertently saved in a number of locations including the browser history, proxy server logs, referrer logs, web logs, etc. Accidental disclosure of the session id makes the application more vulnerable to session hijacking attacks. Instead, make sure the JSESSIONID is stored in a cookie if tracking-mode is set to COOKIE. The valid values for tracing-mode are COOKIE/SSL/URL

<session-config>
  <cookie-config>
    <tracking-mode>COOKIE</tracking-mode>
  </cookie-config>
</session-config>

.
.
Thanks
MiddlewareMagic Team


Copyright © 2010-2012 Middleware Magic. All rights reserved. |