Java EE Course Material - Srikanth Pragada

August 25, 2017 | Author: Dany Cenas Vásquez | Category: Software Engineering, Data, Information Retrieval, Data Management Software, Areas Of Computer Science
Share Embed Donate


Short Description

Java EE...

Description

Java EE Course Material Srikanth Pragada (SCJP, SCWCD, SCBCD, MCTS for .Net 4.0, Oracle Database SQL Expert, Oracle PL/SQL Associate Developer)

COPYRIGHT Copyright @ 2016 by Srikanth Technologies. All rights reserved. No part of this book may be reproduced or distributed in any form or by any means, or stored in a database or retrieval system, without the prior written permission of the author & publisher – Srikanth Pragada, with the exception that the programs may be entered, stored, and executed in a computer system, but they may not be reproduced for publication. Although every precaution has been taken in the preparation of this book, the author assumes no responsibility for errors or omissions. Neither is any liability assumed for damages resulting from the use of information contained therein.

Srikanth Technologies

ABOUT THE AUTHOR Srikanth Pragada is the director of Srikanth Technologies, a software training company. He started programming in early 90s and worked with more than 15 different programming languages. Srikanth Pragada holds the following certifications:       

Sun Certified Java Programmer Sun Certified Web Component Developer Sun Certified Business Component Developer Oracle Database SQL Certified Expert Oracle PL/SQL Developer Certified Associate Microsoft Certified Technology Specialist for .NET 4.0 (Web Applications)

He currently conducts online, classroom and onsite training on C, Java, Oracle, Microsoft.NET and Android technologies. His website www.srikanthtechnologies.com provides more information about C, Java, Android programming, Oracle and Microsoft.Net. It contains online examinations, programs, projects, articles and his blog. When he is not teaching or learning, he would like to visit new places, read books, involve in sports and listen to music. He can be reached through his email address [email protected].

Srikanth Technologies

HOW TO USE THIS MATERIAL This is to be carried to classroom everyday as long as the contents of this material are being discussed. You are suggested to read relevant content before and after attending the class. Use picture and text to grasp the concept. Programs are to illustrate how to implement the concepts. Try the programs given in this material in your system.

REQUEST FOR FEEDBACK We have taken considerable effort to ensure accuracy of the contents of this material. However if you come across any mistakes or have any suggestions to improve the quality of this material, please take a few minutes of your valuable time to send mail to me at [email protected]. Alternatively you can visit my website www.srikanthtechnologies.com/feedback.aspx and provide feedback there.

Srikanth Technologies

JDBC

JDBC

1

Getting Started With Oracle11g Express Edition Oracle11g express edition provides HR account by default. But this account is locked by default. So you must log in as SYSTEM (DBA) to unlock this account. The password of this account is expired by default, so you have to reset password as well. Steps to unlock HR Account: 1. StartAll ProgramsOracle Database 11g Express EditionRun SQL Command Line. 2. Use CONNECT command at SQL> prompt to connect to Oracle using SYSTEM account. SQL>connect SYSTEM

3. When prompted to enter password, enter password that you gave at the time of installing Oracle. 4. Unlock HR account and reset password by giving following two commands at the SQL> prompt. SQL>alter user hr account unlock; SQL>alter user hr identified by hr;

5. Then connect Oracle as HR by using CONNECT command as follows: SQL>Connect hr/hr SQL>select * from tab; SQL>select * from jobs; …

Note: HR account comes with a set of tables like EMPLOYEES, JOBS, DEPARTMENTS etc.

Srikanth Technologies

JDBC

2

The following are some of the tables that come with HR account. The following are the tables we use in Java programs. SQL> desc jobs Name Null? Type ---------------------------------- -------- ------------ JOB_ID NOT NULL VARCHAR2(10) JOB_TITLE NOT NULL VARCHAR2(35) MIN_SALARY NUMBER(10) MAX_SALARY NUMBER(6) SQL> desc employees Name ---------------------------------EMPLOYEE_ID FIRST_NAME LAST_NAME EMAIL PHONE_NUMBER HIRE_DATE JOB_ID SALARY COMMISSION_PCT MANAGER_ID DEPARTMENT_ID SQL> desc departments Name ---------------------------------DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID

Null? Type -------- -------------NOT NULL NUMBER(6) VARCHAR2(20) NOT NULL VARCHAR2(25) NOT NULL VARCHAR2(25) VARCHAR2(20) NOT NULL DATE NOT NULL VARCHAR2(10) NUMBER(8,2) NUMBER(2,2) NUMBER(6) NUMBER(4) Null? -------NOT NULL NOT NULL

SQL>

Srikanth Technologies

Type -------------NUMBER(4) VARCHAR2(30) NUMBER(6) NUMBER(4)

JDBC

3

What is JDBC (Java Database Connectivity)?  The JDBC API provides universal data access from Java language  JDBC is Java API to execute SQL Statements. It is standard API to access databases from Java  Using JDBC API you can access any database that may run on any platform  The JDBC 4.x API is divided into two packages: java.sql and javax.sql. Both packages are included in the Java SE and Java EE platforms

What is JDBC Driver?  To use the JDBC API with a particular DBMS, you need a JDBC technology-based driver to access database  Driver must support at least ANSI SQL-2 Entry Level (1992)

Srikanth Technologies

JDBC

4

JDBC Components JDBC provides the following components as part of the JDK. JDBC driver manager

JDBC-ODBC bridge

The JDBC driver manager is the backbone of the JDBC architecture. It actually is quite small and simple; its primary function is to connect Java applications to the correct JDBC driver and then get out of the way. The JDBC-ODBC bridge allows ODBC drivers to be used as JDBC drivers. It provides a way to access less popular DBMS if JDBC driver is not implemented for it.

Important Interfaces The following are the interfaces provided with JDBC API. These interfaces are implemented by driver. A driver contains a collection of classes to implement these interfaces. Interface CallableStatement

Meaning The interface used to execute SQL stored procedures. Connection A connection (session) with a specific database. DatabaseMetaData Comprehensive information about the database as a whole. Driver The interface that every driver class must implement. PreparedStatement An object that represents a precompiled SQL statement. ResultSet A ResultSet provides access to a table of data. ResultSetMetaData An object that can be used to find out about the types and properties of the columns in a ResultSet. Srikanth Technologies

JDBC

Statement

5

The object used for executing a static SQL statement and obtaining the results produced by it.

Important Classes The following are the classes provided by JDBC API. These classes are provided in addition to interfaces mentioned above. Class Date

Description A thin wrapper around a millisecond value that allows JDBC to identify this as SQL DATE. DriverManager The basic service for managing a set of JDBC drivers. DriverPropertyInfo Driver properties for making a connection. Time A thin wrapper around java.util.Date that allows JDBC to identify this as SQL TIME value. Timestamp This class is a thin wrapper around java.util.Date that allows JDBC to identify this as SQL TIMESTAMP value. Types The class that defines constants that are used to identify generic SQL types, called JDBC types.

DriverManager Class  Part of java.sql package, used to manage JDBC drivers.  Sits between the application programs and the drivers.  Keeps track of the drivers that are available and handles establishing a connection between a database and the appropriate driver.

Srikanth Technologies

JDBC

6

Method Connection getConnection (String url, String un, String pwd) Driver getDriver(String url) Enumeration getDrivers() void registerDriver (Driver driver)

Meaning Establishes a connection with the specified database. Returns a driver that can understand the URL. Returns the drivers that are currently loaded. Registers the given driver.

Driver Interface  This is the interface that every driver has to implement.  Each driver should supply a class that implements the Driver interface. Method boolean acceptsURL(String url) Connection connect(String url, Properties info) int getMajorVersion() int getMinorVersion()

