• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 377
  • Last Modified:

How to add a cookie using Java filters

Hello,

I need to add a cookie from a filter. I have created a very simple class. Please see attached file. All it does is to cast the ServletResponse object passed to doFilter method and try to add a cookie with HttpServletResponse object. However, I get an exception. Please, could some one help me to add a cookie from a filter?

Thanks

AppFilter.txt
0
vielkacarolina1239
Asked:
vielkacarolina1239
  • 3
  • 2
  • 2
1 Solution
 
for_yanCommented:

I am not sure it applies to your situation, but maybe it makes sense to read it if you ahven't seen it:
http://stackoverflow.com/questions/2158548/adding-a-cookie-to-the-response-in-java-after-the-header-has-been-flushed

But you see an Exception (as opposed to those folks); so you probably have some details of where and what is happneing
0
 
rrzCommented:
Your attached code didn't retain it's formatting. Please post your code in a code box provided with comment form.
>I get an exception.  
Please show us the error message or stacktrace.
0
 
vielkacarolina1239Author Commented:
Please see below code snippet

Thanks,
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Filters;

import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;


import javax.servlet.http.*;

import javax.servlet.http.Cookie;

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


@WebFilter(filterName = "AppFilter", urlPatterns =
{
   "/*"
})
public class AppFilter implements Filter
{
   
   HttpServletRequest httpRequest = null;
   HttpServletResponse httpResponse = null;
   
      
   private static final boolean debug = true;
   
   private FilterConfig filterConfig = null;
   
   public AppFilter()
   {
   }   
   
   private void doBeforeProcessing(ServletRequest request, ServletResponse response)
      throws IOException, ServletException
   {
      try
      {
         if (debug)
         {
            log("AppFilter:DoBeforeProcessing");
         }

      }
      catch(Exception ex)
      {
         System.out.println("Error in AppFilter.java : " + ex.getMessage());
      }
   }   
   
   private void doAfterProcessing(ServletRequest request, ServletResponse response)
      throws IOException, ServletException
   {
      try
      {
         if (debug)
         {
            log("AppFilter:DoAfterProcessing");
         }
      }
      catch(Exception ex)
      {
         System.out.println("Error in AppFilter.java : " + ex.getMessage());
      }
   }


   public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain chain)
      throws IOException, ServletException
   {
      

      if (debug)
      {
         log("AppFilter:doFilter()");
      }

      httpRequest = (HttpServletRequest)request;
      httpResponse = (HttpServletResponse)response;


      HttpSession session = httpRequest.getSession();
      
      String cookiePath = httpRequest.getContextPath();

      Cookie myCookie = null;
     

      myCookie = new Cookie("application","cookieVal");
      

      myCookie.setMaxAge(999999999);         


      httpResponse.addCookie(myCookie);

      doBeforeProcessing(request, response);

      Throwable problem = null;
      try
      {
         chain.doFilter(request,httpResponse);         
      }
      catch (Throwable t)
      {
         
         problem = t;
         t.printStackTrace();         
      }

      doAfterProcessing(request, response);
      
      if (problem != null)
      {
         if (problem instanceof ServletException)
         {
            throw (ServletException) problem;
         }
         if (problem instanceof IOException)
         {
            throw (IOException) problem;
         }
         sendProcessingError(problem, response);
      }

   }

   
   public FilterConfig getFilterConfig()
   {      
      return (this.filterConfig);
   }

   
   public void setFilterConfig(FilterConfig filterConfig)
   {
      try
      {
      this.filterConfig = filterConfig;
      }
      catch(Exception ex)
      {
         System.out.println("Error in AppFilter.java : " + ex.getMessage());
      }
   }


   public void destroy()
   {      
   }

   public void init(FilterConfig filterConfig)
   {      
      try
      {
         this.filterConfig = filterConfig;
         if (filterConfig != null)
         {
            if (debug)
            {            
               log("AppFilter:Initializing filter");
            }
         }
      }
      catch(Exception ex)
      {
         System.out.println("Error in AppFilter.java : " + ex.getMessage());
      }
   }

   
   @Override
   public String toString()
   {
      StringBuffer sb = new StringBuffer("AppFilter(");
      
      try
      {
         if (filterConfig == null)
         {
            return ("AppFilter()");
         }

         sb.append(filterConfig);
         sb.append(")");
      }
      catch(Exception ex)
      {
         System.out.println("Error in AppFilter.java : " + ex.getMessage());   
      }
      
      return (sb.toString());
   }
   
   private void sendProcessingError(Throwable t, ServletResponse response)
   {
      String stackTrace = getStackTrace(t);      
      
      if (stackTrace != null && !stackTrace.equals(""))
      {
         try
         {
            response.setContentType("text/html");
            PrintStream ps = new PrintStream(response.getOutputStream());
            PrintWriter pw = new PrintWriter(ps);            
            pw.print("<html>\n<head>\n<title>Error</title>\n</head>\n<body>\n"); //NOI18N

            // PENDING! Localize this for next official release
            pw.print("<h1>The resource did not process correctly</h1>\n<pre>\n");            
            pw.print(stackTrace);            
            pw.print("</pre></body>\n</html>"); //NOI18N
            pw.close();
            ps.close();
            response.getOutputStream().close();
         }
         catch (Exception ex)
         {
            System.out.println("Error in AppFilter.java : " + ex.getMessage());
         }
      }
      else
      {
         try
         {
            PrintStream ps = new PrintStream(response.getOutputStream());
            t.printStackTrace(ps);
            ps.close();
            response.getOutputStream().close();
         }
         catch (Exception ex)
         {
            System.out.println("Error in AppFilter.java : " + ex.getMessage());
         }
      }
   }
   
   public static String getStackTrace(Throwable t)
   {
      String stackTrace = null;
      try
      {
         StringWriter sw = new StringWriter();
         PrintWriter pw = new PrintWriter(sw);
         t.printStackTrace(pw);
         pw.close();
         sw.close();
         stackTrace = sw.getBuffer().toString();
      }
      catch (Exception ex)
      {
         System.out.println("Error in AppFilter.java : " + ex.getMessage());
      }
      return stackTrace;
   }
   
   public void log(String msg)
   {
      try
      {
         filterConfig.getServletContext().log(msg);      
      }
      catch(Exception ex)
      {
         System.out.println("Error in AppFilter.java : " + ex.getMessage());
      }
   }
}

