Java Q&A

by David Reilly



Example 1:



<form action="/servlets/FormServlet" method="post">

<input type="hidden" name=useraction  value="enroll">

<input type="hidden" name=customer_id value="942004961">

My name  is : <input type="text" name=username value="" size=20><br>

My email is : <input type="text" name=email value="" size=20><br>

<input type=submit>



Example 2: 



<p> Would you like to :- <ul>

<li> <a href="/servlets/Shopping?order=447&action=add>Add items to your order</a>

<li> <a href="/servlets/Shopping?order=447&action=del>Delete items from your order</a>

<li> <a href="/servlets/Shopping?order=447&action=ship>Ship the current order</a>







Listing One

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class WriteCookieServlet extends javax.servlet.http.HttpServlet

{

        public void doGet(HttpServletRequest req, 

                          HttpServletResponse res) throws IOException

        {

              ServletOutputStream out = res.getOutputStream();

              res.setContentType ("text/html");

              // Output a form to request data

              out.println ("<form method=post action='WriteCookieServlet'>");

              out.println ("Name : <input type=text name=name size=15><br>");

              out.println ("Email: <input type=text name=email size=15><br>");

              out.println ("<input type=submit></form>");

        }

        public void doPost(HttpServletRequest req, 

                           HttpServletResponse res) throws IOException

        {

                ServletOutputStream out = res.getOutputStream();

                res.setContentType ("text/html");

                // Check to see if an email was submitted

                String email = req.getParameter("email");

                if (email != null)

                {

                        // Store as a cookie

                        Cookie cookie = new Cookie("email", email);

                        res.addCookie(cookie);

                }

                // Check to see if an email was submitted

                String name = req.getParameter("name");

                if ( (name != null) && (!name.equals("")) )

                {

                        // Store as a cookie

                        Cookie cookie = new Cookie("name", name);

                        res.addCookie(cookie);

                }

                out.println ("Thank you for registering");

                out.println ("<a href=

                    'ReadCookieServlet'>Click here to read cookie data</a>");

        }

}



Listing Two

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;



public class ReadCookieServlet extends javax.servlet.http.HttpServlet

{

        public void doGet(HttpServletRequest req, 

                          HttpServletResponse res) throws IOException

        {

                String name  = null;

                String email = null;

                ServletOutputStream out = res.getOutputStream();

                res.setContentType ("text/html");

                // Search for name & email address

                Cookie list[] = req.getCookies();

                for (int cookieIndex = 0; 

                         cookieIndex < list.length; cookieIndex++)

                {

                        String cookiename = list[cookieIndex].getName();

                        if ( cookiename.equals ("name") )

                        {

                                // Get cookie data value

                                name = list[cookieIndex].getValue() ;

                        }

                        else

                        if ( cookiename.equals("email") )

                        {

                                // Get cookie data value

                                email = list[cookieIndex].getValue() ;

                        }

                }

                if (name != null)

                        out.println ("Hello " + name + "<br>");

                else

                        out.println ("Cookie 'name' not found<br>");



                if (email != null)

                        out.println ("Your email is " + email + "<br>");

                else

                        out.println ("Cookie 'email' not found<br>");

        }

}



Listing Three

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;



public class SessionCounterServlet extends javax.servlet.http.HttpServlet

{

        public void doGet(HttpServletRequest req, 

                          HttpServletResponse res) throws IOException

        {

                ServletOutputStream out = res.getOutputStream();

                res.setContentType ("text/html");

                // Get user session

                HttpSession userSession = req.getSession(true);



                // Check to see if there is a sessioncounter key

                String sessionCounter = 

                           (String) userSession.getValue("session_counter");

                if (sessionCounter == null)

                        sessionCounter = "1";

                else

                {

                        // increment counter for each request

                        int count = Integer.parseInt(sessionCounter);

                        count++;

                        sessionCounter = String.valueOf(count);

                }

                // Place modified state data back in session

                userSession.putValue("session_counter", sessionCounter);



                out.println ("Number of times 

                                visited this session : " + sessionCounter);

                out.println ("<br>Refresh this 

                                 page to see change in session count");

        }

}





Listing Four

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;



public class NoCookieSessionServlet extends javax.servlet.http.HttpServlet

{

        // Context allows us to lookup sessions

        private HttpSessionContext context;



        public void doGet(HttpServletRequest req, 

                              HttpServletResponse res) throws IOException

        {

                ServletOutputStream out = res.getOutputStream();

                res.setContentType ("text/html");

                try

                {

                        // Get user session

                        // HttpSession userSession = req.getSession(true);

                        HttpSession userSession = getSession(req);

                        // Check to see if there is a sessioncounter key

                        String sessionCounter = (String) userSession.

                                       getValue("no_cookie_session_counter");

                        if (sessionCounter == null)

                                sessionCounter = "1";

                        else

                        {

                                // increment counter for each request

                                int count = Integer.parseInt(sessionCounter);

                                count++;

                                sessionCounter = String.valueOf(count);

                        }

                        // Place modified state data back in session

                        userSession.putValue("no_cookie_session_counter", 

                                                      sessionCounter);

                        out.println ("Number of times visited this session : 

                                                      " + sessionCounter);

                        out.println ("<br><a href='" + encodeUrl(

                                    "NoCookieSessionServlet", userSession) );

                        out.println ("'>Click here to reload this page</a>");



                        // Output a dummy form, to test session-tracking

                        out.println ("<p><form action=

                                   'NoCookieSessionServlet' method=post>");

                        out.println ("Test field <input type=text name=test 

                                    value='default value'><br>");

                        out.println ("<input type=submit>");

                        out.println (encodeForm(userSession));

                        out.println ("</form>");

                }

                catch(IllegalStateException ise)

                {

                        out.println ("Invalid session");

                }

        }

        public void doPost(HttpServletRequest req, 

                           HttpServletResponse res) throws IOException

        {

                doGet(req,res);

        }

        private HttpSession getSession(HttpServletRequest req)

        {

               // Create a local variable to hold session

               HttpSession session = null;

               // Check to see if a session ID was specified as CGI paramater

               String sessionID = req.getParameter ( "sessionid" );

               // Check to see if this is the first invocation of the servlet

               if ( (context == null) || ( sessionID == null) )

               {

                        // Yes, so create brand new sessions.

                        session = req.getSession(true);

                        // If session context not stored, get for later

                        if (context == null)

                                context = session.getSessionContext();

               }

               else

               {

                        // No, so we can attempt to look up the session

                        session = context.getSession (sessionID);

                        // Check to see session is really valid

                        if (session == null)

                        {

                                // No, so create a new one

                                session = req.getSession(true);

                        }

               }

               return session;

        }

        private String encodeUrl (String url, HttpSession session)

        {

                String sessionId = session.getId();

                return ( url + "?sessionid=" + sessionId );

        }

        private String encodeForm (HttpSession session)

        {

                String sessionId = session.getId();

                return ("<input type=hidden name=sessionid value='" 

                                                      + sessionId + "'>");

        }

}











5



