⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 controllerservlet.java

📁 ORACLE AQ sample 演示的如何出列
💻 JAVA
字号:

/**
 * @author  Rajat Gupta
 * @version 1.0
 *
 * Name of the Application        :  ControllerServlet.java
 * Development Environment        :  Oracle 9i JDeveloper
 * Creation/Modification History  :
 *
 *    Rajat Gupta       15-Jan-2001      Created
 *
 */

// Import Statements
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;

import java.io.IOException;

import java.util.Hashtable;
import java.util.Vector;

import java.net.URL;

import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.NamedNodeMap;

import oracle.xml.parser.v2.DOMParser;
import oracle.xml.parser.v2.XMLDocument;
import oracle.xml.parser.v2.XMLParser;
import oracle.xml.parser.v2.XMLParseException;

import oracle.otnsamples.AQ.Manager.Manager;
import oracle.otnsamples.AQ.Helper.CreateURL;

import oracle.xml.parser.schema.XSDBuilder;
import oracle.xml.parser.schema.XMLSchema;


/**
 * This application follows the Model-View-Controller (MVC) architecture. The Model
 * is formed by the Manager and Helper classes. The View is formed by the JSP and
 * HTML files. This Servlet forms the Controller. Each and every request and response
 * has to pass through this Servlet. On initialization of this servlet, the XML file
 * Control.xml is parsed and its contents are stored in a Hashtable. For more
 * information on Control.xml please refer to the header in the XML file. Through
 * Reflection, the Manager classes are invoked by this Servlet. The instances of
 * the manager classes are then cached i.e. stored in a hashtable. This makes the
 * application faster.
 * Every time there is a request from a JSP, HTML or maybe another Servlet, an event
 * is generated. For this event, the servlet gets the required parameters from the
 * Control.xml ( Hashtable ) and the necessary class and method are invoked. The
 * response is then forwarded to the necessary JSP/ HTML/ Servlet.
 * If there is an exception generated then another Manager class ExceptionManager.java
 * is instantiated which returns the necessary Exception String to be displayed to
 * the user.
 * So effectively, every request has an event associated with it which this Servlet
 * recognizes. This Servlet then does the necessary action for that event. On
 * completion, the response is forwarded to the required JSP file.
 */
public class ControllerServlet extends HttpServlet{

  /**
   * Hashtable to store parameters from Control.xml. For every key in hashtable,
   * the value stored is a Vector. This Vector contains Class Name, method Name
   * and JSP name in that order.
   *
   * @see Control.xml
   */
  private Hashtable m_controlTable;

  /**
   * This hashtable stores the instances of the manager classes. This basically
   * works as a cache from where we can reuse the manager objects once created.
   * This saves a lot of time as for every request we don't have to instantiate
   * the classes again.
   *
   * @see ComputerManager.java
   * @see CustomerManager.java
   * @see LoginManager.java
   * @see PrinterManager.java
   * @see RetailManager.java
   * @see ExceptionManager.java
   */
  private Hashtable m_managerObj = new Hashtable();

  /**
   * This field tells the Reflection that this is the type of argument
   * to be passed to the instantiating method in Manager class.
   */
  private Class m_requestArgs[] = {HttpServletRequest.class};

  /**
   * This field tells the Reflection that this is the type of argument
   * to be passed to the instantiating method in Exception Class.
   */
  private Class m_exceptionArgs[] = {HttpServletRequest.class, Exception.class};


  /**
   * Servlets Constructor.
   * Here, the file Control.xml is parsed and its contents are stored in a
   * hashtable for future use.
   *
   * @exception ServletException In case Servlet throws an exception
   * @param p_config HttpServlet Config Object
   * @see CreateURL.java
   */
  public void init(ServletConfig p_config) throws ServletException
  {
    super.init(p_config);
    try{
      // Parse the XML file, store in a HashTable.
      CreateURL createURL = new CreateURL();
      URL xmlURL = createURL.getURL("AQConfig/Control.xml");
      URL schemaURL = createURL.getURL("AQConfig/Control.xsd");

      m_controlTable = parseXML(xmlURL, schemaURL);

    }catch(Exception p_exp){
      // Log the Exception and Through it. Servlet Container takes care.
      p_config.getServletContext().log("Exception in init() of ControllerServlet : " + p_exp.getMessage());
      throw new ServletException(p_exp);
    }
  }