Open in new window

0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
for_yanCommented:
And waht about the exception stacktrace ?
0
 
vielkacarolina1239Author Commented:
please see below exception in code snippet. This exception is issued once the code reaches: chain.doFilter(request,httpResponse);    

Thanks,
SEVERE: java.lang.ArrayIndexOutOfBoundsException
	at java.lang.System.arraycopy(Native Method)
	at java.nio.HeapByteBuffer.put(HeapByteBuffer.java:201)
	at com.sun.grizzly.http.SocketChannelOutputBuffer.realWriteBytes(SocketChannelOutputBuffer.java:290)
	at com.sun.grizzly.tcp.http11.InternalOutputBuffer$OutputStreamOutputBuffer.doWrite(InternalOutputBuffer.java:898)
	at com.sun.grizzly.tcp.http11.filters.IdentityOutputFilter.doWrite(IdentityOutputFilter.java:159)
	at com.sun.grizzly.tcp.http11.InternalOutputBuffer.doWrite(InternalOutputBuffer.java:658)
	at com.sun.grizzly.tcp.Response.doWrite(Response.java:685)
	at org.apache.catalina.connector.OutputBuffer.realWriteBytes(OutputBuffer.java:422)
	at com.sun.grizzly.util.buf.ByteChunk.flushBuffer(ByteChunk.java:453)
	at com.sun.grizzly.util.buf.ByteChunk.append(ByteChunk.java:375)
	at org.apache.catalina.connector.OutputBuffer.writeBytes(OutputBuffer.java:452)
	at org.apache.catalina.connector.OutputBuffer.write(OutputBuffer.java:439)
	at org.apache.catalina.connector.CoyoteOutputStream.write(CoyoteOutputStream.java:160)
	at org.apache.catalina.servlets.DefaultServlet.copyRange(DefaultServlet.java:2229)
	at org.apache.catalina.servlets.DefaultServlet.copy(DefaultServlet.java:1965)
	at org.apache.catalina.servlets.DefaultServlet.serveResource(DefaultServlet.java:987)
	at org.apache.catalina.servlets.DefaultServlet.doGet(DefaultServlet.java:413)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:734)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
	at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1539)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
	at Filters.AppFilter.doFilter(AppFilter.java:116)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
	at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
	at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
	at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98)
	at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162)
	at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:330)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
	at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:174)
	at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:828)
	at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:725)
	at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1019)
	at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
	at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
	at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
	at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
	at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
	at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
	at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
	at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
	at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)

Open in new window

0
 
rrzCommented:
>This exception is issued once the code reaches: chain.doFilter(request,httpResponse);  
I am guessing that the problem is not in your Filter. To test, remove the Filter, does your web app run without error when your Filter is not called ?
0
 
vielkacarolina1239Author Commented:
I found the issue. It was similar to what you said. A store procedure was blowing up. Got it fix. Thanks.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now