Meaning Returns true if the driver thinks that it can open a connection to the given URL. Connects to a database and returns connection object. Returns major version number. Returns minor version number.

Srikanth Technologies

JDBC

7

Connection interface  Represents a connection to specific database.  SQL statements are executed and results are returned within the context of a connection. Method Statement createStatement() Statement createStatement (int resultSetType, int resultSetConcurrency) DatabaseMetaData getMetaData() boolean isClosed()

Meaning Creates and returns an object of Statement Creates a Statement object that will generate ResultSet objects with the given type and concurrency Returns an object of DatabaseMetaData, which can be used to get information about the database Returns true if connection is closed

Srikanth Technologies

JDBC

8

CallableStatement prepareCall(String sql) PreparedStatement prepareStatement(String sql) void close()

Creates a callable statement Creates a prepared statement Closes the connection

Steps to connect to Oracle using OCI driver    

01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17:

Include ojdbc6.jar file in classpath of the application Load jdbc driver for Oracle using Class.forName() method Starting from Jdbc 4.0, loading driver class is optional Establish a connection to database by using DriverManager.getConnection() with required connection string, username and password. import java.sql.Connection; import java.sql.DriverManager; public class OracleOCIConnection { public static void main(String args[]) { try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con = DriverManager.getConnection ("jdbc:oracle:oci8:@","hr","hr"); System.out.println("Connected Using OCI driver"); con.close(); } catch(Exception ex) { ex.printStackTrace(); } } // end of main } // class

Srikanth Technologies

JDBC

9

Using Oracle’s Thin driver  Thin driver provided by Oracle belongs to Type 4 category of JDBC drivers.  This accesses oracle’s TNS listener on the server.  Connection string contains host, port number of listener, oracle instance name, username and password. 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16:

