tomcat-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From msasc...@esg-gmbh.de
Subject Re: Session Cookies to/from JApplet (using 1.3 plugin)
Date Fri, 09 Jun 2000 08:44:35 GMT
Mike,

I had similar problems but I got it working, i.e. an applet talks to a servlet
with a valid session.

There are some major points to consider:
1. with Netscape the applet code must be in the same directory as the page from
where it was in invoked - ore a subdir of the page. With a servlet use an alias
to make Netscape think that ALL is from the same place
2. I ran into serious troubles after I had invalidated my session. See mail #
4063 from me. I do basically the same as you, i.e. I set and send the cookie
from my applet's post request. The difference is how I pass it to the applet.
The page to start the applet is generated by a JSP. From there it's easy to get
the current session and the cookie and to pass it as an argument to the applet.
Code is given below. But I'm not happy with this workaround since I'm not sure
whether it works everywhere everytime.
3. Finally, stop the browser from caching the content when you start the
session. See code below.

Martin

martin.saschek@esg-gmbh.de


Here's the servlet, through which all request are routed
=======================================

public class ContrServlet extends HttpServlet
{

  public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
  {
    // handles login, logout and default behaviour
    if( request.getParameter( "user" ) != null )
    {
      login( request, response );
      return;
    }
    HttpSession session = request.getSession( true );
    session.setMaxInactiveInterval( 0x8FFFFFFF );
    PrintWriter writer = response.getWriter();
    if( request.getParameter( "logout" ) != null )
    {
      Enumeration enumParams = request.getParameterNames();
      String strParamName;
      response.setContentType( "text/html" );
      writer.println( "<HTML>" );
      writer.println( "<HEAD>" );
      writer.println( "<TITLE>Logout</TITLE>" );
      writer.println( "</HEAD>" );
      writer.println( "<BODY>" );
      writer.println( "LOGOUT!" );
      writer.println( "<BR>" );
      writer.println( "<a href =
\"http://localhost:8080/etk/index.html\">Startseite</a>" );
      writer.println( "</BODY>" );
      writer.println( "</HTML>" );
      session.invalidate();
    }
    else
    {
      Enumeration enumParams = request.getParameterNames();
      String strParamName;
      response.setContentType( "text/html" );
      writer.println( "<HTML>" );
      writer.println( "<HEAD>" );
      writer.println( "<TITLE>Logout</TITLE>" );
      writer.println( "</HEAD>" );
      writer.println( "<BODY>" );
      writer.println( "got unknown request to control" );
      writer.println( "<BR>" );
      while( enumParams.hasMoreElements() )
      {
        strParamName = (String)enumParams.nextElement();
        writer.println( strParamName );
        writer.println( ":" );
        writer.println( request.getParameter( strParamName ) );
        writer.println( "<BR>" );
      }
      writer.println( "<a href =
\"http://localhost:8080/etk/index.html\">Startseite</a>" );
      writer.println( "</BODY>" );
      writer.println( "</HTML>" );
    }
  }

  //Process the HTTP Post request
  public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
  {
    // requests from the applet end up here
    String strLeftCommand = request.getParameter( "command" );
    if( strLeftCommand == null )
    {
      doGet( request, response );
      return;
    }
    HttpSession session = request.getSession( true );
    session.setMaxInactiveInterval( 0x8FFFFFFF );
    PrintWriter writer = response.getWriter();
    response.setContentType( "text/plain" );
    if( strLeftCommand.equalsIgnoreCase( "time" ) )
    {
      Date dateCreation = new Date( session.getCreationTime() );
      DateFormat dformLocal = DateFormat.getDateTimeInstance( DateFormat.FULL,
DateFormat.FULL );
      writer.println("creation time: " + dformLocal.format( dateCreation ) );
    }
    // handle various commands...

    writer.println();
    writer.close();
  }

