In my experience of servlets, session tracking is part of the JSDK (Java
Servlet Development Kit)  module, and not part of the JSSI servlet, which
simply provides Java Server Side Include functionality.  JSSI is however a
servlet, and to get it working you most probably have JServ installed onto
Apache already.  Make sure that you have downloaded the JSDK and that it's
working properley (if JSSI is working it probably is already) and make
sure you are including the right package, which I believe is
'javax.servlet.http.*'

The following code snippet is an example of how I write all my servlets at
the enterance level.  It deals with authentication through session
objects, and passes everything else over to other code, which mostly
contains JDBC components for dynamic page generation.  You are welcome to
study the code and use it in your own servlets.  However, I am no expert
and not part of working dogs, although I subscribe to the list.  There's
probably some guru looking at this code and grimacing.  good luck anyway.

Don Howard


#StartSample
/***********************************
 * (C) 98/09/25 Ql8a W3 Engineering
 * Geezas: Ql8a
 * Status: Software - Public.
 **********************************/

package uk.co.townpages.servlet.kiosk;

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

import java.sql.*;  // can possibly move this to 'Sql.class'
import java.math.*;

import java.io.*;
import java.net.*;
import java.util.Date;
import java.util.*;
import java.text.*;

/**
*/
public class Op8 extends javax.servlet.http.HttpServlet implements
Runnable {

  //*Class Variables instantiated here
  public static boolean debug = false;
  //public static String servletName = new
String("uk.co.townpages.servlet.contact.Op8");
  public static String servletName;
  public static StringBuffer sb = new StringBuffer();
  public static String htroot = new
String("/uk.co.townpages.servlet.kiosk/htroot");
  Connection conn;
  Connection con1;
  Driver d;
  public static Statement stmt;
  public static Statement stmt1;
  public static Statement stmt2;
  public static Statement c1stmt;
  public static Statement c1stmt1;
  public static HttpServletRequest request;
  //public static String qrl;

  //*Variables instantiated in Section Service - alphabetical by variable
name
  String host;
  int port;
  PrintWriter out;

  //*Variables instantiated in Section QRL's - alphabetical by variable
name
  //String imgPath; - replaced by htroot/images
  String qrlString;
  String servletPath;
  Qrl qrls;

/*******************************************************************
 *
 * Section Service - this is the main method for
 * dealing with the requests and responses.  It is the main section
 * of a servlet, and comprises of either a service() method, or a
 * doPost and doGet method.
 */

/**
  */
  public synchronized void doPost (HttpServletRequest req,
HttpServletResponse resp)
   throws ServletException, IOException {
    doGet(req, resp);
  }

/**
  */
  public synchronized void doGet (HttpServletRequest req,
HttpServletResponse resp)
   throws ServletException, IOException {

    // Ql8a: start our timer asap
    //long startMS = System.currentTimeMillis();
    // Ql8a: create instances of variables delcared in class
    host=req.getServerName();
    port=req.getServerPort();

    request=req;

    try {
      // Start Authentication
      // Ql8a: Get the session object
      HttpSession session01 = req.getSession(true);
      if (session01.isNew()) {
        //traceD("Ql8a: "+servletName+": New Session");
        session01.putValue("username", "guest");
        session01.putValue("password", "punter");

        if (authentic8(session01)) {
          //traceD("Ql8a: "+servletName+": New Session authenticated");

          // Call the qrls object - currently methods, but soon to be
classes
          response(req, resp, session01);

        }
        else {
          authentic8Failed(resp);
        }
      }
      // if our user already has a session object, check if authentic.
      else {
        //traceD("Ql8a: "+servletName+": Existing Session");
        // if authentication is ok - go ahead!
        if (authentic8(session01)) {
          //traceD("Ql8a: "+servletName+": Existing Session
authenticated");

          // Call the qrls object - currently methods, but soon to be
classes
          response(req, resp, session01);

        }
        else {
          authentic8Failed(resp);
        }
      }
      // End Authentication
    }
    catch (SocketException e) {
      ServletOutputStream out = resp.getOutputStream();
      StringWriter sw = new StringWriter();
      e.printStackTrace(new PrintWriter(sw));
      out.print(sw.toString());
    }
    catch (Error er) {
      ServletOutputStream out = resp.getOutputStream();
      StringWriter sw = new StringWriter();
      er.printStackTrace(new PrintWriter(sw));
      out.print(sw.toString());
    }
    catch (Exception e) {
      ServletOutputStream out = resp.getOutputStream();
      StringWriter sw = new StringWriter();
      e.printStackTrace(new PrintWriter(sw));
      out.print(sw.toString());
    }

    // Ql8a: when the qrls() method returns, print out some performance
stats
    //long stopMS = System.currentTimeMillis();
    //long elapsed = stopMS - startMS;
    //traceP("Ql8a: "+servletName+".stop @ "+stopMS+" -
"+servletName+".elapsed = "+ elapsed+"\n");
    return;
  }


/*****************************************************************************/

/** <p>Ql8a: qrls - this method lists the pages that are available
  * to the user.  qrl's are either .</p>
  */
  public void response (HttpServletRequest req, HttpServletResponse resp,
HttpSession session01) throws ServletException, IOException {
    // Ql8a: start our timer asap
    long startQrlsMS = System.currentTimeMillis();
    //traceP("Ql8a startQrlsMS="+startQrlsMS+"ms\n");
    // Ql8a: create instances of variables delcared in class
    qrls = new Qrl();
    //imgPath="/images/";
    out = new PrintWriter(resp.getOutputStream());
    servletPath=""+host+":"+port+"/";

    // Ql8a: set default qrl to index if qrl=null, or set qrl = qrl
    if ((req.getParameter("qrl") == null)) {
      qrlString="index";
    }
    else {
      qrlString=(req.getParameter("qrl"));
    }

    // Ql8a: set the string buffer length to '0'
    sb.setLength(0);
    // Ql8a: set the content type
    resp.setContentType("text/html");
    // Ql8a: start to make the page
    htmlHead(qrlString);
    //htmlHeader();

    qrls.processor(qrlString);

    htmlFooter();
    htmlFoot();
    // comment out if you don't want the debug info
    htmlDebug(req, session01, qrlString);

    // Ql8a: print the output.
    // Ql8a: but first, some monitor output
    long qrlsElapsed = System.currentTimeMillis() - startQrlsMS;
    sb.append("\n-"+ qrlsElapsed+"ms");
    // Ql8a: required print section
    resp.setContentLength(sb.length()+2);
    out.println(""+sb);
    sb.setLength(0);
    out.flush();
    out.close();
    return;
  }
#StopSample





/*****************************************************************************/

/** <p>Ql8a: htmlHead - this is a standard header that is included before
all
  * methods that output html - refer to the 'qrls' method.</p>
  */
  public void htmlHead(String qrl) throws IOException {
    sb.append("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 3.2//EN'>\n");
    sb.append("<html>\n");
    sb.append("<head>\n");
    sb.append("<title>"+servletName+"</title>\n");
    sb.append("<meta http-equiv='Content-Type' content='text/html;
charset=iso-8859-1'>\n");
    sb.append("<meta name='FORMATTER' content='Ql8a'>\n");
    sb.append("<meta name='GENERATOR' content='Ql8a'>\n");
    sb.append("<meta name='AUTHOR' content='Ql8a'>\n");
    sb.append("<meta name='DESIGNER' content='Ql8a'>\n");
    sb.append("<meta name='DESCRIPTION' content='"+servletName+" -
"+qrl+"'>\n");
    sb.append("<meta name='KEYWORDS' content='"+servletName+" -
"+qrl+"'>\n");
    sb.append("<meta name='ROBOTS' content='NONE'>\n");
    sb.append("</head>\n");
    sb.append("<body bgcolor=\"white\" text=\"Black\">\n");
    return;
  }

/** <p>Ql8a: htmlHeader - standard output to come at the top of all
pages.</p>
  */
  public void htmlHeader() throws IOException, ServletException {
    // Start Logo Table
    sb.append("\n<h4>"+servletName+"</h4>");
    return;
  }

/** <p>Ql8a: htmlFooter - a standard footer included at the end of all
methods that
  * provide html output - refer to the 'qrls' method.</p>
  */
  public void htmlFooter() throws IOException {
    sb.append("\n<hr size=\"1\" color=\"#008080\">\n");
    sb.append("\n<applet code=\"Ql8aLogo\" codebase=\""+htroot+"/applet\"
align=\"baseline\" width=\"55\" height=\"30\"></applet><br>\n");
    return;
  }

/** <p>Ql8a: htmlFoot - a standard footer included at the end of all
methods that
  * provide html output - refer to the 'qrls' method.</p>
  */
  public void htmlFoot() throws IOException {
    sb.append("</body>\n");
    sb.append("</html>\n");
    return;
  }

/*****************************************************************************/

/** <p>Ql8a: htmlDebug - standard output that comes at the bottom of all
pages.</p>
  */
  public void htmlDebug(HttpServletRequest req, HttpSession session01,
String qrl) throws IOException {
    long startHtmlDebugMS = System.currentTimeMillis();
    sb.append("<hr size='1' color='#B69B72'>\n");
    sb.append("<b>Ql8a:</b> Debug Output for "+servletName+"<br>\n");
    sb.append("- sb.length = "+sb.length()+"<br>\n");
    sb.append("- serverName: req.getServerName() = "+req.getServerName()+"
& String.host = "+host+" <br>\n");
    sb.append("- serverPort: req.getServerPort() = "+req.getServerPort()+"
& int.port = "+port+" <br>\n");
    sb.append("- remoteAddr = "+req.getRemoteAddr()+"<br>\n");
    sb.append("- remoteHost = "+req.getRemoteHost()+"<br>\n");
    sb.append("- URLScheme = "+req.getScheme()+"<br>\n");
    sb.append("- protocol = "+req.getProtocol()+"<br>\n");
    sb.append("- htroot = "+htroot+"<br>\n");
    count(session01);
    long stopHtmlDebugMS = System.currentTimeMillis();
    long elapsedHtmlDebug = stopHtmlDebugMS - startHtmlDebugMS;
    return;
  }

/** <p>Ql8a: count - a session counter, counts the number of hits in a
session.
  * this method is used by the htmlFooter method.</p>
  */
  private void count(HttpSession session01) throws IOException {
    Integer count = (Integer) session01.getValue("sessiontest.counter");
    if (count==null) count = new Integer(1);
    else count = new Integer(count.intValue() + 1);
    session01.putValue("sessiontest.counter", count);
    sb.append("user = "+session01.getValue("username")+"<br>\n");
    sb.append("pass = "+session01.getValue("password")+"<br>\n");
    sb.append("sessionCount = "+count+"<br>\n");
    return;
  }


/*****************************************************************************/

/** <p>Ql8a: sqlError - standard output when encountering an SQLError.</p>

  */
  public void sqlError(SQLException e) throws ServletException,
IOException {
    sb.append("<br><b>Ql8a:</b> doh! Database Error in
"+servletName+"</b><br>\n"
             +"<b>SQLException e: </b> "+e+"<br>\n"
             +"<b>e.getErrorCode:</b> "+e.getErrorCode()+"<br>\n"
             +"<b>e.getSQLState(X/Open):</b> "+e.getSQLState()+"<br>\n");
    return;
  }

/*************************************************************************

* Trace components - redundant
*/

/**
  * <p>Trace the given string.</p>
  */
  private void trace(String s) {
    //System.out.println("\n"+servletName+".trace: " + s);
    //out.println("\n"+servletName+".trace: " + s);
    return;
  }

/**
  * <p>Trace the given string.</p>
  */
  private void traceD(String s) {
    System.out.println(servletName+".traceDebug: " + s);
    return;
  }

/**
  * <p>Trace the given string.</p>
  */
  private void traceE(String s) {
    System.err.println(servletName+".traceError: " + s);
    return;
  }

/**
  * <p>Trace the given string.</p>
  */
  private void traceP(String s) {
    //out.println(servletName+".tracePform: " + s);
    return;
  }


/*************************************************************************

* Authentication system
*/

/** Ql8a: authentic8  - authenticates the user for public access.
  */
  private boolean authentic8(HttpSession session01) {
    String user = "guest";
    String password = "punter";
    if (session01.getValue("username") != null &
session01.getValue("password") != null) {
      if (session01.getValue("username").equals(user) &
session01.getValue("password").equals(password)) {
        return true;
      }
      return false;
    }
    return false;
  }

/** Ql8a: authentic8Failed - what happens if you use the wrong username
  * and password.
  */
  public void authentic8Failed(HttpServletResponse resp) throws
ServletException, IOException {
    PrintWriter out = new PrintWriter(resp.getOutputStream());
    out.println("<b>Ql8a:</b> Imposter! Try that again 'n I'll cut your
throat out :~!\n");
    out.flush();
    out.close();
    traceE("Ql8a: "+servletName+".authentic8Failed (this shouldn't happen
- please report)");
    return;
  }


/*****************************************************
* Required Components
* The following methods are required by all servlets.
*/

/** Ql8a: Destroy the servlet.  This method is called once when the
  * servlet is unloaded.
  */
  public void destroy() {
    super.destroy();
    try {
      conn.close();
      con1.close();
    }
    catch (SQLException e) {
      sb.append("Failed to disconnect from database:"+e+"\n");
    }
    try {
      DriverManager.deregisterDriver(d);
    }
    catch (Exception e) {
      sb.append("\nderegisterDriver() failed:"+e+"\n");
    }

    //DriverManager.deregisterDriver(d);
  //trace("Ql8a: "+servletName+" destroyed");
  }

/** Ql8a: Initialize the servlet.  This method is called once when the
  * servlet is loaded.  It is guaranteed to complete before andy
  * requests are mede to the servlet.
  */
  public void init(ServletConfig conf) throws ServletException {
    super.init(conf);
    servletName = new String(this.getClass().getName());
    try {
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      //conn = DriverManager.getConnection("jdbc:odbc:contact");
      conn = DriverManager.getConnection("jdbc:odbc:contact");
      con1 = DriverManager.getConnection("jdbc:odbc:kioskInfo");
      stmt = conn.createStatement();
      stmt1 = conn.createStatement();
      stmt2 = conn.createStatement();
      c1stmt = con1.createStatement();
      c1stmt1 = con1.createStatement();
    }
    catch (Exception e) {  // Ql8a: (ClassNotFoundException and
SQLException)
      throw(new UnavailableException(2, this, "Ql8a: Sorry! The Database
didn't load!: " + e));  // Throw an UnvailableException
    }
  }

/** Ql8a: run method to implement runnable & synchronize qrls().
  */
  public void run() {
    trace("Ql8a: "+servletName+": public void run();");
  }

/* cul8a
*/
}


Bernhard Heinrich wrote:

> Hi,
> I am using Apache1.3.6 JServ1.0 and the Apache JSSI-servlet under
> WinNT.
>
> (1) I tried JSSI, but the session-tracking seems not to work:
> The request.getSession(false) always returns null; even if I try to
> start a new session in the SSI-servlet(via request.getSession(true)).
> Is there a trick?
>
> (2) How can I manage to insert (String)session-Object in existing
> HTML code?: Is there another way apart from using <servlet>-Tag?, or
> anoter way using the <servlet>-tag)
>
> (3) First I thougt it's something with the zones. (The ssi-servlet
> runs in another zone as the servlets working with the session.) Does
> the zone make a difference to the bound session-Objects?
>
> (4) There is something wondering me: the SSI-Servlet is NOT called by
> its zone (does not work: <servlet code=/zone1/myServlet>), but it must
> be called by its class: <servlet code="servlets.ssi.myServlet">.
> Hmm, is the ssi-called-servlet running in the JServ-Context at all? Or
> otherway round: Is the ssi-called-servlet-Context the same as the
> normal-servlet Context?
>
> Bernhard
> --
> ______________________________________________________________________
>
> Bernhard Heinrich
> mailto:[EMAIL PROTECTED]
> ______________________________________________________________________
>
> ------------------------------------------------------------
> To subscribe:    [EMAIL PROTECTED]
> To unsubscribe:  [EMAIL PROTECTED]
> Problems?:       [EMAIL PROTECTED]



------------------------------------------------------------
To subscribe:    [EMAIL PROTECTED]
To unsubscribe:  [EMAIL PROTECTED]
Problems?:       [EMAIL PROTECTED]

Reply via email to