Saturday, 24 November 2012

J2ee tutorial part 7 :- explorring request session and application scopes

//explorring request session and application scopes
package webcert.ch03.ex0302;

import java.io.*;
import java.util.*;

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

public class AttributesAllScopes extends HttpServlet {

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        /* Set the response type, retrieve the writer */
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out
                .write("<HTML><HEAD><TITLE>Show all the attributes, all scopes</TITLE></HEAD><BODY>");
        out.write("<H1>Show attributes for every scope</H1>");

        String attrName;
        Object attrValue;

        /* Set up a request attribute */

        request.setAttribute("my.request.attribute", "By special request");
       
        /* Set up a session attribute */
        request.getSession().setAttribute("my.session.attribute", "Today's session is about scope");
       
        out.write("<H2>Request Scope</H2>");
        Enumeration enum = request.getAttributeNames();
        while (enum.hasMoreElements()) {
            attrName = (String) enum.nextElement();
            attrValue = request.getAttribute(attrName);
            writeAttribute(out, attrName, attrValue);
        }

        out.write("<H2>Session Scope</H2>");
        HttpSession session = request.getSession();
        enum = session.getAttributeNames();
        while (enum.hasMoreElements()) {
            attrName = (String) enum.nextElement();
            attrValue = session.getAttribute(attrName);
            writeAttribute(out, attrName, attrValue);
        }

        out.write("<H2>Context (Application) Scope</H2>");
        ServletContext context = getServletContext();
        String myAttributeName = "com.osborne.conductor";
        context.setAttribute(myAttributeName, "Andre Previn");

        enum = context.getAttributeNames();
        while (enum.hasMoreElements()) {
            attrName = (String) enum.nextElement();
            attrValue = context.getAttribute(attrName);
            out.write("<BR />Attribute name: <B>" + attrName + "</B>, value: <B>"
                    + attrValue + "</B>");
        }

        // I know I put a String in there, so it's safe to cast my attribute
        // object back to a String

        String conductor = (String) context.getAttribute(myAttributeName);
        out.write("<BR /> Just used getAttribute() to obtain "
                + myAttributeName + " whose value is " + conductor);

        // Get rid of the attribute
        context.removeAttribute(myAttributeName);

        // Could have done this to remove attribute instead;

        // no harm in executing the code even though the attribute has gone.
        context.setAttribute(myAttributeName, null);

        // Check attribute has gone
        out.write("<BR />Value of attribute " + myAttributeName + " is now "
                + context.getAttribute(myAttributeName));

        /* Tidy up */
        out.write("</BODY></HTML>");

    }

    private void writeAttribute(PrintWriter out, String name, Object value) {

        out.write("<BR />Attribute name: <B>" + name + "</B>, value: <B>"
                + value + "</B>");

    }

}

//Session management example


/*
 * Created on 12-Sep-2004
 */

import java.io.*;
import java.util.*;

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

public class SessionDisplayer2 extends HttpServlet {

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        PrintWriter out = response.getWriter();
        response.setContentType("text/html");
        out.write("<HTML><HEAD>");
        out.write("<TITLE>Session Aspects</TITLE>");
        out.write("</HEAD><BODY>");

        // Only perform session handling code when requested
        if ("true".equals(request.getParameter("getSession"))) {
           
            // Only perform session invalidation code when requested
            String maxInact = request.getParameter("maxinact");
            if (maxInact != null) {
                int timeLimit = Integer.parseInt(maxInact);
                HttpSession session = request.getSession();
                session.setMaxInactiveInterval(timeLimit);
            }
            String invalidate = request.getParameter("invalidate");
            if ("true".equals(invalidate)) {
                request.getSession().invalidate();//invalidating session
            }
           
            doSessionStuff(request, out);
           
        } else {
            out
                    .write("<BR />Session not accessed on this request to SessionDisplayer servlet");
        }

        // Forms to simplify re-calling servlet
       
        // Ensure encoded URLs are used

        String servletURL = response.encodeURL("SessionDisplayer2");
       
        out.write("<FORM action=\"" + servletURL + "\" method=\"GET\">");
        out.write("<input type=\"hidden\" name=\"getSession\" value=\"true\">");
        out.write("<br /><input type=\"submit\" value=\"Recall Servlet: Access Session\"/>");
        out.write("</FORM>");

        out.write("<FORM action=\"" + servletURL + "\" method=\"GET\">");
        out.write("<input type=\"hidden\" name=\"getSession\" value=\"false\">");
        out.write("<br /><input type=\"submit\" value=\"Recall Servlet: Don't Access Session\"/>");
        out.write("</FORM>");

        out.write("<FORM action=\"" + servletURL + "\" method=\"GET\">");
        out.write("<input type=\"hidden\" name=\"getSession\" value=\"true\">");
        out.write("<input type=\"hidden\" name=\"invalidate\" value=\"true\">");
        out.write("<br /><input type=\"submit\" value=\"Invalidate Session Immediately\"/>");
        out.write("</FORM>");

        out.write("<FORM action=\"" + servletURL + "\" method=\"GET\">");
        out.write("<input type=\"hidden\" name=\"getSession\" value=\"true\">");
        out.write("<br />Enter new session time limit in seconds: <input type=\"text\" name=\"maxinact\" />");
        out.write("<br /><input type=\"submit\" value=\"Change Session Time Limit\"/>");
        out.write("</FORM>");

       
       
       
        // Conclude page
        out.write("</BODY></HTML>");
        response.flushBuffer();

    }

    private void doSessionStuff(HttpServletRequest request, PrintWriter out) {
        HttpSession session = request.getSession();
        setAccessAttribute(session);
        displaySessionStuff(request, out);
    }

    private void setAccessAttribute(HttpSession session) {
        Integer accessCount = (Integer) session.getAttribute("accessCount");
        int a;
        if (accessCount == null) {
            a = 1;
        } else {
            a = accessCount.intValue() + 1;
        }
        session.setAttribute("accessCount", new Integer(a));
    }

    private void displaySessionStuff(HttpServletRequest request, PrintWriter out) {
       
        HttpSession session = request.getSession();
        // Display things about the session
        int accessCount = ((Integer) session.getAttribute("accessCount"))
                .intValue();
        out.write("\n<P>Session has been accessed <B>" + accessCount
                + "</B> times</P>");
        out.write("\n<P>Session id is <B>" + session.getId() + "</B>.</P>");
        if (session.isNew()) {
            out.write("\n<P>The session is new.</P>");
        } else {
            out.write("\n<P>The session is old.</P>");
        }
        // Calculate age of session
        long creation = session.getCreationTime();
        long now = (new Date()).getTime();

        // Get difference in seconds
        long diffMilliSecs = now - creation;
        long diffSecs = diffMilliSecs / (1000);
        long minutes = diffSecs / 60;
        long seconds = diffSecs % 60;

        // Write out age in minutes and seconds
        out.write("\n<P>The session is " + minutes + " minutes and " + seconds
                + " seconds old.</P>");

        // Write out maximum inactive interval
        out.write("\n<P>Maximum inactive interval for session is <B>"
                + session.getMaxInactiveInterval() + "</B> seconds.</P>");

        if (request.isRequestedSessionIdFromCookie()) {
            out.write("\n<P>Session id comes from cookie JSESSIONID.</P>");
            Cookie[] theCookies = request.getCookies();
            for (int i = 0; i < theCookies.length; i++) {
                Cookie c = theCookies[i];
                out.write("<H2>Cookie </H2>" + c.getName());
                out.write("<BR />Domain: " + c.getDomain());
                out.write("<BR />Max Age: " + c.getMaxAge());
                out.write("<BR />Path: " + c.getPath());
                out.write("<BR />Value: " + c.getValue());
                out.write("<BR />Version: " + c.getVersion());
            }
        }
       
        if (request.isRequestedSessionIdFromURL()) {
            out.write("\n<P>Session id comes from URL.</P>");
        }
       
        out.write("\n<BR />End of session information");
       
    }


}

No comments:

Post a Comment

Custom single threaded java server

 package com.diffengine.csv; import java.io.*; import java.net.*; import java.util.Date; public class Server { public static void main(Str...