  /**
   * Process the HTTP doGet request.
   *
   * @param p_request HttpServlet Request Object
   * @param p_response HttpServlet Response Object
   * @exception ServletException In case Servlet throws an exception
   * @exception IOException In case a file is not found
   */
  public void doGet(HttpServletRequest p_request, HttpServletResponse p_response)
                                              throws ServletException, IOException{
    try{
      try{
        // Initialize Event
        String event_name = "";

        // parameter to be passed to the method through reflection
        Object params[] = {p_request};

        Vector requestParameters;

        if (p_request.getParameter("Event") != null){
          // Check if the Incoming Request is for Validating the User
          if (p_request.getParameter("Event").equals("Login")){

            // Get the various parameters for this event
            Vector loginParameters = (Vector)m_controlTable.get("Login");

            // Get the Manager Object from the Cache.
            Manager loginManager = (Manager)m_managerObj.get((String)loginParameters.elementAt(0));

            // If not present in cache, then create the Object and put in Cache
            if (loginManager == null){
              loginManager = (Manager)Class.forName((String)loginParameters.elementAt(0)).newInstance();
              m_managerObj.put((String)loginParameters.elementAt(0),loginManager);
            }

            // Get the method Object
            Method method = loginManager.getClass().getMethod((String)loginParameters.elementAt(1),m_requestArgs);

            // Invoke the specified method
            Object obj = method.invoke(loginManager,params);

            // Create the appropriate event if Login is successful
            event_name = p_request.getParameter("Event") +
                  p_request.getSession(false).getAttribute("User") + "Successful";
          }else{

            // If the incoming request is not for validating the user, get the user
            String user = (String)p_request.getSession(false).getAttribute("User");

            if (user == null){
              user="Default";
            }

            // Get the event
            event_name = user + p_request.getParameter("Event");
          }
          }else{
            throw new Exception("AQ-1011");
        }

        // Get the required parameters for the particular event
        requestParameters = (Vector)m_controlTable.get(event_name);

        // Get Manager object from the Cache
        Manager manager = (Manager)m_managerObj.get((String)requestParameters.elementAt(0));

        // If not present in cache, then create the Object and put in Cache
        if (manager == null){
          manager = (Manager)Class.forName((String)requestParameters.elementAt(0)).newInstance();
          m_managerObj.put((String)requestParameters.elementAt(0),manager);
        }

        // Get the method object
        Method method = manager.getClass().getMethod((String)requestParameters.elementAt(1),m_requestArgs);

        // Invoke the specified method
        Object obj = method.invoke(manager,params);

        // Forward the request to the requisite JSP
        p_request.getRequestDispatcher("/" + (String)requestParameters.elementAt(2)).forward(p_request, p_response);

      }catch(ClassNotFoundException p_classnotfoundexp){
        p_classnotfoundexp.printStackTrace();
        throw new Exception("AQ-1001");
      }catch(IllegalAccessException p_illegalexp){
        p_illegalexp.printStackTrace();
        throw new Exception("AQ-1002");
      }catch(NoSuchMethodException p_nomethodexp){
        p_nomethodexp.printStackTrace();
        throw new Exception("AQ-1003");
      }catch(InvocationTargetException p_invokeexp){
        Throwable ex = p_invokeexp.getTargetException();
        throw new Exception(ex.getMessage());
      }catch(InstantiationException p_instanceexp){
        p_instanceexp.printStackTrace();
        throw new Exception("AQ-1004");
      }
    }catch(Exception p_ex){
      try{
        // Get the required parameters for the exception event
        Vector exceptionParameters = (Vector)m_controlTable.get("Exception");

        // Get Manager object from the Cache
        Manager exceptionManager = (Manager)m_managerObj.get((String)exceptionParameters.elementAt(0));

        // If not present in cache, then create the Object and put in Cache
        if (exceptionManager == null){
          exceptionManager = (Manager)Class.forName((String)exceptionParameters.elementAt(0)).newInstance();
          m_managerObj.put((String)exceptionParameters.elementAt(0),exceptionManager);
        }

        // Get the method object
        Method method = exceptionManager.getClass().getMethod((String)exceptionParameters.elementAt(1),m_exceptionArgs);

        // Initialize the parameters to be passed to the method through reflection
        Object[] exception_params = {p_request,p_ex};

        // Invoke the specified method
        Object obj = method.invoke(exceptionManager,exception_params);

        // Forward the request to the requisite JSP
        p_request.getRequestDispatcher("/" + (String)exceptionParameters.elementAt(2)).forward(p_request, p_response);

      }catch(Exception p_exp){
        this.log("Exception in Catch of ControllerServlet : " + p_exp.getMessage());
        throw new ServletException(p_exp);
      }
    }
  }


