Java/Servlets/Context — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 06:10, 1 июня 2010

Context accessor

import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ContextAccessor extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, java.io.IOException {
    //get a servlet context attribute
    ContextObject contextObj = (ContextObject) getServletContext()
        .getAttribute("com.jexp.ContextObject");
    if (contextObj != null)
      contextObj.put(request.getRemoteAddr(), "" + new java.util.Date());
    //display
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    out
        .println("<html><head><title>Servlet Context Attribute</title></head><body>");
    if (contextObj != null) {
      out.println("<h2>Servlet Context Attribute Values</h2>");
      out.println(contextObj.getValues());
    } else {
      out.println("<h2>Servlet Context Attribute is Null</h2>");
    }
    out.println("</body></html>");
  } //end doGet
}
//ContextObject.java
class ContextObject {
  private Map map;
  public ContextObject() {
    map = Collections.synchronizedMap(new HashMap());
  }
  public void put(Object key, Object value) {
    if (key == null || value == null)
      throw new IllegalArgumentException(
          "Invalid parameters passed to ContextObject.put");
    map.put(key, value);
  }
  public Map getMap() {
    return map;
  }
  public String getValues() {
    StringBuffer buf = new StringBuffer("");
    Set set = map.keySet();
    synchronized (map) {
      Iterator i = set.iterator();
      while (i.hasNext())
        buf.append((String) i.next() + "<br>");
    }
    return buf.toString();
  }
  public String toString() {
    return getClass().getName() + "[ " + map + " ]";
  }
}





Context Attributes Servlet

import java.io.PrintWriter;
import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class SessionTracker2 extends HttpServlet 
{
  public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException 
  {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    HttpSession session = req.getSession(true);
    Integer totalCount = (Integer) getServletContext().getAttribute("total");
    if (totalCount == null)
    {
      totalCount = new Integer(1);
    }
    else
    {
      totalCount = new Integer(totalCount.intValue() + 1);
    }
    Integer count = (Integer) session.getAttribute("count");
    if (count == null) {
      count = new Integer(1);
    } else {
      count = new Integer(count.intValue() + 1);
    }
    session.setAttribute("count", count);
    getServletContext().setAttribute("total", totalCount);
    out.println("<html><head><title>SessionSnoop</title></head>");
    out.println("<body><h1>Session Details</h1>");
    out.println("You"ve visited this page " + count + ((count.intValue() == 1) ? " time." : " times.") + "<br/>");
    out.println("Total number of visits: " + totalCount + "<br/>");
    out.println("<h3>Details of this session:</h3>");
    out.println("Session id: " + session.getId() + "<br/>");
    out.println("New session: " + session.isNew() + "<br/>");
    out.println("Timeout: " + session.getMaxInactiveInterval() + "<br/>");
    out.println("Creation time: " + new Date(session.getCreationTime()) + "<br/>");
    out.println("Last access time: " + new Date(session.getLastAccessedTime()) + "<br/>");
    out.println("</body></html>");
  }
}





Context binder

import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ContextBinder extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, java.io.IOException {
    //bind an object to the servlet context
    getServletContext().setAttribute("com.jexp.ContextObject",
        new ContextObject());
    //better display something
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    out
        .println("<html><head><title>Servlet Context Attribute</title></head><body>");
    out.println("<h2>Servlet Context Attribute Bound</h2>");
    out.println("Object: "
        + getServletContext().getAttribute("com.jexp.ContextObject"));
    out.println("</body></html>");
  } //end doGet
}
//ContextObject.java
class ContextObject {
  private Map map;
  public ContextObject() {
    map = Collections.synchronizedMap(new HashMap());
  }
  public void put(Object key, Object value) {
    if (key == null || value == null)
      throw new IllegalArgumentException(
          "Invalid parameters passed to ContextObject.put");
    map.put(key, value);
  }
  public Map getMap() {
    return map;
  }
  public String getValues() {
    StringBuffer buf = new StringBuffer("");
    Set set = map.keySet();
    synchronized (map) {
      Iterator i = set.iterator();
      while (i.hasNext())
        buf.append((String) i.next() + "<br>");
    }
    return buf.toString();
  }
  public String toString() {
    return getClass().getName() + "[ " + map + " ]";
  }
}