  public void login(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
  {
    // prohibit caching, get session, set session parameters and forward output
to framejsp.html
    response.setHeader("pragma","no-cache");
    response.setHeader("Cache-Control","no-cache");
    response.setHeader("Cache-Control","no-store");
    response.setDateHeader("Expires",0);
    HttpSession session = request.getSession( true );
    session.setMaxInactiveInterval( 0x8FFFFFFF );
    PrintWriter writer = response.getWriter();
    String strUser = request.getParameter( "user" );
    if( strUser != null )
    {
      String strDispatch = "/src/framejsp.html";
      try
      {
        session.putValue( "ContrServlet.user", strUser );
        session.putValue( "ContrServlet.password", request.getParameter(
"password" ) );
        RequestDispatcher disp = getServletContext().getRequestDispatcher(
strDispatch );
        disp.forward( request, response );
      }
      catch( NullPointerException e )
      {
        response.setContentType( "text/html" );
        writer.println( "<HTML>" );
        writer.println( "<HEAD>" );
        writer.println( "<TITLE>Error</TITLE>" );
        writer.println( "</HEAD>" );
        writer.println( "<BODY>" );
        writer.println( "couldn't find " + strDispatch );
        writer.println( "<BR>" );
        writer.println( "<a href =
\"http://localhost:8080/etk/index.html\">Startseite</a>" );
        writer.println( "</BODY>" );
        writer.println( "</HTML>" );
        session.invalidate();
      }
    }
  }
}


==============================================
Here's the JSP to start the applet - it's a frame in framejsp.html
Note how the cookie is passed to the applet!
there may be a better way to get the cookie; here I rely that
the session cookie is the first one in the cookie array
==============================================


<%@ page language="java" %>
<%
  Cookie[] cookies = request.getCookies();
%>
<HTML>
<HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252">
<TITLE>
linke Seite
</TITLE>
</HEAD>
<BODY>
linke Seite ├╝ber JSP<BR>
<jsp:plugin
  type="applet"
  code="applet.LeftApplet"
  codebase="appletcode"
  name="leftApplet"
  width="530"
  height="300"
  jreversion="1.3"
  nspluginurl="http://java.sun.com/products/plugin/1.3/plugin-install.html"

iepluginurl="http://a4991847:8080/etk/Plugin/j2re1_3_0-win-i.exe#Version=1,3,0,0"

  >
  <jsp:params>
    <jsp:param name="cache_option" value="Plugin"/>
    <jsp:param name="cache_archive" value="jbcl3.1.jar,appletcomm.jar"/>
    <jsp:param name="cache_version" value="3.1.0.0,1.0.0.5"/>
    <jsp:param name="name" value="leftApplet"/>
    <jsp:param name="cookieName" value="<%= cookies[0].getName() %>" />
    <jsp:param name="cookieValue" value="<%= cookies[0].getValue() %>" />
  </jsp:params>
  <jsp:fallback>
    Plugin tag OBJECT or EMBED not supported by browser or no JDK 1.3 support
for APPLET.
  </jsp:fallback>
</jsp:plugin>
</BODY>
</HTML>

===============
and the applet's code
===============
  public void init()
  {
    strCookieName = getParameter( "cookieName" );
    strCookieValue = getParameter( "cookieValue" );
    strCookie = strCookieName + "=" + strCookieValue;
  }

 public void sendServlet()
  {
      String strInput = jTextField1.getText();
      jTextField1.setText("");

      try {
        // set up command
        String strCommand = URLEncoder.encode("command") + "=" +
                           URLEncoder.encode(strInput);

        // connect to servlet
        URL url = new URL( strBaseURL + "src/control" );
        jTextArea1.setText( url.toString() );
        URLConnection uc = url.openConnection();
        uc.setRequestProperty("cookie", strCookie );
        uc.setDoOutput(true);
        uc.setDoInput(true);
        uc.setUseCaches(false);
        uc.setRequestProperty("Content-type",
"application/x-www-form-urlencoded");

        // send command
        DataOutputStream dos = new DataOutputStream(uc.getOutputStream());
        dos.writeBytes(strCommand);
        dos.flush();
        dos.close();

        // get response
        BufferedReader bufReader = new BufferedReader( new InputStreamReader(
uc.getInputStream() ) );
        String str = bufReader.readLine();
        bufReader.close();
        jTextArea2.setText( str );
      }
      catch(MalformedURLException e)
      {
         jTextArea2.setText(e.toString());
         e.printStackTrace();
      }
      catch(IOException e)
      {
         jTextArea2.setText(e.toString());
         e.printStackTrace();
      }
   }

=======================================================



Hello all,

I'm developing a GUI applet in swing that communicates
with Servlets handling a multitude of connections
to other applications.  Strangely enough, one thing
I'm having problem with is sending the JSESSIONID
cookie back to Tomcat (through Apache, if that
matters).

This seems relatively straightforward, but does not work when
the cookie is a existing JSESSIONID.  By not work, I mean that
I get no response from my servlet, and no apparent errors in
the "tomcat.log" file.  My servlet code is supposed to bounce the
header information sent by the client back in the form of HTML.
(The applet and servlet code are included below).

Note that I've hard-coded strings into the cookie property, even
strings with JSESSIONID={some bogus id} and the servlet
is invoked and returns just fine (of course, it creates a new
session).  So, the servlet (or Tomcat) only has problems when
the session id maps to a current session.  Here is the header
my applet sends to Tomcat and below that is the servlet
source.  If anyone has any suggestions as to why Tomcat
(or the Servlet API) doesn't like this, please let me know.
(This is Apache 1.3.11, Tomcat 3.1 release build)

Thanks in advance,

Mike Grady



Sample HTTP header sent to Tomcat/Servlet (servlet does NOT respond)

content-type=application/x-www-form-urlencoded
connection=keep-alive
cookie=JSESSIONID=To1037mC4023944164377369At
accept=text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
host=devbox
content-length=63
user-agent=Java1.3.0


In my JApplet, I have code like the following:

