Listing of Servlet (Controller): AirlineTicketBookingServlet (Web Component)

You learned about servlets on Days 3 and 4. Listing C.10 shows the detailed code for the controller servlet described in Chapter 4 for the MVC application. Place these files in the directory called web_components_src, discussed on Day 16.

Listing C.10 AirlineTicketBookingServlet
 /*********************************************************************************  * Class Name:AirlineTicketBookingServlet.java  * Description:Controller servlet for the MVC Application   * @author Mandar S. Chitnis, Pravin S. Tiwari, Lakshmi AM.          @version 11.5   * Copyright (c) by Sams Publishing. All Rights Reserved. **********************************************************************************/ package com.sams.learnweblogic7.airlines.servlet; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; import javax.naming.*; import javax.rmi.*; import javax.ejb.*; import com.sams.learnweblogic7.airlines.businessobject.*; import com.sams.learnweblogic7.airlines.constants.*; import com.sams.learnweblogic7.airlines.sessionbean.*; import com.sams.learnweblogic7.airlines.exception.*; public class AirlineTicketBookingServlet extends HttpServlet {   String[][] jspMappings= {{"*","1","/ViewAvailFlightsPage"},{"*","2","/Login"},{"1","3","/Login"},  {"3","4","/DisplayConfirmation"},{"9","4","/DisplayConfirmation"},  {"4","7","/Welcome"},{"4","6","/Message"},{"6","10","/Welcome"},  {"3","5","/RegisterUserProfilePage"},{"2","5","/RegisterUserProfilePage"},  {"5","9","/Login"},{"2","4","/ViewUserProfilePage"},{"4","8","/Welcome"},  {"4","11","/ViewFlightDetails"},{"11","12","/Welcome"}};   ServletContext sc;   private String sep=System.getProperty( "line.separator" );   /****************************************************************************      * Method Name       : getServletInfo      * Input Parameters  : none      * Return Parameters : java.lang.String      * Exceptions thrown : None      * Description       : This method provides information about the servlet's                            functions   ****************************************************************************/   public String getServletInfo()   {     return "Airline Booking System's Controller servlet";   }   /***************************************************************************      * Method Name : init      * Input Parameters : ServletConfig      * Return Parameters : none      * Exceptions : none      * Description : This method is used to perform functions which should be                      carried over the entire life of the servlet.     **************************************************************************/   public void init(ServletConfig config) throws ServletException{     super.init(config);     sc=getServletConfig().getServletContext();   }     /**************************************************************************      * Method Name : doGet      * Input Parameters : HttpServletRequest, HttpServletResponse      * Return Parameters : none      * Exceptions : javax.servlet.ServletException, java.io.IOException      * Description : This method is called by the Get method of an http request.      *               Here, call the doPost method and pass the request      *               and response objects to the doPost method.     **************************************************************************/     public void doGet(HttpServletRequest req, HttpServletResponse resp)       throws ServletException, IOException     {         doPost(req,resp);     }     public void doPost(HttpServletRequest req, HttpServletResponse resp)       throws ServletException, IOException     {       try       {           //STEP-1 => Get the MVCAppValueObject from the HttpServletRequest           MVCAppValueObject inputValueObject=                   MVCAppValueFactory.getMVCAppValueObject(req);           //STEP-2 => Call the business method (if required)           //          and get the output MVCAppValueObject           MVCAppValueObject outputValueObject=                   businessMethod(inputValueObject, req);           //STEP-3 => Pass the outputValueObject to the respective JSP           //          based on action id           callJSP(req, resp, outputValueObject);       }catch(GenericException ge){         ge.printStackTrace();         req.setAttribute(MVCConstants.OUTPUT_MVCVALUEOBJECT, ge);         RequestDispatcher rd=sc.getRequestDispatcher("/ErrorPage");         rd.forward(req,resp);       }       catch(Exception e){         e.printStackTrace();         req.setAttribute(MVCConstants.OUTPUT_MVCVALUEOBJECT,                 new GenericException(e));         RequestDispatcher rd=sc.getRequestDispatcher("/ErrorPage");         rd.forward(req,resp);       }       finally       {         //add any other code that you feel appropriate         System.out.println("inside finally of doPost");       }     }     //STEP-2 => Call the business method (if required) and get the output     //          MVCAppValueObject     public MVCAppValueObject businessMethod(MVCAppValueObject inputValueObject,             HttpServletRequest req) throws Exception     {       MVCAppValueObject outputValueObject=new MVCAppValueObject();       CustomerServiceAgentHome customerServiceAgentHomeObj=null;       CustomerServiceAgentInterface customerServiceAgentRemoteObj=null;       TicketSalesAgentHome ticketSalesAgentHomeObj=null;       TicketSalesAgentInterface ticketSalesAgentRemoteObj=null;       HttpSession httpSessionObj=null;       Handle statefulBeanHandle=null;       String errorDesc="";       try       {         // Get the Previous and Current Action Ids         String previousActionID=(String)inputValueObject.                 get(JspFieldConstants.PREVIOUS_ACTION_ID);         String strActionID=(String)inputValueObject.                 get(JspFieldConstants.ACTION_ID);         int actionID=Integer.parseInt(strActionID);         switch(actionID)         {             // searching the list of flights available for a location and a date             case JspFieldConstants.SEARCH_ACTION_ID :                 customerServiceAgentHomeObj=lookupCustomerServiceAgentHome();                 customerServiceAgentRemoteObj=(CustomerServiceAgentInterface)                         PortableRemoteObject.narrow                         (customerServiceAgentHomeObj.create(),                         CustomerServiceAgentInterface.class);                 outputValueObject=                         customerServiceAgentRemoteObj.viewAvailableFlights                         (inputValueObject);                 String day=(String)inputValueObject.                         get(JspFieldConstants.CHECK_AVAIL_FLIGHTS_PAGE_DEP_DAY);                 String month=(String)inputValueObject.                         get(JspFieldConstants.CHECK_AVAIL_FLIGHTS_PAGE_DEP_MONTH);                 String year=(String)inputValueObject.                         get(JspFieldConstants.CHECK_AVAIL_FLIGHTS_PAGE_DEP_YEAR);                 Calendar buildSqlDate=Calendar.getInstance();                 buildSqlDate.set(Integer.parseInt(year),                         Integer.parseInt(month), Integer.parseInt(day));                 java.sql.Date bookDate=                         new java.sql.Date(buildSqlDate.getTime().getTime());                 outputValueObject.put(JspFieldConstants.                         DISPLAY_AVAIL_FLIGHTS_PAGE_DEP_DATE, bookDate.toString());                 outputValueObject.put(JspFieldConstants.ACTION_ID, strActionID);                 outputValueObject.put(JspFieldConstants.PREVIOUS_ACTION_ID,                         previousActionID);                 return outputValueObject;             // viewing the profile of the existing user based on user name and                     password             case JspFieldConstants.VIEW_PROFILE_ACTION_ID :                 outputValueObject.put(JspFieldConstants.ACTION_ID, strActionID);                 outputValueObject.put(JspFieldConstants.PREVIOUS_ACTION_ID,                         previousActionID);                 return outputValueObject;             // user selects a particular flight he wants to buy from the list             // of available flights             case JspFieldConstants.BOOK_ACTION_ID :                 // now since we are not doing any business operations we simply                 // return the inputValueObject.                 outputValueObject=inputValueObject;                 return outputValueObject;             case JspFieldConstants.LOGIN_ACTION_ID :                 customerServiceAgentHomeObj=lookupCustomerServiceAgentHome();                 customerServiceAgentRemoteObj=(CustomerServiceAgentInterface)                         PortableRemoteObject.narrow(customerServiceAgentHomeObj.                         create(),CustomerServiceAgentInterface.class);                 MVCAppValueObject userProfileValueObject=                         customerServiceAgentRemoteObj.authenticateUser                         (inputValueObject);                 httpSessionObj=req.getSession(true);                 //if the user has come from the view profile page, then do this               if((Integer.parseInt(previousActionID)) == 2)               {               // time to create a session (STATEFULL SESSION BEAN) for the user                 ticketSalesAgentHomeObj=lookupTicketSalesAgentHome();                 ticketSalesAgentRemoteObj=(TicketSalesAgentInterface)                         PortableRemoteObject.narrow(ticketSalesAgentHomeObj.                         create(),TicketSalesAgentInterface.class);                 // STEP (1) : put the user information in session for future use                 ticketSalesAgentRemoteObj.putUserInformation                         (userProfileValueObject);                   outputValueObject=userProfileValueObject;               }               else               {//the user has come here after selecting flight details                 // time to create a session (STATEFULL SESSION BEAN) for the user                 ticketSalesAgentHomeObj=lookupTicketSalesAgentHome();                 ticketSalesAgentRemoteObj=(TicketSalesAgentInterface)                         PortableRemoteObject.narrow(ticketSalesAgentHomeObj.                         create(),TicketSalesAgentInterface.class);                 // ******* now do three things here ....                 // STEP (1) put the user informtion in session for future use                 // STEP (2) add the ticket details in the user session                 // STEP (3) get all the informtion from the session                 //(user information that is set in STEP 1 and ticket informtion                 //from STEP 2                 // STEP (1) : put the user informtion in session for future use                 ticketSalesAgentRemoteObj.putUserInformation                         (userProfileValueObject);                 // STEP (2) add the ticket details in the user session                 ticketSalesAgentRemoteObj.addOrder(inputValueObject);                 // STEP (3) get all the informtion from the session                 outputValueObject=ticketSalesAgentRemoteObj.getSessionData();               }               // Now you need to put the handle of this STATEFUL SESSION BEAN               // in the HttpSession               statefulBeanHandle=ticketSalesAgentRemoteObj.getHandle();               // this handle is stored in HttpSession               httpSessionObj.setAttribute(MVCConstants.SESSION_HANDLE,                       statefulBeanHandle);               outputValueObject.put(JspFieldConstants.ACTION_ID, strActionID);               outputValueObject.put(JspFieldConstants.PREVIOUS_ACTION_ID,                       previousActionID);               return outputValueObject;             case JspFieldConstants.REGISTER_ACTION_ID :             // now since you are not doing any business operations, simply             // return the inputValueObject             outputValueObject=inputValueObject;             outputValueObject.put(JspFieldConstants.ACTION_ID, strActionID);             outputValueObject.put(JspFieldConstants.PREVIOUS_ACTION_ID,                     previousActionID);             return outputValueObject;             case JspFieldConstants.DISPLAY_CONFIRMED_FLIGHTS_CONFIRM_ACTION_ID :             // now that user has CONFIRMED THE TICKET, COMMIT the             // transaction. Also, the order is removed from the user session as             // it is already bought by the user and the new orders will             // be added to user session if he/she wishes to buy more             httpSessionObj=req.getSession(false);             if(httpSessionObj == null)             {               errorDesc="There seems to be some problem accessing your profile                       .... Please try again" + sep;               errorDesc=errorDesc + " Sorry for the inconvenience ";               throw new GenericException(errorDesc);             }else             {               statefulBeanHandle= (Handle)httpSessionObj.getAttribute                       (MVCConstants.SESSION_HANDLE);ticketSalesAgentRemoteObj=                       (TicketSalesAgentInterface) PortableRemoteObject.narrow                       (statefulBeanHandle. getEJBObject(),                       TicketSalesAgentInterface.class);               outputValueObject=ticketSalesAgentRemoteObj.confirmBooking();             }             outputValueObject.put(JspFieldConstants.ACTION_ID, strActionID);             outputValueObject.put(JspFieldConstants.PREVIOUS_ACTION_ID,                     previousActionID);             return outputValueObject;             case JspFieldConstants.DISPLAY_CONFIRMED_FLIGHTS_CANCEL_ACTION_ID :               httpSessionObj=req.getSession(false);               if(httpSessionObj == null)               {                 errorDesc="There seems to be some problem accessing your profile                         .... Please try again" + sep;                 errorDesc=errorDesc + " Sorry for the inconvenience ";                 throw new GenericException(errorDesc);               }else               {                 statefulBeanHandle=                         (Handle)httpSessionObj.getAttribute                         (MVCConstants.SESSION_HANDLE);                 ticketSalesAgentRemoteObj=(TicketSalesAgentInterface)                         PortableRemoteObject.narrow(statefulBeanHandle.                         getEJBObject(), TicketSalesAgentInterface.class);                 // remove the ticket order from the session and rollback the                 // transaction, if required                 ticketSalesAgentRemoteObj.cancelBooking();                }                outputValueObject=inputValueObject;                return outputValueObject;             case JspFieldConstants.VIEW_USER_PROFILE_PAGE_BACK_TO_SEARCH_                     ACTION_ID:             case JspFieldConstants.VIEW_USER_PROFILE_PAGE_LOGOUT_ACTION_ID:                httpSessionObj=req.getSession(true);                if(httpSessionObj.isNew())                {                 //do nothing                }else                {                 statefulBeanHandle=                         (Handle)httpSessionObj.getAttribute                         (MVCConstants.SESSION_HANDLE);      ticketSalesAgentRemoteObj=(TicketSalesAgentInterface) PortableRemoteObject.              narrow(statefulBeanHandle.getEJBObject(),              TicketSalesAgentInterface.class);                 // end the session                 if (ticketSalesAgentRemoteObj != null)                 {                   ticketSalesAgentRemoteObj.remove();                 }                   // you have already ended session for stateful session bean                   // now invalidate the session of the user from the servlet                   weblogic.servlet.security.ServletAuthentication.                           invalidateAll(req);                }                outputValueObject=inputValueObject;                return outputValueObject;             case JspFieldConstants.                     VIEW_USER_PROFILE_PAGE_FLIGHT_DETAILS_ACTION_ID :                httpSessionObj=req.getSession(false);                if(httpSessionObj == null)                {                 errorDesc="There seems to be some problem accessing your profile                         .... Please try again" + sep;                 errorDesc=errorDesc + " Sorry for the inconvenience ";                 throw new GenericException(errorDesc);                }else                {                 statefulBeanHandle=(Handle)httpSessionObj.                         getAttribute(MVCConstants.SESSION_HANDLE);                 ticketSalesAgentRemoteObj=(TicketSalesAgentInterface)                         PortableRemoteObject.narrow(statefulBeanHandle.                         getEJBObject(), TicketSalesAgentInterface.class);                 outputValueObject=ticketSalesAgentRemoteObj.getUserTicketInfo();                }                outputValueObject.put(JspFieldConstants.ACTION_ID, strActionID);                outputValueObject.put(JspFieldConstants.PREVIOUS_ACTION_ID,                        previousActionID);                return outputValueObject;             case JspFieldConstants.REGISTER_USER_PROFILE_PAGE_REGISTER_SUBMIT_                     ACTION_ID:                customerServiceAgentHomeObj=lookupCustomerServiceAgentHome();                CustomerServiceAgentInterface customerServiceAgentInterfaceObj=                         (CustomerServiceAgentInterface)PortableRemoteObject.                         narrow(customerServiceAgentHomeObj.create(),                         CustomerServiceAgentInterface.class);                customerServiceAgentInterfaceObj.createUserProfile(inputValueObject);                // after user profile is created you have nothing to return,                // so send the inputdata itself                outputValueObject=inputValueObject;                return outputValueObject;             case JspFieldConstants.THANK_YOU_PAGE_ACTION_ID:               //when the user clicks on OK button, remove his session from               //session object and then call on the first jsp                 httpSessionObj=req.getSession(false);                 if(httpSessionObj == null)                {                   // do nothing                }else                {                 weblogic.servlet.security.ServletAuthentication.invalidateAll(req);                }                outputValueObject.put(JspFieldConstants.ACTION_ID, strActionID);                outputValueObject.put(JspFieldConstants.PREVIOUS_ACTION_ID,                        previousActionID);                return outputValueObject;             default:         }         }catch(GenericException exp)         {            httpSessionObj=req.getSession(false);            if(httpSessionObj==null)            {               // do nothing            }else            {             statefulBeanHandle=(Handle)httpSessionObj.                     getAttribute(MVCConstants.SESSION_HANDLE);             if (statefulBeanHandle!= null)             {               ticketSalesAgentRemoteObj=(TicketSalesAgentInterface)                       PortableRemoteObject.narrow                       (statefulBeanHandle.getEJBObject(),                       TicketSalesAgentInterface.class);               ticketSalesAgentRemoteObj.remove();             }             // you have already ended session for stateful session bean             // now invalidate the session of the user from the servlet also             weblogic.servlet.security.ServletAuthentication.invalidateAll(req);            }             throw exp;           }catch(Exception exp)           {              httpSessionObj=req.getSession(true);              if(httpSessionObj.isNew())              {                 // you may want to throw an exception here              }else              {               statefulBeanHandle=                       (Handle)httpSessionObj.getAttribute                       (MVCConstants.SESSION_HANDLE);               if (statefulBeanHandle != null)               {                   ticketSalesAgentRemoteObj=(TicketSalesAgentInterface)                           PortableRemoteObject.narrow                           (statefulBeanHandle.getEJBObject(),                           TicketSalesAgentInterface.class);                 ticketSalesAgentRemoteObj.remove();               }               // you have already ended session for stateful session bean               // now invalidate the session of the user from the servlet too               weblogic.servlet.security.ServletAuthentication.invalidateAll(req);              }             throw new GenericException(exp);           }           return outputValueObject;     }     public void callJSP(HttpServletRequest req, HttpServletResponse resp,             MVCAppValueObject outputValueObject) throws Exception   {         // get the Previous and Current Action Id's         String previousActionID=(String)outputValueObject.                 get(JspFieldConstants.PREVIOUS_ACTION_ID);         String presActionID=(String)outputValueObject.                 get(JspFieldConstants.ACTION_ID);         String jspToBeCalled=getNextJSPToBeCalled(previousActionID,                 presActionID);         req.setAttribute(MVCConstants.OUTPUT_MVCVALUEOBJECT, outputValueObject);         RequestDispatcher rd=sc.getRequestDispatcher(jspToBeCalled);         rd.forward(req,resp);       }   /**      * Look up the Airline bean's home interface using JNDI.      */     private CustomerServiceAgentHome lookupCustomerServiceAgentHome()             throws NamingException     {     Hashtable h=new Hashtable();     h.put(Context.INITIAL_CONTEXT_FACTORY, MVCConstants.             WEBLOGIC_INITIAL_CONTEXT_FACTORY);     h.put(Context.PROVIDER_URL, MVCConstants.WEBLOGIC_PROVIDER_URL);     Context ctx=new InitialContext(h);     try {       Object home=(CustomerServiceAgentHome)               ctx.lookup("CustomerServiceAgentBean");       return (CustomerServiceAgentHome)PortableRemoteObject.               narrow(home, CustomerServiceAgentHome.class);     }catch (NamingException ne) {       System.out.println("Unable to lookup the EJBHome.Verify the ejb JNDI               name CustomerServiceAgentHome on the WebLogic server");       throw ne;     } }   /**      * Look up the TicketSalesAgent bean's home interface using JNDI.      */     private TicketSalesAgentHome lookupTicketSalesAgentHome() throws             NamingException     {     Hashtable h=new Hashtable();     h.put(Context.INITIAL_CONTEXT_FACTORY,             "weblogic.jndi.WLInitialContextFactory");     h.put(Context.PROVIDER_URL, "t3://localhost:7001");     Context ctx=new InitialContext(h);     try {       Object home=(TicketSalesAgentHome)ctx.lookup("TicketSalesAgent");       return (TicketSalesAgentHome) PortableRemoteObject.narrow(home,               TicketSalesAgentHome.class);     } catch (NamingException ne) {       System.out.println("Unable to lookup the EJBHome.  Verify the ejb JNDI               name TicketSalesAgentHome on the WebLogic server");       throw ne;     }     }     private String getNextJSPToBeCalled(String prevActionId, String presActionId)     {       for(int i=0; i < jspMappings.length; i++)       {         if(jspMappings[i][0].equals(prevActionId))         {           for(int j=1;j<jspMappings[i].length;j++)           {             if(jspMappings[i][j].equals(presActionId))             {               return jspMappings[i][j+1];             }           }          }       }//end of for     return "FAILED";     } } 


Sams Teach Yourself BEA WebLogic Server 7. 0 in 21 Days
Sams Teach Yourself BEA WebLogic Server 7.0 in 21 Days
ISBN: 0672324334
EAN: 2147483647
Year: 2002
Pages: 339

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net