Context Parameters Servlet

Get settings from ServletContext

 
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class WebAppProperties extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
      IOException {
    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();
    ServletContext context = getServletContext();
    String displayName = context.getServletContextName();
    if (displayName == null) {
      displayName = "(no display-name element defined)";
    }
    out.println("<html>");
    out.println("<body>");
    out.println("<br>Name: " + displayName);
    out.println("<br>Context: " + req.getContextPath());
    out.println("<h2><center>");
    out.println("Initialization Parameters</center></h2>");
    out.println("<br>");
    out.println("<center><table>");
    Enumeration e = context.getInitParameterNames();
    while (e.hasMoreElements()) {
      String name = (String) e.nextElement();
      out.println("<tr>");
      out.println("<td>" + name + "</td>");
      out.println("<td>" + context.getInitParameter(name) + "</td>");
      out.println("</tr>");
    }
    out.println("</table></center>");
    out.println("</body>");
    out.println("</html>");
    out.flush();
  }
}





Servlets Context Sample

Set the context parameters in web.xml

// web.xml
/*
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.ru/xml/ns/j2ee" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xsi:schemaLocation="http://java.sun.ru/xml/ns/j2ee
         http://java.sun.ru/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
  <context-param>
    <param-name>name</param-name>
    <param-value>Joe</param-value>
  </context-param>
  <context-param>
    <param-name>password</param-name>
    <param-value>password</param-value>
  </context-param>
  <servlet>
    <servlet-name>ParameterServlet</servlet-name>
    <servlet-class>ParameterServlet</servlet-class>
    <init-param>
      <param-name>name</param-name>
      <param-value>Joe</param-value>
    </init-param>
    <init-param>
      <param-name>password</param-name>
      <param-value>password</param-value>
    </init-param>
  </servlet>
</web-app>
*/
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ParameterServlet extends HttpServlet {
  private String dbName = "";
  private String dbPassword = "";
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
    ServletContext context = getServletContext();
    dbName = context.getInitParameter("name");
    dbPassword = context.getInitParameter("password");
  }
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws IOException {
    ServletOutputStream out = res.getOutputStream();
    res.setContentType("text/html");
    out.println("<html><head><title>Basic Servlet</title></head>");
    out.println("<body>Database username is  <b>" + dbName);
    out.println("</b><br>Database password is  <b>" + dbPassword + "</b>");
    out.println("</body></html>");
  }
}





Using Contexts Servlet

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class UsingContexts extends HttpServlet 
{
    public void doGet(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException 
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession(true);
        Integer counter2 = (Integer) getServletContext().getAttribute ("counter2");
        if (counter2 == null) {
            counter2 = new Integer(1);
        } else {
            counter2 = new Integer(counter2.intValue() + 1);
        }
        getServletContext().setAttribute("counter2", counter2);
        Integer counter = (Integer) session.getAttribute("counter");
        if (counter == null) {
            counter = new Integer(1);
        } else {
            counter = new Integer(counter.intValue() + 1);
        } 
        session.setAttribute("counter", counter);
        out.println("<HTML>");
        out.println("<HEAD>");
        out.println("<TITLE>");
        out.println("Using Contexts");
        out.println("</TITLE>");
        out.println("</HEAD>");
        out.println("<BODY>");
        out.println("<H1>Using Contexts</H1>");
        out.println("Welcome! You have been here " + counter + " times.<BR>");
        out.println("Total page accesses: " + counter2 + "<BR>");
        if(session.isNew()){
            out.println("This is a new session.<BR>");
        } else {
            out.println("This is not a new session.<BR>");
        }
        out.println("The session ID: " + session.getId() + "<BR>");
        out.println("Last time accessed: " + new Date(session.getLastAccessedTime()) + "<BR>"); 
        out.println("Creation time: " + new Date(session.getCreationTime()) + "<BR>");
        out.println("Timeout length: " + session.getMaxInactiveInterval() + " seconds<BR>");
        out.println("</BODY>");
        out.println("</HTML>");
    } 
}