   HttpURLConnection servCon = (HttpURLConnection)
urlServlet.openConnection();

   if (m_strCurrentCookie.length() > 0)
   {
        servCon.setRequestProperty("Cookie", m_strCurrentCookie);
   }

   servCon.setDoOutput(true);
   servCon.setDoInput(true);
   servCon.setRequestMethod("POST");

   StringBuffer postString = new StringBuffer();

    /*I set some variables in the post string */

   java.io.DataOutputStream out = new java.io.DataOutputStream(
                              servCon.getOutputStream());

   out.writeBytes(postString.toString());
   out.close();

    java.io.BufferedReader in = new java.io.BufferedReader(
    new java.io.InputStreamReader(
     servCon.getInputStream()));

/*    get the cookie sent back by the servlet container for later...*/
   m_strCurrentCookie = servCon.getHeaderField("Set-Cookie");
   m_strCurrentCookie = m_strCurrentCookie.substring(0,
m_strCurrentCookie.indexOf(";"));

/*Do something with return from servlet*/


This is my Servlet:

public class Bounce extends javax.servlet.http.HttpServlet
{
     public void doPost(javax.servlet.http.HttpServletRequest request,
          javax.servlet.http.HttpServletResponse response)
     {
          javax.servlet.http.HttpSession session = request.getSession(true);

          /* get the contents of the request and "bounce" them back to the
user*/
          java.util.Enumeration headerContents = request.getHeaderNames();
          java.lang.StringBuffer headerString = new
java.lang.StringBuffer("");
          while (headerContents.hasMoreElements())
          {
               java.lang.String headerKey = (java.lang.String)
headerContents.nextElement();
               headerString.append(headerKey + "=");
               headerString.append(request.getHeader(headerKey) + "<BR>");
          }

        /*get an input stream and store it in another string*/
       java.lang.StringBuffer bodyStream = new java.lang.StringBuffer();
      try
      {
           java.io.BufferedReader bodyReader = new java.io.BufferedReader(
                       new
java.io.InputStreamReader(request.getInputStream()));

           java.lang.String bodyLine;
           while ((bodyLine = bodyReader.readLine()) != null)
           {
                bodyStream.append(bodyLine);
           }
           bodyReader.close();

           response.setContentType("text/html");
           java.io.PrintWriter outPost = response.getWriter();

           outPost.println("<HTML>");
           outPost.println("<TITLE>Bounce!</TITLE>");
           outPost.println("<BODY><H3>Header Data follows</H3><BR>");
           outPost.print(headerString.toString());
           outPost.println("<BR><H3>POST Data follows</H3><BR>");
           outPost.print(bodyStream.toString());
           outPost.println("</BODY>");
           outPost.println("</HTML>");
      }
      catch (java.io.IOException ioE)
      {
           System.out.println("IOException!");
      }
   }
}




--------------------------------------------------------------------------
To unsubscribe, email: tomcat-user-unsubscribe@jakarta.apache.org
For additional commmands, email: tomcat-user-help@jakarta.apache.org








Mime
View raw message