  /**
   * Process the HTTP doPost request.
   *
   * @param p_request HttpServlet Request Object
   * @param p_response HttpServlet Response Object
   * @exception ServletException In case Servlet throws an exception
   * @exception IOException In case a file is not found
   */
  public void doPost(HttpServletRequest p_request, HttpServletResponse p_response)
                                            throws ServletException, IOException {
    doGet(p_request, p_response);
  }


  /**
   * This method parses the Control.xml, stores its contents in a Hashtable
   * and returns it.
   *
   * @param p_xmlURL URL to the Control.xml
   * @param p_schemaURL URL to the Control.xsd
   * @exception Exception In case a file is not found
   * @return Contains Control.xml parameters
   */
  static Hashtable parseXML(URL p_xmlURL, URL p_schemaURL) throws Exception{
    Hashtable controlParameters = new Hashtable();
    try{
      // Define the variables used for parsing
      Node childNode, node;
      NodeList nodeList;
      NamedNodeMap nnm;
      URL url;

      // Get an instance of the parser
      DOMParser parser = new DOMParser();
      XSDBuilder builder = new XSDBuilder();

      XMLSchema schemadoc = (XMLSchema)builder.build(p_schemaURL);
      parser.setXMLSchema(schemadoc);

      // Set various parser options: validation on,
      // warnings shown, error stream set to stderr.
      parser.setErrorStream(System.err);

      // This statement will be used when we write the schema for the XML file
      parser.setValidationMode(XMLParser.SCHEMA_VALIDATION);

      parser.showWarnings(true);

      // Parse the document.
      parser.parse(p_xmlURL);

      // Obtain the document.
      XMLDocument doc = parser.getDocument();

      // Get all the Child Nodes in a NodeList
      nodeList = doc.getFirstChild().getNextSibling().getNextSibling().getChildNodes();

      // Iterate through the nodelist and get the Attribute and value of
      // DataSource used to connect to the DataBase. Store these then in
      // the Hashtable.
      for (int i=0; i<nodeList.getLength() ; i++){
        Vector parameters = new Vector(3,1);

        childNode = nodeList.item(i);
        nnm = childNode.getAttributes();
        node = nnm.item(0);
        NodeList nl = childNode.getChildNodes();
        for (int j=0; j<nl.getLength(); j++){
          Node n = nl.item(j);
          parameters.addElement(n.getFirstChild().getNodeValue());
        }
        controlParameters.put(node.getNodeValue(),parameters);
      }
      return controlParameters;
    }catch(XMLParseException p_xmlexp){
      p_xmlexp.printStackTrace();
      throw new Exception("AQ-1017");
    }
    catch(IOException p_ioexp){
      p_ioexp.printStackTrace();
      throw new Exception("AQ-1005");
    }catch (Exception p_exp){
      throw p_exp;
    }
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -