AJAX call example

ajax autocomplete example and ajax database application
JohenCorner Profile Pic
Published Date:02-08-2017
Your Website URL(Optional)
EJB 3.0 Database Persistence with Ajax in the UI While EJB 3.0 has facilitated database persistence, Ajax has simplified the user interface facet of web applications. Asynchronous JavaScript And XML (AJAX) is a web technique for developing asynchronous web applications using JavaScript, Document Object Model (DOM) andXMLHttpRequest technologies. AJAX provides dynamic interaction between a client and a server. In this chapter, we discuss the following: • TheXMLHttpRequest object • Creating an EJB 3.0 application • Creating a data source in WebLogic Server • Creating an entity bean • Creating a wrapper session bean • Creating a servlet client • Creating an Ajax user interface • Deploying the EJB 3 application to WebLogic Server • Testing the Ajax user interface aEJB 3.0 Database Persistence with Ajax in the UI The XMLHttpRequest Object TheXMLHttpRequest object, which is supported by most browsers, provides asynchronous communication between a web browser and an underlying server. Using the object, clients may submit XML data to a server, and retrieve it from the server, without reloading the page. XML data may be converted to HTML on the client side, using the DOM API and Extensible Stylesheet Transformations (XSLT). The implementations ofXMLHttpRequest may vary across browsers. For example, XMLHttpRequest an instance of an object is created in IE 6 as follows: var req = new ActiveXObject("Microsoft.XMLHTTP"); In Internet Explorer 7,XMLHttpRequest is available as a window object property. An instance of anXMLHttpRequest object in IE 7 is created as follows: var req = new XMLHttpRequest(); W3C has introduced anXMLHttpRequest object specification ( http://www.w3.org/ TR/XMLHttpRequest/) to standardize implementations of theXMLHttpRequest object. TheXMLHttpRequest object has various attributes/properties, which are discussed in the following table, to provide HTTP client functionality. Property Description onreadystatechange Sets the callback method for asynchronous requests. readyState Retrieves the current state of a request. 0—XMLHttpRequest object has been created. 1—The object has been created andopen() method has been invoked. 2—Thesend() method has been called, but the response has not been received. 3—Some data has been received that is available in the responseText property.responseXML produces null and response headers and status are not completely available. 4—Response has been received. responseText Retrieves the text of response from server. responseXML Retrieves the XML DOM of response from server. status Retrieves the HTTP status code of request. statusText Retrieves the status text of the HTTP request. XMLHttpRequest object methods, which are discussed in the following table, are used to open an HTTP request, send the request, and receive the response. 260 aChapter 8 Method Description abort() Aborts the current HTTP request. getAllResponseHeaders() Gets all the response headers. getResponseHeader(string header) Gets a specified response header. open(string method, string url, Opens a HTTP request. Does not send boolean asynch, string username, a request. Boolean parameter asynch string password) specifies if HTTP request is asynchronous; default value is true. Username and password are optional. send(data) Sends a HTTP request to the server, including data. Thesend() method is synchronous or asynchronous corresponding to the value of the asynch argument in the open() method. If synchronous, the method does not return until the request is completely loaded and the entire response has been received. If asynchronous, method returns immediately. setRequestHeader(string Sets HTTP request headers. headerName, string headerValue) In this chapter, we create an EJB 3.0 Ajax application in which an input form is validated using Ajax and persisted using EJB 3.0. The following procedure is used for a catalog entry form validation and submission: 1. A user inputs a catalog ID in a catalog entry form. 2. The catalog id value is sent to a servletdoGet method. The servlet looks up the remote component interface of a session bean and invokes avalidate() method that returns aCatalog entity instance to validate the catalog id. 3. The session beanvalidate() method runs a Java persistence language query using the catalog id value. If the query returns an empty list, thevalidate() method returnsnull, else it returns a list with aCatalog entity instance; the validate() method returns theCatalog entity instance. 4. In the servlet, if thevalidate() method returns null, the servlet constructs aString consisting of an XML elementvalidtrue/valid, which is returned to the browser that sent the catalog id value via Ajax. 5. In the catalog entry form, the XML is parsed and if the valid element value istrue, a validation message that the catalog ID specied i fi s valid gets displayed. A user may continue to fill the form and submit it to create a new catalog entry. 261 aEJB 3.0 Database Persistence with Ajax in the UI 6. If thevalidate() method returns aCatalog entity instance, the servlet constructs aString that consists of an element valid with text set tofalse and also consists of elements corresponding to theCatalog bean properties journal,publisher,edition, title, andauthor. TheString is returned to the browser, which parses theString and n fi ding a false value for the valid element displays a validation message that the catalog id value specie fi d is false. The JavaScript in the Catalog entry form JSP also l fi ls the form e fi lds with the values returned in theString and disables the Submit button. 7. If the catalog id is valid, a user may fill out the form and submit it, which invokes thedoPost method. In thedoPost method of the servlet, the input field values are retrieved and the remote business interface of the session bean is looked up. Thepersist() method of the session bean is invoked with the input form field values. 8. In thepersist() method of the session bean, a newCatalog entity instance is created from the input field values and the persist() method of the EntityManager is invoked to persist the entity instance to the database. Thus, a user did not have to fill out the form only to find later that a catalog id is not valid. Ajax validates the catalog id value and displays a validation message. Setting the environment We need to install Oracle Fusion Middleware 11g (http://www.oracle.com/ technology/software/products/middleware/index.html). We need to download the following two components from the For Development section. • Oracle WebLogic Server 11g Rel 1 (10.3.2) Net Installer • Oracle JDeveloper 11g Rel 1 ( (JDeveloper + ADF) First, install JDeveloper 11g Studio Edition. Also install Oracle database 10g/11g/ XE (including the sample schemas). We shall be using the XE version in this chapter. Create an Oracle database tableCATALOG with the following SQL script: CREATE TABLE Catalog(CatalogId VARCHAR(255), Journal VARCHAR(255), Publisher Varchar(255), Edition VARCHAR(255), Title Varchar(255), Author Varchar(255)); INSERT INTO Catalog VALUES('catalog1', 'Oracle Magazine', 'Oracle Publishing', 'September-October 2009','Oracle Fusion Middleware 11g: The Foundation for Innovation', 'David Baum'); INSERT INTO Catalog VALUES('catalog2', 'Oracle Magazine', 'Oracle Publishing', 'September-October 2009', 'Put Your Arrays in a Bind', 'Mark Williams'); 262 aChapter 8 Installing WebLogic Server Next, install WebLogic Server 11g. Subsequently, create a WebLogic server domain. A domain is an administration unit for WebLogic Server instances. Start the Fusion Middleware Configuration Wizard. Select Create a new WebLogic domain and click on Next: In the Domain Source window select Basic WebLogic Server Domain as the domain to generate. Click on Next: 263 aEJB 3.0 Database Persistence with Ajax in the UI Specify Domain name as base_domain and select the default Domain location. Click on Next: Specify the Administrator User name and User password and click on Next: 264 aChapter 8 Select WebLogic Domain Startup Mode as Development Mode, which is for developing applications. The development mode supports auto deployment of applications. Select JDK as Sun JDK 1.6 and click on Next: In the Select Optional Configuration window, select at least the Administration Server option and click on Next: 265 aEJB 3.0 Database Persistence with Ajax in the UI In the Configure the Administration Server window, select the default settings for server Name, Listen address, and Listen port (7001), and click on Next: As our domain will only have a single server, skip the following steps : = Configure Managed Servers = Configure Clusters = Configure Machines In the Configuration Summary window, click on Create: 266 aChapter 8 A WebLogic Server domain gets created. Click on Done: Creating an EJB 3.0 application in JDeveloper In this section, we create an EJB 3 application and project in JDeveloper 11g. Select New Application in JDeveloper 11g. Specify an Application Name and select Java EE Web Application as the Application Template. Click on Next. Specify a Project Name for the view controller project, the default being ViewController. Select EJB in the Available list and add to the Selected list of Project Technologies. Click on Next. Select the default Java settings for the view controller project, which include the package name, source path, and output directory, and click on Next. 267 aEJB 3.0 Database Persistence with Ajax in the UI Select the default EJB settings; select EJB Version as EJB 3.0, and select the Using annotations feature. Click on Next. Specify a Project Name for the model project, the default being Model. Select EJB in the Project Technologies. Click on Next. Select the default Java settings for the model project, which include the package name, Java Source Path, and the Output Directory. Click on Next. Select the default EJB settings; set EJB Version as 3.0 and select the Using annotations feature. Click on Finish. An EJB 3 application, which includes a view controller project and a model project, gets created. We shall be creating an EJB 3.0 entity bean in the Model project. We shall also create an EJB 3.0 session bean and servlet in the Model project. In the ViewController project, we shall create a JSP for the Ajax user interface. 268 aChapter 8 Creating a database connection We need to create a database connection to the Oracle database for generating an EJB 3.0 entity bean from theCATALOG table, which we created in the Setting the environment section. In the Database Navigator, right-click on EJB3Ajax and select New Connection. In the Create Database Connection, specify a Connection Name, and select Connection Type as Oracle (JDBC). Specify Username as OE and the Password for the OE schema. Select Driver Type as thin, Host Name as localhost, and SID as XE. Click on Test Connection to test the connection. If a connection gets established, click on OK. 269 aEJB 3.0 Database Persistence with Ajax in the UI A JDBC connection gets added to the Database Navigator. AnOracleDBConnection-jdbc.xml congu fi ration file gets created in the src/ META-INF directory. The configuration file specifies the connection settings such as the driver class and the connection URL. The cong fi uration file also specie fi s a JNDI data source,jdbc/OracleDBConnectionDS, which gets created when the JDBC connectionOracleDBConnection is created. The cong fi uration file is listed next: ?xml version = '1.0' encoding = 'windows-1252'? jdbc-data-source xmlns:xsi="http://www.w3.org/2001/XMLSchema- instance" xsi:schemaLocation="http://www.bea.com/ns/weblogic/jdbc-data- source http://www.bea.com/ns/weblogic/jdbc-data-source/1.0/jdbc-data- source.xsd" xmlns="http://www.bea.com/ns/weblogic/jdbc-data-source" nameOracleDBConnection/name jdbc-driver-params urljdbc:oracle:thin:localhost:1521:XE/url driver-nameoracle.jdbc.OracleDriver/driver-name properties property nameuser/name valueOE/value /property property nameservername/name valuelocalhost/value /property property 270 aChapter 8 nameportnumber/name value1521/value /property property namesid/name valueXE/value /property /properties password-encrypted46969068B219FCC29EC5B6B5A9B8F846D62D1A19 DF561D1E/password-encrypted /jdbc-driver-params jdbc-connection-pool-params test-table-namedual/test-table-name /jdbc-connection-pool-params jdbc-data-source-params jndi-namejdbc/OracleDBConnectionDS/jndi-name scopeApplication/scope /jdbc-data-source-params /jdbc-data-source Creating a data source in WebLogic Server As we shall be deploying the EJB 3.0 Ajax application to WebLogic Server, we need to create a data source in WebLogic Server for the Oracle database. The data source JNDI name should correspond to the data source JNDI name used in thepersistence. xml cong fi uration l fi e for the entity bean, which we shall create in the next section. We shall be using a data source with JNDI namejdbc/OracleDBConnectionDS; therefore, create a data source with JNDI namejdbc/OracleDBConnectionDS in WebLogic Server. Start the WebLogic Server and log in to the Administration Console. 271 aEJB 3.0 Database Persistence with Ajax in the UI Select the base_domainServicesJDBCData Sources node. To create a new data source, click on New in the Data Sources table as shown in the following screenshot: In the Create a New JDBC Data Source window, specify a data source Name, and specify JNDI Name for the data source as jdbc/OracleDBConnectionDS. Select Database Type as Oracle and select Database Driver as Oracle's Driver (Thin XA). Click on Next: 272 aChapter 8 As we selected the XA JDBC driver, the driver will support global transactions and the Two-Phase Commit transaction protocol. Click on Next in Transaction Options: 273 aEJB 3.0 Database Persistence with Ajax in the UI In the Connection Properties window, specify Database Name as XE, Host Name as localhost, Port as 1521, and Database User Name as OE. Specify the Password for the OE user and click on Next: In the Test Database Connection window, the Driver Class Name and the connection URL are specified. Click on Test Configuration to test the data source connection. If a connection gets established, click on Finish: 274 aChapter 8 A data source with JNDI namejdbc/OracleDBConnectionDS gets added to the Data Sources table. Click on the data source in the Data Sources table. The settings for the data source get displayed. Select the Targets tab and select the AdminServer as the target server. Click on Save. The target server settings get applied. 275 aEJB 3.0 Database Persistence with Ajax in the UI Click on the Monitoring tab and click on the Testing tab. Click on Test Data Source. If the test is successful, a message gets displayed as in the following screenshot: Creating an entity bean In this section, we create an entity bean from the database tableCATALOG. Select the Model project node in the Application navigator. Select FileNew. In the New Gallery window select Business TierEJB in the Categories and select Entities from Tables in Items. Click on OK. 276 aChapter 8 As discussed in some of the earlier chapters, in the Persistence Unit window, click on New to create a new persistence unit. Specify the persistence unit Name as em and specify JTA Data Source Name as jdbc/OracleDBConnectionDS. Select WebLogic Server 10 as the Server Platform. Click on OK. Click on Next in the Persistence Unit window. In the Type of Connection window, select Online Database Connection and click on Next. In Database Connection Details, select the OracleDBConnection and click on Next. In Select Tables, select the OE Schema and select the Auto Query checkbox. Shift the CATALOG table from the Available to the Selected list and click on Next. In General Options, specify the Package Name (default being model), and select the default Entity Class options. Click on Next. In Specify Entity Details, select Table Name as OE.CATALOG. Specify Entity Name as Catalog and Entity Class as model.Entity. Click on Next. In the Summary page, click on Finish. An entity class model.Catalog gets created. An entity bean configuration file persistence.xml also gets created in the META-INF directory. 277 aEJB 3.0 Database Persistence with Ajax in the UI Right-click on the Model project and select the Project Properties for the Model project. In the Project Properties window, select Libraries and Classpath. The libraries in the EJB 3.0 project get displayed. The libraries include the TopLink library, as the entity bean uses the TopLink persistence provider. Select the EJB Module node. The EJB Module displays the default data source JNDI name, the EJB Version, the connection, and the annotated entity bean class. Click on OK: 278 a

Advise: Why You Wasting Money in Costly SEO Tools, Use World's Best Free SEO Tool Ubersuggest.