import java.sql.Connection; import java.sql.DriverManager; public class OracleThinConnection { public static void main(String args[]) { try (Connection con = DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:XE", "hr", "hr")) { System.out.println("Connected Using Thin Driver"); } catch (Exception ex) { ex.printStackTrace(); } } // end of main } // end of OracleThinConnection

Srikanth Technologies

JDBC

10

DataSource  Datasource objects can provide connection pooling and distributed transactions.  For convenience and portability, datasources can be bound to Java Naming and Directory Interface (JNDI) entities, so that you can access databases by logical names.  The datasource facility provides a complete replacement for the previous JDBC DriverManager facility.  You can use both facilities in the same application, but it is recommended that you use datasources.  Method setConnectionCachingEnabled(true) is used to turn on connection pooling. The DataSource interface is implemented by a driver vendor. It can be implemented in three different ways:  A basic DataSource implementation produces standard Connection objects that are not pooled or used in a distributed transaction.  A DataSource implementation that supports connection pooling produces Connection objects that participate in connection pooling, that is, connections that can be recycled.  A DataSource implementation that supports distributed transactions produces Connection objects that can be used in a distributed transaction, that is, a transaction that accesses two or more DBMS servers.

Srikanth Technologies

JDBC

11

The following are the properties related to connection pool. Property InitialLimit MaxLimit

MinLimit

Meaning Sets how many connections are created in the cache when it is created or reinitialized. Default is 0. Sets the maximum number of connection instances the cache can hold. The default value is Integer.MAX_VALUE, meaning that there is no limit enforced by the connection cache, so that the number of connections is limited only by the number of database sessions configured for the database. Sets the minimum number of connections the cache maintains. This guarantees that the cache will not shrink below this minimum limit. Default is 0.

1: import java.sql.Connection; 2: import oracle.jdbc.pool.OracleDataSource; 3: 4: public class OracleDatasourceConnection { 5: 6: public static void main(String[] args) 7: throws Exception { 8: OracleDataSource ods = new OracleDataSource(); 9: ods.setURL("jdbc:oracle:thin:@localhost:1521:xe"); 10: ods.setUser("hr"); 11: ods.setPassword("hr"); 12: 13: try (Connection con = ods.getConnection()) { 14: System.out.println 15: ("Connected To Oracle using DataSource"); 16: } 17: } // main() 18: }

Srikanth Technologies

JDBC

12

The following program enables connection pooling and sets connection pool settings: 1: import java.sql.Connection; 2: import java.util.Properties; 3: import java.util.Scanner; 4: import oracle.jdbc.pool.OracleDataSource; 5: 6: public class OracleDatasourceWithCP { 7: public static void main(String[] args) 8: throws Exception{ 9: OracleDataSource ods = new OracleDataSource(); 10: ods.setURL("jdbc:oracle:thin:@localhost:1521:xe"); 11: ods.setUser("hr"); 12: ods.setPassword("hr"); 13: ods.setConnectionCachingEnabled(true); 14: 15: Properties prop = new Properties(); 16: prop.setProperty("MinLimit", "5"); 17: prop.setProperty("MaxLimit", "25"); 18: prop.setProperty("InitialLimit", "5"); 19: ods.setConnectionCacheProperties(prop); 20: 21: try (Connection con = ods.getConnection()) { 22: System.out.println 23: ("Connected To Oracle using DataSource"); 24: } 25: } 26: }

Srikanth Technologies

JDBC

13

Steps to execute an SQL command  Establish a connection to database  Create a statement using createStatement() method of Connection interface  Execute an SQL statement using one of the methods of Statement interface 1: import java.sql.Connection; 2: import java.sql.DriverManager; 3: import java.sql.Statement; 4: 5: public class ExecuteUpdate { 6: public static void main(String args[]){ 7: try (Connection con = 8: DriverManager.getConnection 9: ("jdbc:oracle:thin:@localhost:1521:XE", 10: "hr", "hr"); 11: Statement st = con.createStatement()) { 12: 13: int count = st.executeUpdate("update employees 14: set salary=salary*1.1 where employee_id=120"); 15: 16: if (count == 1) 17: System.out.println("Updation is successful"); 18: else 19: System.out.println("Updation is unsuccessful"); 20: } catch (Exception ex) { 21: ex.printStackTrace(); 22: } 23: } // end of main 24: } // end of ExecuteUpdate

Srikanth Technologies

JDBC

14

Statement Interface  Is used to execute an SQL command.  At the time of creating Statement we have to specify what type of ResultSet is to be created from this Statement.  Only one ResultSet per a statement can be opened at a time. Method ResultSet executeQuery(String) int executeUpdate(String) boolean execute(String) Connection getConnection() ResultSet getResultSet() int getUpdateCount() void close()

Meaning Executes the query in the statement and returns ResultSet. Executes DML command and returns the no. of rows updated. Executes SQL command and returns true if query is executed. Returns the connection object that produced this statement. Returns current ResultSet. Returns update count of most recently executed command. Enables the resources to be released.

ResultSet Interface  Provides access to a set of rows.  Contains a cursor that points to a particular record in the ResultSet.  This cursor is positioned initially before the first row.  You can retrieve values of columns using get() methods. Columns can be referred either by column number or name.  Columns are numbered from 1.  A ResultSet may be either scrollable or forward only. It may be either updatable or read-only. The following are the constants declared in ResultSet interface that are used at the time of creating a Statement to specify the type of ResultSet required. Srikanth Technologies

JDBC

15

CONCUR_READ_ONLY

Concurrency mode for a ResultSet object that may NOT be updated. CONCUR_UPDATABLE Concurrency mode for a ResultSet object that may be updated. TYPE_FORWARD_ONLY The type for a ResultSet object whose cursor may move only forward. TYPE_SCROLL_INSENSITIVE The type for a ResultSet object that is scrollable but generally ResultSet is insensitive to changes made to the underlying data source while it is open. TYPE_SCROLL_SENSITIVE The type for a ResultSet object that is scrollable and reflects changes made to the underlying data source while the result set remains open.

ResultSet Record Pointer

Srikanth Technologies

JDBC

Method type get (int index) type get (String name) ResultSetMetaData getMetaData() boolean next() boolean wasNull() void close() boolean absolute(int row) void cancelRowUpdates() int findColumn(columnName) int getRow() boolean first () boolean last() boolean previous() void beforeFirst() void afterLast() boolean relative(int) boolean isLast() boolean isFirst() boolean isAfterLast() boolean isBeforeFirst()

16

Meaning Returns the value of the column identified by index. Returns the value of the column identified by name. Returns metadata of the ResultSet. Moves cursor to next row and returns true if next row is valid. Returns true when the last columns read was null. Closes ResultSet. Moves the cursor to the given row. Cancels the updates made to a row. Maps the given ResultSet column name to its ResultSet column index. Returns current row number. Row number starts with 1. Moves to first record. Returns true on success. Moves to the last record. Returns true on success. Moves to the previous record. Moves to immediately before first record. Moves to immediately after the last record. Moves forward or backward by specified number of rows. Returns true if cursor is on the last record. Returns true if cursor is on the first record. Returns true if cursor is after the last record. Returns true if cursor is before the first Srikanth Technologies

JDBC

void refreshRow() void update(int, value) void cancelRowUpdates() void moveToInsertRow() void insertRow() void deleteRow() void updateRow()

17

record. Refreshes current row with its most recent values in the database. Changes the existing data. Cancels the updates made to a row. Creates a new blank row. Appends the new row to the table. Deletes the current row of the ResultSet from the table. Updates the database with the new contents of the current row.

1: import java.sql.Connection; 2: import java.sql.DriverManager; 3: import java.sql.ResultSet; 4: import java.sql.Statement; 5: public class EmployeeList { 6: public static void main(String args[]) { 7: try (Connection con = 8: DriverManager.getConnection( 9: "jdbc:oracle:thin:@localhost:1521:XE","hr", "hr"); 10: Statement st = con.createStatement(); 11: ResultSet rs = 12: st.executeQuery 13: ("select employee_id,first_name from 14: employees where employee_id 10000"); stmt.addBatch("update employees set salary=salary+1000 where salary 0 }"> Updated Sucessfully!

emplist.jsp 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19:

select employee_id,first_name,salary from employees ${row.employee_id}, ${row.first_name},${row.salary} Srikanth Technologies

94

Java EE (Web Applications – I)

95

sqlplus.jsp 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42:

Enter Query : ${param.query} ${param.query} ${cn} ${colvalue} Srikanth Technologies

Java EE (Web Applications – I)

96

XML Tags The XML actions are divided into three categories: XML core actions, XML flow control actions, and XML transform actions. The XML set of actions in JSTL is therefore based on XPath.    

out, parse, set choose (when, otherwise) forEach, if transform (param)

Tag parse out set if when forEach transform param

Attributes doc, var, scope, select, escapeXml select, var, scope select, var, scope select var, select, begin, end, step doc, xml, xslt, var, scope, result name, value Srikanth Technologies

Java EE (Web Applications – I)

catalog.xml 01: 02: 03: 04: IBM Server 05: 150000 06: 07: 08: Dell Server 09: 165000 10: 11:

xmlread.jsp 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15:

:

Srikanth Technologies

97

Java EE (Web Applications – I)

98

Java Mail  JavaMail specifications provide a collection of abstract classes that define the common objects and their interfaces for any general mailing system.  JavaMail API allows mails to be sent and received using Java.  It supports the development of Mail Agents (programs used to send and receive mails) such as Outlook Express.  JavaMail providers implement the API and provide support for most common protocols.  Oracle provides providers for Simple Mail Transfer Protocol (SMTP), the Internet Message Access Protocol (IMAP), and Post Office Protocol 3 (POP3).  JavaMail is dependent on the JavaBeans Activation Framework.  javax.mail package provides the required interfaces and classes. Email Sender

Email Recipient

SMTP Server

POP3 Server

Messages

Mail Server

What you need to use JavaMail? The following are required to use JavaMail to either send a mail or receive a mail.  Mail server with SMTP and POP3/IMAP servers  Java Mail API, which includes SMTP, POP3, IMAP providers – javax.mail.jar. Download it from https://java.net/projects/javamail/pages/Home  A mail agent to access Mail server - Outlook Express Srikanth Technologies

Java EE (Web Applications – I)

99

Java Program

Java Mail API

SMTP Provider

SMTP Server

Steps to send mail using Java Mail API :  Set the mail.host property to point to the local mail server.  Start a mail session with the Session.getInstance( ) method.  Create a new Message object, probably by instantiating one of its concrete subclasses.  Set the message's from and to addresses, message's subject and the content of the message.  Send the message with the Transport.send() method.

Java Mail API The following are important classes in Java Mail API. These classes are abstract classes and implemented by a specific provider. These classes are provided through javax.mail and javax.mail.internet packages. Class Message

Description Provides the basic encapsulation of message objects. It provides attributes to specify sender, recipient, message etc. Store Supports storing and retrieving the messages. Transport Is used to exchange messages with message transfer agents. It provides abstract interface to message transfer protocol such as SMTP. Session Used to implement Mail Session. Folder Used to represent a folder for storing mails. Srikanth Technologies

Java EE (Web Applications – I)

100

Session Class  It acts as a factory for the installed Transport and Store implementation.  The Session class represents a mail session. It collects together properties and defaults used by the mail API's.  A single default session can be shared by multiple applications on the desktop. Method static Session getDefaultInstance (Properties props, Authenticator authenticator) static Session getInstance(Properties props, Authenticator authenticator) Properties getProperties() String getProperty(String name) Provider getProvider (String protocol) Provider[] getProviders() Store getStore() Store getStore(String protocol) Transport getTransport(String protocol) void setDebug(boolean debug)

Meaning Get the default Session object. Get a new Session object. Returns the Properties object associated with this Session. Returns the value of the specified property. Returns the default Provider for the protocol specified. Returns an array of all the implementations installed via the JavaMail. Get a Store object that implements this user's desired Store protocol. Get a Store object that implements the specified protocol. Get a Transport object that implements the specified protocol. Set the debug setting for this Session.

Srikanth Technologies

Java EE (Web Applications – I)

101

Session Properties The following are Java Mail related properties. Property mail.transport.protocol mail.store.protocol mail.host mail.user mail.protocol.host

Description The default Transport protocol. The default Store protocol. The default host for both Store and Transport protocols. The default user name for both Store and Transport. The host specific to a particular protocol.

Authenticator Class The class Authenticator represents an object that knows how to obtain authentication for a network connection. PasswordAuthentication getPasswordAuthentication() Called when password authentication is needed. Subclasses should override the default implementation, which returns null.

PasswordAuthentication class This class is a data holder that is used by Authenticator. It is simply a repository for a user name and a password.  String getPassword()  String getUserName()

Store Class Store class models a message store and its access protocol, for storing and retrieving messages. Subclasses provide actual implementations - IMAPStore and POP3Store. Method Folder getDefaultFolder() Folder getFolder(name)

Description Returns a Folder object for 'root'. Returns the folder object corresponding to the given name.

Srikanth Technologies

Java EE (Web Applications – I)

102

Folder Class Folder class represents a folder for mail messages. Subclasses such as IMAPFolder and POP3Folder implement protocol specific Folders. Method Message[] getMessages() int getMode() int getUnreadMessageCount() boolean isOpen() void open(int mode)

Description Gets all message objects. Returns open mode of the folder. Returns total number of unread messages. Indicates whether folder is open. Mode can be READ_ONLY or READ_WRITE.

Message Class  This class models an email message. This is an abstract class. Subclasses provide actual implementations.  Message implements the Part interface. Message contains a set of attributes and "content". Messages within a folder also have a set of flags that describe its state within the folder.  Message objects are obtained either from a Folder or by constructing a new Message object of the appropriate subclass. Messages that have been received are retrieved from a folder named "INBOX".  To send a message, an appropriate subclass of Message (e.g., MimeMessage) is instantiated, the attributes and content are filled in, and the message is sent using the Transport.send method.  A message may be set to any of the valid states such as ANSWERED, DELETED, SEEN and DRAFT. Method void addFrom(Address[] addlist) void addRecipient ( Message.RecipientType type, Address address)

Meaning Adds these addresses to the existing "From" attribute. Adds this recipient address to the existing ones of the given type.

Srikanth Technologies

Java EE (Web Applications – I)

103

void addRecipients (RecipientType type, Address[] addresses) Address[] getAllRecipients()

Adds these recipient addresses to the existing ones of the given type.

Flags getFlags() Folder getFolder() Address[] getFrom() Date getReceivedDate() Address[] getReplyTo() Date getSentDate() String getSubject() void setFlags (Flags flag,boolean set) void setRecipients (RecipientType type, Address[] addresses) void setReplyTo(Address[] addlist) void setSentDate(Date date) void setSubject(String subject)

Gets all recipient addresses of message. Returns a Flags object containing the flags for this message. Gets the folder from which this message was obtained. Returns the "From" addresses. Gets the date this message was received. Gets the addresses to which replies should be directed. Gets the date this message was sent. Gets the subject of this message. Sets the specified flags on this message to the specified value. Sets the recipient addresses. Sets the addresses to which replies should be directed. Sets the sent date of this message. Sets the subject of this message.

Sendmail.html 01: 02: 03: Send Mail 04: 05: 06: Send Mail 07: 08: To Address 09: 10: Srikanth Technologies

Java EE (Web Applications – I) 11: From Address 12: 13: 14: Subject 15: 16: 17: Body 18: 19: 20: 21: 22: 23: 24:

SendMailServlet.java 01: package servlets; 02: import java.io.IOException; 03: import java.io.PrintWriter; 04: import java.util.Properties; 05: import javax.activation.DataHandler; 06: import javax.mail.*; 07: import java.util.Date; 08: import javax.servlet.ServletException; 09: import javax.servlet.annotation.WebServlet; 10: import javax.servlet.http.*; 11: 12: @WebServlet(name = "SendMailServlet", 13: urlPatterns = {"/sendmail"}) 14: public class SendMailServlet extends HttpServlet { 15: protected void doPost(HttpServletRequest request, 16: HttpServletResponse response) 17: throws ServletException, IOException { 18: response.setContentType("text/html"); 19: PrintWriter out = response.getWriter(); 20: 21: String to = request.getParameter("toaddress"); 22: String from = request.getParameter("fromaddress"); 23: String subject = request.getParameter("subject"); 24: String body = request.getParameter("body"); 25: Properties props = System.getProperties(); 26: Session session = Session.getDefaultInstance(props, null); Srikanth Technologies

104

Java EE 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: } 44: }

(Web Applications – I) try { // construct the message Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); msg.setDataHandler( new DataHandler(body, "text/html")); msg.setSentDate(new Date()); msg.setSubject(subject); Transport.send(msg); // send message out.println("\nMail was sent successfully."); } catch(Exception ex){ out.println("Error --> " + ex.getMessage()); }

105

SendMailAttachmentServlet.java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23:

package servlets; import import import import import import import import import import

java.io.IOException; java.io.PrintWriter; java.util.Properties; javax.activation.DataHandler; javax.activation.FileDataSource; javax.mail.*; javax.mail.*; javax.servlet.ServletException; javax.servlet.annotation.WebServlet; javax.servlet.http.*;

@WebServlet(name = "SendMailServlet", urlPatterns = {"/sendfile"}) public class SendMailAttachmentServlet extends HttpServlet{ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String to = "[email protected]"; Srikanth Technologies

Java EE 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: }

(Web Applications – I) String from = "[email protected]"; String subject = "Ship"; String body = "Here is a ship...."; String filename = "ship.jpg";

106

Properties props = System.getProperties(); Session session=Session.getDefaultInstance(props,null); try { MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); msg.setSubject(subject); // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(body); // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); FileDataSource fds = new FileDataSource( getServletContext().getRealPath(filename)); // attach the file to the message mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(fds.getName()); // create the Multipart and its parts to it Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); msg.setContent(mp); Transport.send(msg); out.println( "Mail has been sent with attachment."); } catch (Exception ex) { ex.printStackTrace(out); } }

Srikanth Technologies

Java EE (Web Applications – I)

107

Sendfromgmail.html 01: 02: 03: Send Mail 04: 05: 06: Send Mail From Gmail 07: 08: To Address 09: 10: Username 11: 12: Password 13: 14: Subject 15: 16: Body 17: 18: 19: 20: 21: 22:

SendMailFromGmailServlet.java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18:

package servlets; import java.io.IOException; import java.io.PrintWriter; import java.security.Security; import java.util.Properties; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; @WebServlet(name = "SendFromGmailServlet", urlPatterns = {"/sendfromgmail"}) public class SendMailFromGmailServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) Srikanth Technologies

Java EE (Web Applications – I) 108 19: throws ServletException, IOException { 20: 21: String SMTP_HOST_NAME = "smtp.gmail.com"; 22: String SMTP_PORT = "465"; // or use 567 23: String toAddress = request.getParameter("toaddress"); 24: final String username=request.getParameter("username"); 25: final String fromAddress=username + "@gmail.com"; 26: final String password = request.getParameter("password"); 27: String subject = request.getParameter("subject"); 28: String body = request.getParameter("body"); 29: String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; 30: response.setContentType("text/html"); 31: PrintWriter out = response.getWriter(); 32: try { 33: Security.addProvider( 34: new com.sun.net.ssl.internal.ssl.Provider()); 35: Properties props = new Properties(); 36: props.put("mail.smtp.host", SMTP_HOST_NAME); 37: props.put("mail.smtp.auth", "true"); 38: props.put("mail.smtp.port", SMTP_PORT); 39: props.put("mail.smtp.socketFactory.port", SMTP_PORT); 40: props.put("mail.smtp.socketFactory.class", SSL_FACTORY); 41: props.put("mail.smtp.socketFactory.fallback", "false"); 42: Session session = Session.getInstance(props, 43: new javax.mail.Authenticator() { 44: protected PasswordAuthentication 45: getPasswordAuthentication(){ 46: return new PasswordAuthentication(username, password); 47: } 48: }); 49: Message msg = new MimeMessage(session); 50: msg.setFrom(new InternetAddress(fromAddress)); 51: msg.setRecipient(Message.RecipientType.TO, 52: new InternetAddress(toAddress)); 53: msg.setSubject(subject); 54: msg.setText(body); 55: Transport.send(msg); 56: out.println("Mail has been sent Successfully!"); 57: } catch (Exception ex) { 58: ex.printStackTrace(out); 59: } 60: } 61: } Srikanth Technologies

Web Applications - II

Java EE (Web Applications – II)

JSON (JavaScript Object Notation)  JavaScript Object Notation is a lightweight data-interchange format (Compared to XML)  Easy for humans to read and write  Easy for machines to parse and generate  JSON is a text format and it is programming language independent  JSON objects are typed while XML data is typeless - JSON types are string, number, array, boolean whereas in XML data are all string  Native data form for JavaScript code. Data is readily accessible as JSON objects in your JavaScript code.  XML data is to be parsed and assigned to variables through tedious DOM APIs  Retrieving values is as easy as reading from an object property in your JavaScript code

JSON Structures  A collection of name/value pairs  An ordered list of values  These are universal data structures supported by most modern programming languages  A JSON object is an unordered set of name/value pairs - A JSON object begins with "{" and ends with "}". Each name is followed by : (colon) and the name/value pairs are separated by “,” (comma) {"title":"Professional AJAX","price":399}

The eval() function To convert a JSON text into a JSON object, use the eval() function. The eval() invokes the JavaScript compiler and creates an object from JSON string. var myObject = eval('(' + myJSONtext + ')');

Srikanth Technologies

1

Java EE (Web Applications – II)

2

JSON Processing API Starting from Java EE 7.0, support for JSON Processing is provided by Java. It is called as JSON Processing in Java EE (JSR-353). This API allows Java programmer to do the following:    

Create JSON object using Object Model Generate JSON object using Streaming API Navigate JSON data using Object Model Parse JSON data using Streaming API

The following are the classes and interfaces related to JSON API in Java EE. Class or Interface Description Json Contains static methods to create instances of JSON parsers, builders, and generators. This class also contains methods to create parser, builder, and generator factory objects. JsonReader Reads JSON data from a stream and creates an object model in memory. JsonObjectBuilder, Create an object model or an array model in JsonArrayBuilder memory by adding elements from application code. JsonWriter Writes an object model from memory to a stream. JsonValue, Represent data types for elements in JSON JsonStructure, data. JsonObject, JsonArray, JsonString, JsonNumber JsonParser Represents an event-based parser that can read JSON data from a stream or from an object model. JsonGenerator Writes JSON data to a stream one element at a time. Srikanth Technologies

Java EE (Web Applications – II)

3

Note: Download implementation of JSON Processing API from jsonp.java.net

Using JSON Processing API The following programs demonstrate how to use JSON API provided by Java EE 7.0. 01: import javax.json.Json; 02: import javax.json.JsonObject; 03: import javax.json.JsonObjectBuilder; 04: 05: public class CreateJsonObject { 06: public static void main(String[] args) { 07: JsonObjectBuilder builder = Json.createObjectBuilder(); 08: builder.add("name", "Srikanth"); 09: builder.add("occupation", "Director"); 10: builder.add("company", "Srikanth Technologies"); 11: 12: JsonObject person = builder.build(); 13: System.out.println(person); 14: } 15: }

When you run the above program, the following output is generated: {"name":"Srikanth","occupation":"Director", "company":"Srikanth Technologies"}

In case you want to write JSON object to a file, use the following code after you construct JsonObject: 01: // write JSON object to a file c:\java\person.txt 02: 03: FileWriter fw = new FileWriter("c:\\java\\person.txt"); 04: JsonWriter fjw = Json.createWriter(fw); 05: fjw.writeObject(person); 06: fjw.close(); 07: fw.close();

Srikanth Technologies

Java EE (Web Applications – II)

4

Creating JSON Array with Object Model You can write an object that contains an array as shown in the following example. It creates an array with the name contacts and adds two objects to it. 01: import javax.json.Json; 02: import javax.json.JsonArrayBuilder; 03: import javax.json.JsonObjectBuilder; 04: 05: public class CreateJsonArray { 06: public static void main(String[] args) { 07: JsonObjectBuilder person = Json.createObjectBuilder(); 08: person.add("name", "Srikanth"); 09: person.add("occupation", 10: "Director, Srikanth Technologies"); 11: 12: JsonArrayBuilder emails = Json.createArrayBuilder(); 13: emails.add("[email protected]"); 14: emails.add("[email protected]"); 15: 16: person.add("emails", emails); 17: System.out.println(person.build()); 18: } 19: }

The output JSON is as follows: {"name":"Srikanth", "occupation":"Director,Srikanth Technologies", "emails":["[email protected]","[email protected] "]}

Creating JSON Object using Generator The following program creates a JSON object using Generator. 01: import java.io.StringWriter; 02: import javax.json.Json; 03: import javax.json.stream.JsonGenerator; 04:

Srikanth Technologies

Java EE (Web Applications – II) 5 05: public class UsingGenerator { 06: public static void main(String[] args) { 07: StringWriter sw = new StringWriter(); 08: JsonGenerator gen = Json.createGenerator(sw); 09: 10: gen.writeStartObject() 11: .write("name", "Srikanth Pragada") 12: .write("email", "[email protected]") 13: .write("mobile","9059057000") 14: .writeEnd(); 15: 16: gen.close(); 17: System.out.println(sw.toString()); 18: } 19: }

Creating JSON Array using Generator The following program creates a JSON Array using Generator and writes JSON content into a file. 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20:

import java.io.StringWriter; import javax.json.Json; import javax.json.stream.JsonGenerator; public class CreateJsonArrayWithGenerator { public static void main(String[] args) { StringWriter writer = new StringWriter(); JsonGenerator gen = Json.createGenerator(writer); gen.writeStartObject() .write("name", "Srikanth") .write("occupation", "Director, Srikanth Technologies") .writeStartArray("emails") .write("[email protected]") .write("[email protected]") .writeEnd() // for array .writeEnd(); // for root object gen.close(); System.out.println(writer); } }

Srikanth Technologies

Java EE (Web Applications – II) 6 {"name":"Srikanth", "occupation":"Director, Srikanth Technologies", "emails":["[email protected]","[email protected] m"]}

Read JSON Object using Object Model JSON API allows reading JSON objects either using JsonReader or with JsonParser. This example shows how to use JsonReader. 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15:

import import import import

java.io.StringReader; javax.json.Json; javax.json.JsonObject; javax.json.JsonReader;

public class ReadJsonObject { public static void main(String[] args) throws Exception { JsonReader reader = Json.createReader (new StringReader("{ \"qty\" : 20, \"price\" : 1000}")); JsonObject sale = reader.readObject(); System.out.println("Qty : " + sale.getInt("qty")); System.out.println("Price : " + sale.getInt("price")); } }

The output of the above program is as follows: Qty : 20 Price : 1000

Reading JSON Object using Streaming API The following program shows how to use JsonParser to parse JSON data and get one component at a time. It is left to us to determine the type of the event and handle it accordingly.

Srikanth Technologies

Java EE (Web Applications – II) 7 01: import java.io.StringReader; 02: import javax.json.Json; 03: import javax.json.stream.JsonParser; 04: 05: public class ReadJsonObjectWithStreaming { 06: public static void main(String[] args) throws Exception { 07: JsonParser parser = Json.createParser 08: (new StringReader("{ \"qty\" : 20, \"price\" : 1000}")); 09: while (parser.hasNext()) { 10: JsonParser.Event event = parser.next(); 11: switch (event) { 12: case KEY_NAME: 13: System.out.print(parser.getString() + " :"); 14: break; 15: case VALUE_NUMBER: 16: System.out.println(parser.getInt()); 17: break; 18: } 19: } // while 20: } 21: }

Srikanth Technologies

Java EE (Web Applications – II)

8

AJAX  AJAX stands for Asynchronous JavaScript And XML  AJAX is a type of programming made popular in 2005 by Google (with Google Suggest)  AJAX is not a new programming language, but a new way to use existing standards  With AJAX you can create better, faster, and more user-friendly web applications  AJAX is a technology that uses JavaScript, XML, DOM (Document Object Model), and DHTML  XMLHttpRequest object is the heart of AJAX

What are the problems with web applications?    

Too many round trips by client Users have to wait for page refreshes Loss of context Client/Server (windows) applications provide superior user experience

Advantages with AJAX       

Asynchronous Minimal data transfer Responsiveness Context is maintained No plug-in/code to be downloaded Several Toolkits and frameworks are available Tremendous industry acceptance

The XMLHttpRequest Object  First introduced by Microsoft in 1997. Used in Outlook Web Access and MSDN applications.  Used in IE 5.0. Implemented as ActiveX object in IE.  Used to make asynchronous request and response.  No post back, no full refresh of the page.  Adopted by all other major browsers.  Implemented as standard object in other browsers. Srikanth Technologies

Java EE (Web Applications – II)

9

 Contains methods and properties to make request synchronously or asynchronously and receive response.

Properties of XMLHttpRequest object The following are the properties of XMLHttpRequest object. Property readyState responseXML responseText Status statusText

Meaning Indicates the state of the asynchronous request Contains XML document sent from server Contains text sent from server Status code of the response Status text sent by server Browser XMLHttpRequest Object

3

Callback Function

1. Asynchronous request

1

2

2. Response from server 3. XMLHttpRequest calls callback.

Web pages and web services Web Server

onreadystatechange event  Specifies the JavaScript function to be called when readyState property changes.  Generally it examines readyState property before processing the response.

Srikanth Technologies

Java EE (Web Applications – II)

10

readyState property It contains a value that indicates the state of asynchronous request. Value 0 1 2 3 4

Description Object created but not initialized open() method is called but not sent send() is called but yet to receive response Receiving response. Body is not yet received Response has been completely received

Methods The following are the methods of XMLHttpRequest object. Method open(method, url,async,uname, pwd) send(value)

Meaning Prepares an asynchronous request

setRequestHeader (name, value) getResponseHeader (name) getAllResponseHeaders() abort()

Sends the request with the given value. The values are passed to server in http post request. Sets request header to the given value Returns value of the specified response header Returns all response headers as a string Aborts the current request

add.jsp 01: 02:

Srikanth Technologies

Java EE (Web Applications – II)

11

add.html 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 41: 42:

var xhr; function create(){ xhr = new XMLHttpRequest(); } function updateTotal(){ var num1 = document.getElementById("num1"); var num2 = document.getElementById("num2"); var url="add.jsp?num1=" +num1.value+"&num2=" + num2.value; xhr.open("GET",url,true); xhr.onreadystatechange=doUpdate; xhr.send(null); // make GET request } function doUpdate() { if (xhr.readyState == 4) if (xhr.status == 200){ var result = document.getElementById("result"); result.value= xhr.responseText; } else alert("Error : " + xhr.statusText); } Using AJAX to Add Numbers First Number: Second Number: Result:

Srikanth Technologies

Java EE (Web Applications – II)

12

AJAX and XML Server-side script may send XML content to client, which is processed using XML DOM and JavaScript in client. The following example shows how to send XML from server and process it in client using XML DOM and JavaScript. empdetails.html 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35:

AJAX and XML var xmlHttp; var empname, empsal, message; function create() { xmlHttp = new XMLHttpRequest(); empname = document.getElementById("empname"); empsal = document.getElementById("empsal"); message = document.getElementById("message"); } // end of create function getEmployeeDetails() { var empid = document.getElementById("empid").value; var url = "empdetails_json.jsp?empid=" + empid; xmlHttp.open("GET", url, true); xmlHttp.onreadystatechange = doUpdate; xmlHttp.send(null); // make request } function doUpdate() { if (xmlHttp.readyState === 4 && xmlHttp.status === 200){ var data = xmlHttp.responseText; var details=eval("(" + data + ")");// JSON to Object if (details.error) { // employee id not found empname.value = ""; empsal.value = ""; message.innerHTML = details.error; } else { // employee found empname.value = details.name; empsal.value = details.salary; } } } Srikanth Technologies

Java EE (Web Applications – II) 36: 37: 38: Employee Details 39: 40: Employee ID : 41: 42: 44: 45: 46: Employe Name : 47: 49: 50: Salary : 51: 53: 54: 55: 56:

13

empdetails.jsp 01: 02: Srikanth Technologies

Java EE (Web Applications – II)

14

empdetails_json.html 01: AJAX and XML 02: 03: var xmlHttp; 04: var empname, empsal, message; 05: function create() { 06: xmlHttp = new XMLHttpRequest(); 07: empname = document.getElementById("empname"); 08: empsal = document.getElementById("empsal"); 09: message = document.getElementById("message"); 10: } // end of create 11: function getEmployeeDetails() { 12: var empid = document.getElementById("empid").value; 13: var url = "empdetails_json.jsp?empid=" + empid; 14: xmlHttp.open("GET", url, true); 15: xmlHttp.onreadystatechange = doUpdate; 16: xmlHttp.send(null); // make request 17: } 18: function doUpdate() { 19: if (xmlHttp.readyState === 4 && 20: xmlHttp.status === 200){ 21: var data = xmlHttp.responseText; 22: var details=eval("(" + data + ")");// JSON to Object 23: if (details.error) { // employee id not found 24: empname.value = ""; 25: empsal.value = ""; 26: message.innerHTML = details.error; 27: } 28: else { // employee found 29: empname.value = details.name; 30: empsal.value = details.salary; 31: } 32: } 33: } 34: 35: 36: 37: 39: Employee Details 40: Employee ID : 41: 42: 44: Srikanth Technologies

Java EE (Web Applications – II) 45: 46: 47: Employe Name : 48: 50: 51: 52: 53: Salary : 54: 56: 57: 58: 60: 61:

15

empdetails_json.jsp 01: 03:

Srikanth Technologies

Java EE (Web Applications – II)

16

jQuery  JQuery is a JavaScript library developed by John Resig and his company.  Its tagline is - write less, do more.  It greatly simplifies things that you handle with JavaScript.  AJAX needs code to be written in JavaScript. So, instead of using XMLHttpRequest object and other JavaScript construct to implement AJAX, we can use JQuery to achieve the same, of course with far less code to handle.  Many regard JQuery as the best JavaScript libraries of all.  Download JQuery from www.jquery.com. You can download either of the versions – compressed or development.  Place jquery-1.10.2.js in your web application’s root directory. Refer to JQuery from tag in your pages.  It is a good practice to rename jquery-version.js to jquery.js so that tag need not change when version changes.

Syntax The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s). $(selector).action()

 A $ sign to define/access jQuery  A (selector) to "query (or find)" HTML elements  A jQuery action() to be performed on the element(s)

The .ready() function This function is used to execute code when the DOM is fully loaded. 01: $(document).ready(function(){ 02: 03: // jQuery methods go here... 04: 05: });

Srikanth Technologies

Java EE (Web Applications – II)

17

Selectors  jQuery selectors allow you to select and manipulate HTML element(s).  jQuery selectors are used to "find" (or select) HTML elements based on their id, classes, types, attributes, values of attributes and much more.  All selectors in jQuery start with the dollar sign and parentheses: $(). Selector Example Element $("p") $("[href]") $("p:first") $("tr:even") Id $("#output") Class $(".red") $("p.intro")

Meaning Selects all elements Selects all elements with an href attribute Selects the first element Selects all even elements Selects element with id output Selects items with css class red Selects all elements with class="intro"

jQuery and AJAX The following examples show how to use jQuery to make AJAX request. Method load()

get()

post()

Meaning The load() method loads data from a server and puts the returned data into the selected element. $(selector).load(URL,data,callback); The $.get() method requests data from the server with an HTTP GET request. jQuery.get( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] ) The $.post() method requests data from the server using an HTTP POST request. jQuery.post( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] ) Srikanth Technologies

Java EE (Web Applications – II)

getJSON()

18

Load JSON-encoded data from the server using a GET HTTP request. jQuery.getJSON( url [, data ] [, success(data, textStatus, jqXHR)])

Create an HTML page (add.html) that takes two numbers from user and calls add.jsp with .get() method of JQuery library. add.html 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 31: 32:

function addNumbers(){ $.get("add.jsp",{num1 : $("#num1").val(), num2 : $("#num2").val()},doUpdate); } function doUpdate(response) { if (response) { $("#result").val(response); } } Using AJAX to Add Numbers with Jquery First Number : Second Number : Result:

Srikanth Technologies

Java EE (Web Applications – II) The following are important steps in the above program :

19

 Include jquery.js using tag  Use $.get method to make an AJAX call to add.jsp. No need to use XMLHttpRequest directly. JQuery library takes care of it.  The expression $("#num1").val() takes the value from the field that is with id num1. The last parameter to get() method is the call-back method.  Call-back method (doUpdate) has a single parameter that contains the response from the server, which is sum in this case.  Check whether response is available and then place it into text field with id result.

Using XML with JQuery  The following is the code for EMPDETAILS.HTML. Apart from taking XML from server and parsing it, it also demonstrates how to show progress icon to user while request is in progress. I have used clock.gif for this.  Make sure clock.gif is placed in webpages folder.  Function css is used to add CSS attributes to an element.  JSP empdetails.jsp is same as what we used in AJAX example. 01: 02: 03: AJAX and XML with JQUERY 04: 05: 06: function getEmployeeDetails() { 07: // make clock image visible 08: $("#clock").css("visibility", "visible") 09: $.get("../empdetails.jsp", 10: {empid: $("#empid").val()}, 11: displayResult); 12: } 13: function displayResult(data) { 14: // hide clock image 15: $("#clock").css("visibility", "hidden") 16: 17: if($(data).find("error").text()!= "") // error 18: { Srikanth Technologies

Java EE (Web Applications – II) 20 19: // clear fields 20: $("#empname").val("") 21: $("#empsal").val("") 22: alert("Error : "+ $(data).find("error").text()); 23: } 24: else // found employee and got details 25: { 26: $("#empname").val($(data).find("name").text()); 27: $("#empsal").val($("salary", data).text()) 28: } 29: } 30: 31: 32: 33: Employee Details 34: Employee ID : 35: 36: 38: 39: Employe Name : 40: 42: Salary : 43: 45: 46: 47: 49: 50:

Run EMPDETAILS.HTML page, enter employee id and click on button. After a little while, you must see either details of employee in text fields or error message as alert.

Srikanth Technologies

Java EE (Web Applications – II)

21

Using JSON with JQuery Let us now see how JQuery is used to process JSON string that comes from server to client. The following example takes employee id and displays details of employee by getting those details from empdetails_json.jsp, which was used in AJAX example. Let us create HTML page (empdetails_json.html) that uses JQuery to make AJAX call to EMPDETAILS_JSON.JSP. We will use getJSON() method to send request to server. The main advantage with this method is, it parses the response string as JSON. The code is given below. empdetails_json.html 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 26: 27: 28: 29: 30:

AJAX and JSON with JQUERY function getEmployeeDetails(){ $.getJSON( "empdetails_json.jsp",{empid : $("#empid").val()}, displayResult); } function displayResult(data) { if ( data.error) { // emp not found $("#empname").val("") // clear fields $("#empsal").val("") alert( data.error); } else { // Found employee. Display details $("#empname").val( data.name); $("#empsal").val( data.salary); } } Employee Details Employee ID : Srikanth Technologies

Java EE (Web Applications – II) 31: 33: Employee Name : 34: 36: 37: Salary : 38: 40: 41: 42: 43: 44:

22

Run EMPDETAILS_JSON.HTML page, enter employee id and click on button. After a little while, you must see either details of employee in text fields or error message as alert.

Getting details of Employees based on selected Job The following example displays list of jobs in a listbox and allows user to select a job by double clicking on job to get the names of the employees who belong to the selected job. jobs.html 01: 02: 03: Jobs and Employees 04: 05: 06: // this is done when page is loaded 07: $(function() { 08: $.getJSON("jobs.jsp",{},displayJobs); 09: } 10: ); 11: 12: function displayJobs(data) { 13: $.each(data, function(index,job){ 14: // add items to List box 15: $("#jobs").append("" 16: + job.title + ""); Srikanth Technologies

Java EE (Web Applications – II) 23 17: } 18: ); 19: } 20: 21: function getEmployees() { 22: $("#employees").contents().remove(); // clear options 23: $.getJSON("employees.jsp",{jobid:$("#jobs").val()}, 24: displayEmployees); 25: } 26: 27: function displayEmployees(data) { 28: $.each(data, function(index,name){ 29: // add names to List box 30: $("#employees").append("" + 31: name + ""); 32: } // end of function 33: ); // each 34: } 35: 36: 37: 38: 39: Jobs and Employees 40: 41: 42: Jobs 43: 45: Double click on Job to get Employees of that Job. 46: 47: 48: Employees 49: 51: 52: 53: 54:

Srikanth Technologies

Java EE (Web Applications – II)

24

jobs.jsp 01: 03: 04:

employees.jsp 01: 03:

(Web Applications – II) emps.add(rs.getString("fullname")); } rs.close(); out.println( emps.build().toString());

Srikanth Technologies

25

Java EE (Web Applications – II)

26

BEAN VALIDATION  Bean validation (JSR 303) is a new feature that is available in Java EE 6.  The bean validation model is supported by constraints in the form of annotations placed on a field, method, or class of a JavaBean.  Several built-in annotations are available in the javax.validation.constraints package. Some of the commonly used built-in annotations are listed below: @Min

The annotated element must be a number whose value must be higher or equal to the specified minimum. @Max The annotated element must be a number whose value must be lower or equal to the specified maximum. @Size The annotated element must be between specified minimum and maximum boundaries. @NotNull The annotated element must not be null. @Null The annotated element must be null. @Pattern The annotated element must match the specified Java regular expression. To use Bean Validation, we have to use Hibernate Validator, which is one of the implementations of Bean Validation Specifications. Download Hibernate Validator from http://hibernate.org/validator and place .jar files related to Hibernate Validator and their dependencies in classpath of our project. User.java 01: 02: 03: 04: 05: 06: 07:

import import import import import

javax.validation.constraints.Max; javax.validation.constraints.Min; javax.validation.constraints.NotNull; javax.validation.constraints.Pattern; javax.validation.constraints.Size;

public class User { Srikanth Technologies

Java EE (Web Applications – II) 27 08: @NotNull(message="Username Required") 09: @Size(min=6, max=10, 10: message="Username must be between 6 to 10 chars") 11: private String uname; 12: 13: @NotNull(message="Password Required") 14: private String password; 15: 16: @Min( value=18 , message="Age must be >= 18") 17: @Max( value=100, message="Age must be 15}"> 08: Big Name 09: 10: 11: 12:

Person.java 01: package beans; 02: public class Person { 03: private String name; 04: private int age; 05: public Person(String name, int age) { 06: this.name = name; 07: this.age = age; 08: } 09: public int getAge() { 10: return age; 11: } 12: public void setAge(int age) { 13: this.age = age; 14: } 15: public String getName() { 16: return name; Srikanth Technologies

Java EE 17: 18: 19: 20: 21: }

(Web Applications – II) } public void setName(String name) { this.name = name; }

91

PersonsBean.java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15:

package beans; import java.util.ArrayList; import java.util.List; import javax.faces.bean.ManagedBean; @ManagedBean public class PersonsBean { public List getPersons() { ArrayList persons = new ArrayList(); persons.add( new Person("Mr.John Resig",32)); persons.add( new Person("Mr.Joe Stagner",42)); persons.add( new Person("Mr.Scott Mitchell",38)); persons.add( new Person("Mr.Rod Johnson",41)); return persons; } }

AJAX Support using  JSF 2.0 supports integrated Ajax using tag.  The presence of the tag triggers the Ajax request.  This allows Ajax requests to be issued without requiring the page author to write any JavaScript code.  This tag serves two roles depending on its placement. If this tag is nested within a single component, it will associate an Ajax action with that component. If this tag is placed around a group of components it will associate an Ajax action with all components that support the event attribute. Attribute Description event A String identifying the type of event the Ajax action will apply to. If specified, it must be one of the events supported by the component the Ajax behavior is being applied to. If not specified, the default event is determined for the component. The default event is Srikanth Technologies

Java EE (Web Applications – II)

execute

92

“action” for ActionSource components and “valueChange” for EditableValueHolder components. If a literal is specified, it must be a space delimited String of component identifiers and/or one of the keywords given below. @all - All component identifiers @none - No identifiers @this - The element that triggered the request @form - The enclosing form

render

onevent onerror listener

If not specified, then @this is the default. If a ValueExpression is specified, it must refer to a property that returns a Collection of Strings. A Collection that identifies a list of components to be rendered on the client. It has the same options as execute attribute. If not specified, then @none is the default. If a ValueExpression is specified, it must refer to a property that returns a Collection of Strings. The name of a JavaScript function that will handle events. The name of a JavaScript function that will handle errors. The name of the listener method that is called when an AjaxBehaviorEvent has been broadcast for the listener.

01: 02: 03:

Using the listener Attribute  The listener attribute refers to a method expression that is executed on the server side in response to an Ajax action on the client. Srikanth Technologies

Java EE (Web Applications – II)

93

 The listener's processAjaxBehavior method is called once during the Invoke Application phase of the lifecycle.

The following code represents the someaction method in mybean. 01: public void someaction(AjaxBehaviorEvent event) { 02: dosomething; 03: }

phonedirectory.xhtml 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22:

Search Phone Directory Enter person name :

Srikanth Technologies

Java EE (Web Applications – II)

94

DirectoryBean.java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42:

import import import import

java.util.TreeMap; javax.faces.bean.ManagedBean; javax.faces.bean.RequestScoped; javax.faces.event.ActionEvent;

@ManagedBean(name="directoryBean") @RequestScoped public class DirectoryBean { private TreeMapdirectory = new TreeMap(); private String name,phone, email; public DirectoryBean() { directory.put("Resig","9000099999:[email protected]"); directory.put("John", "9000011111:[email protected]"); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone;} public void setPhone(String phone) { this.phone = phone; } public void search(ActionEvent evt) { String details = directory.get(name); if ( details == null) { phone = "Sorry! Name not found"; email = ""; } else { String parts[] = details.split(":"); phone = parts[0]; email = parts[1]; } } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } Srikanth Technologies

Java EE (Web Applications – II)

95

Templates  JSF provides the tools to implement user interfaces that are easy to extend and reuse. Templating is a useful Facelets feature that allows you to create a page that will act as the base, or template, for the other pages in an application.  By using templates, you can reuse code and avoid recreating similarly constructed pages. Templating also helps in maintaining a standard look and feel in an application with a large number of pages.  A template page is used as a template for other pages, usually referred to as client pages.  Templates in JSF are similar to Tiles in Struts. Tag ui:component ui:composition ui:define ui:fragment ui:include ui:insert ui:param ui:repeat ui:remove

Function Defines a component that is created and added to the component tree. Defines a page composition that optionally uses a template. Content outside this tag is ignored. Defines content that is inserted into a page by a template. Similar to the component tag but does not disregard content outside this tag. Encapsulates and reuses content for multiple pages. Inserts content into a template. Used to pass parameters to an included file. Used as an alternative for loop tags, such as c:forEach or h:dataTable. Removes content from a page.

template.xhtml 01: 02: 03: 04: 05: 06: 07: 08:

Srikanth Technologies

Java EE (Web Applications – II) 96 09: Title 10: 11: 12: 13: 14: 15: First Page 16:    17: Second Page 18: 19: 20: 21: 22: 23: Content Page 24: 25: 26:

WEB-CONTENT/resources/css/default.css 01: 02: 03: 04: 05: 06:

.main { background-color:red;} .links{ background-color:white;} .head {background-color:yellow;font-size:20pt; font-weight:700;} .title{font-size:16pt;font-weight:700;} body {background-color: silver;}

Header.html Templates Demo

first.xhtml 01: 04: First Page 05: 06: First Page Content! 07: 08:

Srikanth Technologies

Java EE (Web Applications – II)

97

second.xhtml 01: 04: Second Page 05: Second Page Content! 06:

Uploading File with inputFile element  The is used to upload a file from client to server.  The upload is stored in a bean property of type javax.servlet.http.Part referenced in the value attribute.  The form submit encoding must be set to multipart/formdata in the enctype attribute of the enclosing h:form. countwords.xhtml 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26:

Word Count Word Count Select File : No. of words in the document are : Srikanth Technologies

Java EE (Web Applications – II) 27:

98

FileBean.java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40:

package beans; import java.io.*; import javax.faces.bean.* import javax.faces.event.ActionEvent; import javax.servlet.http.Part; @ManagedBean @RequestScoped public class FileBean { private Part file; private int count; public Part getFile() { return file; } public void setFile(Part file) { this.file = file; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public void upload(ActionEvent evt) { // read the contents of the file and count number of words try { BufferedReader br = new BufferedReader( new InputStreamReader(file.getInputStream())); String line = br.readLine(); count = 0; while (line != null) { String words[] = line.split("[^A-Za-z0-9-]+"); count += words.length; line = br.readLine(); } br.close(); } catch (Exception ex) { System.out.println("Error -->" + ex.getMessage()); } } Srikanth Technologies

Java EE (Web Applications – II) 41: }

99

The and components  JSF 2.2 extends GET processing further by allowing you to take action using viewAction component.  A view action operates like a button command (UICommand) component.  By default, it is executed during the Invoke Application phase in response to an initial request.  The viewAction component is declared as a child of the metadata facet (). This allows the view action to be incorporated into the JavaServer Faces lifecycle on both nonfaces (initial) and faces (postback) requests.  Like other UICommand components, the viewAction component supports declarative navigation as well. So you can write a navigation rule that is consulted before the page is rendered. WishBean.java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22:

package beans; import java.util.Calendar; import javax.enterprise.context.RequestScoped; import javax.faces.bean.ManagedBean; @ManagedBean @RequestScoped public class WishBean { private String name, message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String wish() { Srikanth Technologies

Java EE (Web Applications – II) 23: Calendar c = Calendar.getInstance(); 24: int hour = c.get(Calendar.HOUR_OF_DAY); 25: message = name + ", "; 26: if (hour < 12) { 27: message += "Good Morning"; 28: } else if (hour < 17) { 29: message += "Good Afternoon"; 30: } else { 31: message += "Good Evening"; 32: } 33: return null; 34: } 35: }

100

wish.xhtml 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20:

" + e.getMessage()); return null; } } public RowSet getEmployees() { try { CachedRowSet rs = new OracleCachedRowSet(); rs.setUrl("jdbc:oracle:thin:@localhost:1521:XE"); rs.setUsername("hr"); Srikanth Technologies

Java EE (Web Applications – II) 103 44: rs.setPassword("hr"); 45: rs.setCommand 46: ("select * from employees where job_id = ?"); 47: rs.setString(1, job); 48: rs.execute(); 49: return rs; 50: } catch (Exception e) { 51: System.out.println(e); 52: return (null); 53: } 54: } // getEmployees 55: }

Srikanth Technologies

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF