TYIT Sem V Advanced Java Old Syllabus
TYIT Sem V Advanced Java Old Syllabus
(IT)
SEMESTER-V PAPER-IV (CBCS)
UNIT I
1. Swings 1
UNIT II
2. Introduction To Servlets 17
UNIT III
UNIT IV
UNIT V
9. Struts 131
UNIT VI
*****
SYLLABUS
Books:
Java EE 6 for Beginners, Sharanam Shah, Vaishali Shah, SPD (Unit II to
VI) Core Java Vol. II – Advanced Features, Cay S. Horstmans, Gary
Coronell, Eight Edition, Pearson (Unit I and III) Java Complete Reference,
Herbert Schildt, Seventh Edition,TMH. (Unit I)
References:
Java EE Project using EJB 3, JPA and struts 2 for beginners, Shah, SPD
Java Programming A practical Approach, C Xavier, McGraw Hill Java
Server Faces A practical Approach for beginners, B M Harwani, Eastern
Economy Edition (PHI). Advanced Java Technology, Savaliya,
Dreamtech.
Term Work:
Practicals
1. Write a java program to present a set of choices for a user to select
Stationary products and display the price of Product after Selection
from the list.
2. Write a java program to demonstrate typical Editable Table,
describing employee details for a software company.
3. Write a java program using Split pane to demonstrate a screen
divided in two parts, one part contains the names of Planets and
another Displays the image of planet. When user selects the planet
name form Left screen, appropriate image of planet displayed in right
screen.
4. Develop Simple Servlet Question Answer Application to demonstrate
use of HttpServletRequest and HttpServletResponse interfaces.
5. Develop Servlet Application of Basic Calculator (+,-,*, /, %) using
ServletInputStream and ServletOutputStream.
6. Develop a JSP Application to accept Registration Details form user
and Store it into the database table.
7. Develop a JSP Application to Authenticate User Login as per the
registration details. If login success the forward user to Index Page
otherwise show login failure Message.
8. Develop a web application to add items in the inventory using JSF.
9. Develop a Room Reservation System Application Using Enterprise
Java Beans.
10. Develop a Hibernate application to store Feedback of Website Visitor
in MySQL Database.
11. a. Develop a simple Struts Application to Demonstrate 3 page
Website of Teaching Classes which passes values from every page to
another.
*****
UNIT I
1
SWINGS
Unit Structure
1.0 Event Handling
1.1 JFrames
1.2 Lists
1.3 Tables
1.4 Trees
1.5 Text Components
1.6 Progress Indicators
1.7 Component Organizers
References
Unit End Questions
1
1.1 SWINGS
1.2 JFRAME
jfrm.setSize(275, 100);
The setSize( ) method (which is inherited by JFrame from the AWT class
Component) setsthe dimensions of the window, which are specified in
pixels. Its general form is shown here:
In this example, the width of the window is set to 275 and the
height is set to 100.By default, when a top-level window is closed (such as
when the user clicks the closebox), the window is removed from the
screen, but the application is not terminated. Whilethis default behavior is
useful in some situations, it is not what is needed for most
applications.Instead, you will usually want the entire application to
terminate when its top-levelwindow is closed. There are a couple of ways
to achieve this. The easiest way is to callsetDefaultCloseOperation( ), as
the program does:
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
3
After this call executes, closing the window causes the entire application
to terminate. The general form of setDefaultCloseOperation( ) is shown
here:
The value passed in what determines what happens when the window is
closed. There areseveral other options in addition to
JFrame.EXIT_ON_CLOSE. They are shown here:
JFrame.DISPOSE_ON_CLOSE
JFrame.HIDE_ON_CLOSE
JFrame.DO_NOTHING_ON_CLOSE
4
2. Container getContentPane() – This method creates the
JFrame’scontentPane object.
3. Component getGlassPane() – This method creates the glassPane
object for JFrame.
4. int getDefaultCloseOperation() – When the user clicks on the close
button on this Frame then this method returns the operation.
5. JMenuBargetJMenuBar() – Menubar set created at the Frame by
using this method.
6. JLayeredPanegetLayeredPane() – LayeredPane object is returned by
this method.
7. JRootPanegetRootPane() – The rootPane object is returned by this
method.
1.3 LISTS
Method Description
void add(int index, E element) It is used to insert the specified
element at the specified position in a
list.
booleanadd(E e) It is used to append the specified
element at the end of a list.
booleanaddAll(Collection<? It is used to append all of the
extends E> c) elements in the specified collection
to the end of a list.
booleanaddAll(int index, It is used to append all the elements
Collection<? extends E> c) in the specified collection, starting at
the specified position of the list.
void clear() It is used to remove all of the
elements from this list.
booleanequals(Object o) It is used to compare the specified
object with the elements of a list.
int hashcode() It is used to return the hash code
value for a list.
Eget(int index) It is used to fetch the element from
the particular position of the list.
5
booleanisEmpty() It returns true if the list is empty,
otherwise false.
int lastIndexOf(Object o) It is used to return the index in this
list of the last occurrence of the
specified element, or -1 if the list
does not contain this element.
Object[] toArray() It is used to return an array
containing all of the elements in this
list in the correct order.
<T>T[] toArray(T[] a) It is used to return an array
containing all of the elements in this
list in the correct order.
booleancontains(Object o) It returns true if the list contains the
specified element
booleancontainsAll(Collection<?> It returns true if the list contains all
c) the specified element
int indexOf(Object o) It is used to return the index in this
list of the first occurrence of the
specified element, or -1 if the List
does not contain this element.
E remove(int index) It is used to remove the element
present at the specified position in
the list.
booleanremove(Object o) It is used to remove the first
occurrence of the specified element.
booleanremoveAll(Collection<?> c) It is used to remove all the elements
from the list.
void replaceAll(UnaryOperator<E> It is used to replace all the elements
operator) from the list with the specified
element.
void retainAll(Collection<?> c) It is used to retain all the elements in
the list that are present in the
specified collection.
E set(int index, E element) It is used to replace the specified
element in the list, present at the
specified position.
void sort(Comparator<? super E> c) It is used to sort the elements of the
list on the basis of specified
comparator.
Example:
import java.util.*;
public class ListExample1{
public static void main(String args[]){
//Creating a List
List<String> list=new ArrayList<String>();
//Adding elements in the List
list.add("Mango");
list.add("Apple");
list.add("Banana");
6
list.add("Grapes");
//Iterating the List element using for-each loop
for(String fruit:list)
System.out.println(fruit);
}
}
1.4 TABLE
JTable is a component that displays rows and columns of data. You can
drag the cursor on column boundaries to resize columns. You can also drag a
column to a new position. Depending on its configuration, it is also possible to
select a row, column, or cell within the table, and to change the data within a cell.
JTable is a sophisticated component that offers many more options and features
than can be discussed here. (It is perhaps Swing’s most complicated component.)
However, in its default configuration, JTable still offers substantial functionality
that is easy to use—especially if you simply want to use the table to present data
in a tabular format. The brief overview presented here will give you a general
understanding of this powerful component. Like JTree, JTable has many classes
and interfaces associated with it. These are packaged in javax.swing.table. JTable
supplies several constructors. The one used here is JTable(Object data[ ][ ],
Object colHeads[ ]) Here, data is a two-dimensional array of the information to
be presented, and colHeads is a one-dimensional array with the column headings.
JTable relies on three models. The first is the table model, which is defined by
the TableModel interface. This model defines those things related to displaying
data in a two-dimensional format. The second is the table column model, which
is represented by TableColumnModel. JTable is defined in terms of columns, and
it is TableColumnModel that specifies the characteristics of a column. These two
models are packaged in javax.swing.table.A JTable can generate several different
events. The two most fundamental to a table’s operation are ListSelectionEvent
and TableModelEvent. A ListSelectionEvent is generated when the user selects
something in the table. By default, JTable allows you to select one or more
complete rows, but you can change this behavior to allow one or more columns,
or one or more individual cells to be selected. A TableModelEvent is fired when
that table’s data changes in some way.
Constructors:
Constructor Description
JTable() Creates a table with empty cells.
JTable(Object[][] rows, Object[] Creates a table with the specified data.
columns)
In the first form, the tree is constructed from the elements in the
array obj. The second form constructs the tree from the elements of vector
v. In the third form, the tree whose root nodeis specified by tn specifies the
tree. Although JTree is packaged in javax.swing, its support classes and
interfaces are packaged in javax.swing.tree. This is because the number
of classes and interfaces neededto support JTree is quite large. JTree relies
on two models: TreeModel and TreeSelectionModel. A JTree generates a
variety of events, but three relate specifically to trees:
TreeExpansionEvent, TreeSelectionEvent, and TreeModelEvent.
TreeExpansionEvent events occur when a nodeis expanded or collapsed.
A TreeSelectionEvent is generated when the user selects ordeselects a
node within the tree. A TreeModelEvent is fired when the data or structure
of thetree changes. The listeners for these events are
TreeExpansionListener, TreeSelectionListener, and TreeModelListener,
respectively. The tree event classes and listener interfaces are packaged in
javax.swing.event.The event handled by the sample program shown in
this section is TreeSelectionEvent. To listen for this event, implement
TreeSelectionListener. It defines only one method, called valueChanged(
), which receives the TreeSelectionEvent object. You can obtain the path
to the selected object by calling getPath( ), shown here, on the event
object.
TreePathgetPath( )
Here, obj is the object to be enclosed in this tree node. The new
tree node doesn’t have a parent or children. To create a hierarchy of tree
nodes, the add( ) method of DefaultMutableTreeNode canbe used. Its
signature is shown here:
void add(MutableTreeNode child)
9
Here, child is a mutable tree node that is to be added as a child to
the current node. JTree does not provide any scrolling capabilities of its
own. Instead, a JTree is typically placed within a JScrollPane. This way, a
large tree can be scrolled through a smaller viewport. Theprogram creates
a DefaultMutableTreeNode instance labeled “Options.” This is the
topnode of the tree hierarchy. Additional tree nodes are then created, and
the add( ) method is called to connect these nodes to the tree. A reference
to the top node in the tree is provided as the argument to the JTree
constructor. The tree is then provided as the argument to the JScrollPane
constructor. This scroll pane is then added to the content pane. Next, a
label is created and added to the content pane. The tree selection is
displayed in this label. To receive selection events from the tree, a
TreeSelectionListener is registered for the tree. Inside the valueChanged( )
method, the path to the current selection is obtained and displayed.
// Demonstrate JTree.
import java.awt.*;
import javax.swing.event.*;
import javax.swing.*;
import javax.swing.tree.*;
/*
<applet code="JTreeDemo" width=400 height=200>
</applet>
*/
public class JTreeDemo extends JApplet {
JTree tree;
JLabeljlab;
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Create top node of tree.
DefaultMutableTreeNode top = new
DefaultMutableTreeNode("Options");
10
// Create subtree of "A".
DefaultMutableTreeNode a = new DefaultMutableTreeNode("A");
top.add(a);
DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1");
a.add(a1);
DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2");
a.add(a2);
// Create subtree of "B".
DefaultMutableTreeNode b = new DefaultMutableTreeNode("B");
top.add(b);
DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1");
b.add(b1);
DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2");
b.add(b2);
DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3");
b.add(b3);
// Create the tree.
tree = new JTree(top);
// Add the tree to a scroll pane.
JScrollPanejsp = new JScrollPane(tree);
// Add the scroll pane to the content pane.
add(jsp);
// Add the label to the content pane.
jlab = new JLabel();
add(jlab, BorderLayout.SOUTH);
// Handle tree selection events.
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEventtse) {
jlab.setText("Selection is " + tse.getPath());
}
});
}
}
It generates text events when the user enters a character. The plain
text components (text field, password field, and text area) are the easiest
and most commonly used components. In a few lines of code, you can
easily create, configure, and use a plain text component in your program.
The components that can display styled text (editor pane and text pane)
typically require more effort to use. Most programmers using editor pane
11
or text pane need to build a user interface that lets the user manipulate the
text styles. Also, getting the content from a styled text component
typically requires more code than a simple call to getText. Yet, as the
diagram shows, both plain and styled text components inherit from
JTextComponent. This abstract base class provides a highly-configurable
and powerful foundation for text manipulation. JTextComponent provides
these customizable features for all of its descendants.
1.6.1 JTextField:
1.6.2 JPasswordField:
Constructors:
JPasswordField(): Constructs a new JPasswordField, with a default
document, null starting text string, and 0 column width.
JPasswordField(int columns): Constructs a new empty JPasswordField
with the specified number of columns.
JPasswordField(String text): Constructs a new JPasswordField
initialized with the specified text.
13
JPasswordField(String text, int columns): Construct a new
JPasswordField initialized with the specified text and columns.
import javax.swing.*;
public class PasswordFieldExample {
public static void main(String[] args) {
JFrame f=new JFrame("Password Field Example");
JPasswordField value = new JPasswordField();
JLabel l1=new JLabel("Password:");
l1.setBounds(20,100, 80,30);
value.setBounds(100,100,100,30);
f.add(value); f.add(l1);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
1.6.3 JTextArea:
Constructors:
JTextArea(): Creates a text area that displays no text initially.
JTextArea(String s): Creates a text area that displays specified text
initially.
JTextArea(int row, int column): Creates a text area with the specified
number of rows and columns that displays no text initially.
JTextArea(String s, int row, int column): Creates a text area with the
specified number of rows and columns that displays specified text.
Methods:
void setRows(int rows): It is used to set specified number of rows.
void setColumns(int cols): It is used to set specified number of columns.
void setFont(Font f): It is used to set the specified font.
void insert(String s, int position): It is used to insert the specified text on
the specified position.
void append(String s): It is used to append the given text to the end of the
document.
import javax.swing.*;
14
public class TextAreaExample
{
TextAreaExample(){
JFrame f= new JFrame();
JTextArea area=new JTextArea("Welcome to javatpoint");
area.setBounds(10,30, 200,200);
f.add(area);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaExample();
}}
Progress Monitors:
15
1.8 COMPONENT ORGANISER
Split Panes:
That's all you have to do. If you like, you can add "one-touch
expand" icons to the splitter bar. We see those icons in the top pane inthe
Metal look and feel, they are small triangles. If you click one of them, the
splitter moves all the way in the direction to which the triangle is pointing,
expanding one of the panes completely.
innerPane.setOneTouchExpandable(true);
TabbedPane:
The last parameter of the addTab method has type Component. To add
multiple components into the same tab, you first pack them up in a
container, such as a JPanel. The icon is optional; for example, the addTab
method does not require an icon:
tabbedPane.addTab(title, component);
We can also add a tab in the middle of the tab collection with the insertTab
method:
16
tabbedPane.insertTab(title, icon, component, tooltip, index);
If we have a lot of tabs, then they can take up quite a bit of space.
Starting with JDK 1.4, we can display the tabs in scrolling mode, in which
only one row of tabs is displayed, together with a set of arrow buttons that
allow the user to scroll through the tab set.
We set the tab layout to wrapped or scrolling mode by calling
tabbedPane.setTabLayoutPolicy(JTabbedPane.WRAP_TAB_LAYOUT);
REFERENCES
1. What is Servlets?
2. Explain Text components.
3. Explain Progress Bar in detail.
*****
17
UNIT II
2
INTRODUCTION TO SERVLETS
Unit Structure
2.0 Need for dynamic content
2.1 Java Servlet Technology
2.2 Why Servlets?
2.3 Servlet API
2.4 Servlet and ServletConfig interface
2.5 ServletRequest Interface
2.6 ServletResponse Interface
2.7 Generic Servlet class
2.8 ServletInputStream class
2.9 ServletOutputStream class
2.10 RequestDispatcher Interface
2.11 HttpServlet Class
2.12 HttpServletRequest interface
2.13 HttpServletResponse Interface
2.14 HttpSession Interface
2.15 Servlet Lifecycle
2.16 Organization of a web application
2.17 Creating a web application (using Netbeans)
Unit End Questions
References
19
2. Portability: because it uses Java language.
3. Robust: JVM manages Servlets, so we don't need to worry about the
memory leak, garbage collection, etc.
4. Secure: because it uses java language.
Two packages contain the classes and interfaces that are required
to build servlets. These are javax.servlet and javax.servlet.http. They
constitute the Servlet API. Keep in mind that these packages are not part
of the Java core packages. Instead, they are standard extensions provided
by Tomcat. Therefore, they are not included with Java SE 6. The Servlet
API has been in a process of ongoing development and enhancement. The
current servlet specification is version 2.4, and that is the one used in this
book. However, because changes happen fast in the world of Java, you
will want to check for any additions or alterations. The javax.servlet
package contains a number of interfaces and classes that establish the
framework in which servlets operate. The following table summarizes the
core interfaces that are provided in this package. The most significant of
these is Servlet. All servlets must implement this interface or extend a
class that implements the interface. The ServletRequest and
ServletResponse interfaces are also very important.
21
2.6 SERVLETRESPONSE INTERFACE
The ServletResponse interface enables a servlet to formulate a response
for a client. Several of its methods are summarized in Table 2.5.
22
2.8 SERVLETINPUTSTREAM CLASS
23
Figure 2.2: forward() method
24
Table 2.6: HttpServlet class methods
2.12 HTTPSERVLETREQUEST
The HttpServletRequest interface enables a servlet to obtain
information about a client request. Several of its methods are shown in
Table 2.7
Three methods are central to the life cycle of a servlet. These are
init( ), service( ), and destroy( ). They are implemented by every servlet
and are invoked at specific times by the server. Let us consider a typical
user scenario to understand when these methods are called. First, assume
that a user enters a Uniform Resource Locator (URL) to a web browser.
The browser then generates an HTTP request for this URL. This request is
then sent to the appropriate server. Second, this HTTP request is received
by the web server. The server maps this request to a particular servlet. The
servlet is dynamically retrieved and loaded into the address space of the
server. Third, the server invokes the init( ) method of the servlet. This
method is invoked only when the servlet is first loaded into memory. It is
possible to pass initialization parameters to the servlet so it may configure
26
itself. Fourth, the server invokes the service( ) method of the servlet. This
method is called to process the HTTP request. You will see that it is
possible for the servlet to read data that has been provided in the HTTP
request. It may also formulate an HTTP response for the client. The servlet
remains in the server’s address space and is available to process any other
HTTP requests received from clients. The service( ) method is called for
each HTTP request. Finally, the server may decide to unload the servlet
from its memory. The algorithms by which this determination is made are
specific to each server. The server calls the destroy( ) method to relinquish
any resources such as file handles that are allocated for the servlet.
Important data may be saved to a persistent store. The memory allocated
for the servlet and its objects can then be garbage collected.
Before we see how the servlet works, let’s get familiar with these three
terms.
Web Server: it can handle HTTP Requests send by clients and responds
the request with an HTTP Response.
27
2. Select Java Web -> Web Application, then click on Next.
28
3. Give a name to your project and click on Next.
29
5. The complete directory structure required for the Servlet Application
will be created automatically by the IDE.
30
7. Give a Name to your Servlet class file.
31
8. Now, your Servlet class is ready, and you just need to change the
method definitions and you will good to go.
32
10. Create an HTML file, right click on Web Pages -> New -> HTML
33
12. Write some code inside your HTML file. We have created a hyperlink
to our Servlet in our HTML file.
13. Edit web.xml file. In the web.xml file you can see, we have specified
the url-pattern and the servlet-name, this means when hello url is
accessed our Servlet file will be executed.
14. Run your application, right click on your Project and select Run.
34
15. Click on the link created, to open your Servlet.
REFERENCES
*****
35
UNIT III
3
JAVA DATABASE CONNECTIVITY
Unit Structure
3.0 Objective
3.1 Introduction
3.2 Design of JDBC
3.3 JDBC configuration
3.4 Executing SQL statement, Query Execution
3.5 Scrollable and updatable result sets
3.6 Row sets
3.7 Metadata
3.8 Transaction
3.9 Summary
Reference for further reading
Unit End Exercises
3.0 OBJECTIVE
3.1 INTRODUCTION
The JDBC library includes APIs for each of the tasks commonly
associated with database usage:
36
● Establish a connection to a database
● Creating SQL or MySQL statements
● Executing that SQL or MySQL queries in the database
● Viewing & Modifying the resulting records using resultset.
JDBC API is a Java programming API that can access any kind of
tabular data, especially data stored in a Relational Database. JDBC works
with Java on different platforms, such as Windows, Mac OS, and the
various versions of Unix/Linux.
JDBC Architecture:
● DriverManager:
○ Manages a list of database drivers.
○ Matches connection requests with the proper database driver
○ Establish a database Connection.
● Driver:
○ Handles the communications with the database server.
○ DriverManager to manage objects
● Connection :
○ This interface with all methods for contacting a database.
○ Connection object represents the communication context
● Statement :
○ This interface to submit the SQL statements to the database.
○ Interfaces accept parameters in addition to executing stored
procedures.
● ResultSet:
○ These objects hold data retrieved from a database after execute an
SQL query using Statement objects.
○ It acts as an iterator.
● SQLException:
○ This class handles any errors that occur in a database application.
38
JDBC drivers are divided into four types or levels. The different types of
jdbc drivers are:
1. Type 1: JDBC-ODBC Bridge driver (Bridge)
2. Type 2: Native-API/partly Java driver (Native)
3. Type 3: JDBC Network-All JAVA driver (Middleware)
4. Type 4: All Java/Native-protocol driver (Pure)
Type 2 drivers use the Java Native Interface (JNI) to make calls to a
local database library API. This driver converts the JDBC calls into a
database specific call for databases such as SQL, ORACLE etc.
Native-protocol/all-Java driver:
The Type 4 uses java networking libraries to communicate directly with
the database server.
40
Fig. 5 Type 4: 100% pure Java
41
memory, which automatically registers it. This method is preferable
because it allows to make the driver registration configurable and portable.
The following example uses Class.forName( ) to register the Oracle
driver:
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException ex)
{
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
DriverManager.registerDriver():
The second approach can use to register a driver is to use the static
DriverManager.registerDriver() method.
try {
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver( myDriver );
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
Following table lists down popular JDBC driver names and database
URLs.
RDBMS JDBC driver name URL format
MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/
databaseName
ORACLE oracle.jdbc.driver.OracleDrive jdbc:oracle:thin:@hostname:p
r ort Number:databaseName
42
DB2 COM.ibm.db2.jdbc.net.DB2D jdbc:db2:hostname:port
river Number/databaseName
Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:hostname:
port Number/databaseName
import java.util.*;
String URL = "jdbc:oracle:thin:@amrood:1521:EMP";
Properties info = new Properties( );
info.put( "user", "username" );
info.put( "password", "password" );
Connection conn = DriverManager.getConnection(URL);
43
3.5 EXECUTING SQL STATEMENT, QUERY
EXECUTION
Statement Class:
For sending SQL Statements, JDBC uses the executeQuery (String
SQL) method of this Statement Class.
The execute (String SQL) method which will return a boolean value,
whether the same have been executed or not. This is normally used
when the statement returns more than one Result Set.
We can also use the executeUpdate (String SQL) method, which will
return an int value, which the number of rows updated (that is inserted,
deleted, or modified).
JDBC provides two kinds of objects that can be used to execute SQL
Statements and they are PreparedStatement and CallableStatement
interfaces which are sub-interfaces of the Statement Interface. The
PreparedStatement Interface extends the Statement Interface and the
CallableStatement Interface extends the PreparedStatement interface.
PreparedStatement objects differ from the Statement objects in that the
SQL statement is pre-compiled and can have placeholders (?) for
runtime parameters values.
The PreparedStatement objects are particularly useful when a statement
will be executed many times (for example, adding new rows) since
substantial performance gains can be achieved.
Example:
import java.sql.*;
class DBTest
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c =
DriverManager.getConnection("jdbc:odbc:dum");
Statement s = c.createStatement();
s.execute("create table DeptMaster(deptno Number, dname
Text, loc Text)");
System.out.println("Table successfully created");
44
}
catch(SQLException e)
{
System.out.println("Datebase Error"+e.getMessage());
}
catch(Exception e)
{
System.out.println("General Error"+e.getMessage());
}
}
}
Creating and Executing SQL statements
We can also specify the columns for which we want to insert data.
45
UPDATE table_name Set colunm_name = new_value WHERE
column_name = some_name;
b) ScrollInSensitive ResultSet:
● These are scrollable ResultSet objects, which will allow the later
database modifications after creation.
● To represent this ResultSet object we have to use the following
constant from the ResultSet interface.
Public static final TYPE_SCROLL_INSENSITIVE
This ResultSet will allow the users only to read the data.To
represent this ResultSet object we have to use the following constant
from the ResultSet interface.
Public static final int CONCUR_READ_ONLY
2. Updatable ResultSet:
This ResultSet object will allow the user to perform updates on it’s
content.
46
To represent this ResultSet object to use following constant from
ResultSet interface.
Public static final int CONCUR_UPDATABLE.
Example:
import java.sql.Connection;
import java.sql.DriverManager;
47
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
public class JdbcApp14 {
public static void main(String args[])throws Exception
{
Class.forName(“com.mysql.jdbc.Driver”);
Properties p=new Properties();
Connection
con=DriverManager.getConnection(“jdbc:mysql://localhos
t:3306/test ”,”root”,”system”);
Statement
st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet. CONCUR_UPDATABLE);
boolean b=st.execute(“select * from emp1″);
System.out.println(b);
ResultSet rs=st.getResultSet();
System.out.println(“————————“);
System.out.println(“ENO ENAME ESAL”);
while(rs.next())
{
System.out.println(rs.getString(“eno”)+”
“+rs.getString(“ename”) +” “+rs.getString(“esal”));
}
System.out.println(“application in pausing state”);
System.out.println(“perform updations at database”);
System.in.read();
rs.beforeFirst();
System.out.println(“data after updations”);
System.out.println(“——————–“);
System.out.println(“ENO ENAME ESAL”);
System.out.println(“——————–“);
while(rs.next())
{
rs.refreshRow();
System.out.println(rs.getString(“eno”)+”
“+rs.getString(“ename”) +” “+rs.getString(“esal”));
}
con.close();
}
}
7. Row sets:
● A RowSet object is a java bean component and extends the ResultSet
interface Thus, it has a set of JavaBeans properties and follows the
JavaBeans event model.
48
● A RowSet object's properties allow it to create its own database
connection and to execute its own query in order to fill itself with data.
● Types of Rowset
The RowSet is mainly classified into two types as per their properties:-
1. Connected Rowset.:- The connected rowset as the name suggests
is connected to the database connection object like the resultset.
2. Disconnected RowSet:- The disconnected RowSet only connects
to the database whenever needed and after finishing the
communication they close the database connection. So if the
connection pool is minimally used in this case.
2. Creating the default object:- This method is useful to set the data
sources dynamically. In this method the Database URL, username
and password is explicitly set in the RowSetObject.
Example:-
JdbcRowSet jdbcRs = new JdbcRowSetImpl();
jdbcRs.setUsername("user");
jdbcRs.setPassword("password");
jdbcRs.setUrl("jdbc:mySubprotocol:mySubname");
jdbcRs.setCommand("select * from EMP ");
jdbcRs.execute();
● The following example will illustrate the basic operation using the
JDBCRowSet interface.
import java.sql.SQLException;
import javax.sql.rowset.JdbcRowSet;
import com.sun.rowset.JdbcRowSetImpl;
public class JDBCRowSetExample
{
public static void main(String[] args) throws
SQLException
{
49
JdbcRowSet jdbcRs = new JdbcRowSetImpl();
jdbcRs.setUsername("scott");
jdbcRs.setPassword("tiger");
jdbcRs.setUrl("jdbc:odbc:MyDsn");
jdbcRs.setCommand("select * from employee");
jdbcRs.execute();
while(jdbcRs.next())
{
System.out.println(jdbcRs.getString("ename"));
}
}
}
8. Metadata:
● Data about the data is called metadata. In JDBC there are two types of
metadata.
1.Database metadata
2.ResultSet metadata.
● JDBC MetaData is the collective information about the data structure
and property of a column available in the table. The meta data of any
table tells the name of the columns,datatype used in column and
constraint used to enter the value of data into the column of the table.
● Loading a driver by calling a class.forname( ),this accepts the driver
class as argument.
getMetaData ( ) - The Result Set call get Metadata( ),which returns the
property of the retrieve record set (length,field,column).MetaData
accounts for the data element and its attribute.
Example:
JdbcMetaDataGettables.java
50
import java.sql.*;
public class JdbcMetaDataGettab
{
static public final String driver = "com.mysql.jdbc.Driver";
static public final String connection =
"jdbc:mysql://localhost:3306/test";
static public final String user = "root";
static public final String password = "root";
public static void main(String args[])
{
try
{
Class.forName(driver);
Connection con = DriverManager.getConnection(connection,
user,password);
Statement st = con.createStatement();
String sql = "select * from person";
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metaData = rs.getMetaData();
int rowCount = metaData.getColumnCount();
System.out.println("Table Name : " +metaData.getTableName(2));
System.out.println("Field \tsize\tDataType");
for (int i = 0; i < rowCount; i++)
{
System.out.print(metaData.getColumnName(i + 1) + "\t");
System.out.print(metaData.getColumnDisplaySize(i + 1)+"\t");
System.out.println(metaData.getColumnTypeNa me(i + 1));
}
} catch (Exception e)
{
System.out.println(e);
}
}
}
Output:-
Table Name: person
Field Size DataTypes
id 2 VARCHAR
cname 50 VARCHAR
dob 10 DATE
9. Transaction:
● Transaction represents a single unit of work. The ACID properties
describe the transaction management well. ACID stands for Atomicity,
Consistency, isolation and durability.
● Advantage of Transaction Management is fast performance It makes
the performance fast because the database is hit at the time of commit.
51
Fig. 6 Transaction Management in JDBC
10 SUMMARY
1. What are the seven basic steps for using JDBC to access a database?
Explain briefly with syntax.?
2. Explain different types of JDBC Driver Managers.?
3. Explain the different types of JDBC Driver?
4. Write a short note on: metadata & resultset.?
*****
53
4
JAVA SERVER PAGES-1
Unit Structure
4.0 Objective
4.1 Introduction
4.2 Disadvantages,
4.3 JSP v/s Servlets,
4.4 Life Cycle of JSP
4.5 Comments,
4.6 JSP documents,
4.7 JSP elements,
4.8 Summary
Reference for further reading
Unit End Exercises
4.0 OBJECTIVE
4.1 INTRODUCTION
54
4.2 DISADVANTAGES OF JSP
1. Not able to use the feature-rich Swing or AWT controls to construct
the user interface.
2. The HTML language has fewer features than the Swing controls for
creating a user interface.
3. In addition, simple functions such as scrolling down in a list of
records, deleting a record, or changing the way information is sorted
requires a refresh of the page.
4. Embedding of JavaScript in the HTML page to enhance functionality,
but this solution requires that the JavaScript that you use be supported
by the ability of users' browsers to interpret it correctly.
5. As JSP pages are translated to servlets and compiled, it is difficult to
trace errors occurred in JSP pages.
6. JSP pages require double the disk space to hold the JSP page.
7. JSP pages require more time when accessed for the first time as they
are to be compiled on the server.
1. Translation phase:
Web server needs a servlet container to provide an interface to servlets,
the server needs a JSP container to process JSP pages. The JSP
container is responsible for intercepting incoming requests for JSP
pages.
To process all JSP elements in the page, the container first turns the
JSP page into a servlet (known as the JSP page implementation class).
The container then compiles the servlet class.
JSP page Converted to a servlet and compiling the servlet form the
translation phase. The JSP container begins the translation phase for a
page automatically when it receives the first request for the page.
The translation phase takes a bit of time, the first user to request a JSP
page notices a slight delay.
Model 1 architecture:
Model 2 architecture:
The Model 2 architecture, shown below, is a server-side
implementation of the popular Model/View/Controller design pattern.
In Model 2 processing is divided between presentation and front
components.
58
Model 2 Presentation components are JSP pages that generate the
HTML/XML response that determines the user interface when rendered
by the browser.
Front components (controllers) do not handle any presentation issues,
but rather, process all the HTTP requests. They are responsible for
creating any beans or objects used by the presentation components, as
well as deciding, depending on the user's actions, which presentation
component to forward the request to. Servlet or JSP pages can be
implemented by front components.
The benefits of this architecture is that there is no processing logic
within the presentation component itself; it is simply responsible for
retrieving any objects or beans that may have been previously created
by the controller, and extracting the dynamic content within for
insertion within its static templates.
Another benefit of this approach is that the front components present a
single point of entry into the application, making the management of
application state, security, and presentation uniform and simple to
maintain.
4.5 COMMENTS
JSP comments are ignored by JSP containers that should be marked. A
JSP comment is useful for hiding or "comment out" part of your JSP
page.
Following is the syntax of JSP comments:
<%-- This is JSP comment --%>
Following is the simple example for JSP Comments:
59
<html>
<head><title>A Comment Test</title></head>
<body>
<h2>A Test of Comments</h2>
<%-- This comment will not be visible in the page source --%>
</body>
</html>
Syntax Purpose
<%-- comment --%> A JSP comment. Ignored by the JSP engine.
<!-- comment --> An HTML comment. Ignored by the browser.
<\% Represents static <% literal.
%\> Represents static %> literal.
\' A single quote in an attribute that uses single
quotes.
\" A double quote in an attribute that uses double
quotes.
60
Template or HTML data is passed through unmodified one, so the
HTML that is ultimately generated contains the template data exactly
as it was coded in the .jsp file.
1. Directives:
61
buffer
language
isELIgnored
isThreadSafe
autoFlush
session
pageEncoding
errorPage
isErrorPage
1) Import:
<html>
<body>
<%@ page import="java.util.Date" %>
Today is: <%= new Date() %>
</body>
</html>
2) contentType:
The contentType attribute defines the MIME(Multipurpose Internet
Mail Extension) type of the HTTP response.The default value is
"text/html;charset=ISO-8859-1".
<html>
<body>
<%@ page contentType=application/msword %>
Today is: <%= new java.util.Date() %>
</body>
</html>
3) extends:
The extends attribute defines the parent class that will be inherited
by the generated servlet. It is rarely used.
62
4) Info:
This attribute simply sets the information of the JSP page which is
retrieved later by using getServletInfo() method of the Servlet interface.
<html>
<body>
<%@ page info="composed by ABC" %>
Today is: <%= new java.util.Date() %>
</body>
</html>
For example:
5) Buffer:
● The buffer attribute sets the buffer size in kilobytes to handle output
generated by the JSP page. The default size of the buffer is 8Kb.
<html>
<body>
<%@ page buffer="16kb" %>
Today is: <%= new java.util.Date() %>
</body>
</html>
6) Language:
The language attribute specifies the scripting language used in the JSP
page. The default value is "java".
7) isELIgnored:
We can ignore the Expression Language (EL) in jsp by the isELIgnored
attribute.
63
By default its value is false i.e. Expression Language is enabled by
default.
<%@ page isELIgnored="true" %>//Now EL will be ignored
8) isThreadSafe:
Servlet and JSP both are multithreaded. If you want to control this
behaviour of a JSP page, you can use the isThreadSafe attribute of the
page directive.
The value of isThreadSafe value is true. If you make it false, the web
container will serialize the multiple requests, i.e. it will wait until the
JSP finishes responding to a request before passing another request to
it.
The value of isThreadSafe attribute like:
<%@ page isThreadSafe="false" %>
The web container in such a case, will generate the servlet as:
public class SimplePage_jsp extends HttpJspBase
implements SingleThreadModel{
.......
}
9) errorPage:
Example:
//index.jsp
<html>
<body>
<%@ page errorPage="myerrorpage.jsp" %>
<%= 100/0 %>
</body>
</html>
10) isErrorPage:
The isErrorPage attribute is used to declare that the current page is the
error page.
Note: The exception object can only be used in the error page.
Example:
//myerrorpage.jsp
64
<html><body>
<%@ page isErrorPage="true" %>
Sorry an exception occured!
<br/>
The exception is: <%= exception %>
</body>
</html>
<html>
<body>
<%@ include file="header.html" %>
Today is: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
In this example, using our tag named currentDate. To use this tag it
must specify the taglib directive so the container may get information
about the tag.
65
<html>
<body>
<%@ tagliburi="http://www.javatpoint.com/tags" prefix="mytag" %>
<mytag:currentDate/>
</body>
</html>
1. scriptlet tag:
A scriptlet is a valid code in java and is placed in the _jspService()
method of the JSP engine at the time of running. The scriptlet syntax is-
<% java code %>
There are variables available exclusively for the scriplets.
They are request, response, out,session and pageContext, application,
config and exception.
index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
66
welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
</form>
</body>
</html>
index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname"><br/>
<input type="submit" value="go">
</form>
</body>
</html>
welcome.jsp
<html>
<body>
<%= "Welcome "+request.getParameter("uname") %>
</form>
</body>
</html>
68
index.jsp
<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>
index.jsp
<html>
<body>
<%!
int cube(int n)
{
return n*n*n*;
}
%>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>
4. JSP Comment:
There is only one type of JSP comment available by JSP specification.
JSP Comment Syntax:
<%-- comment --%>
This JSP comment tag tells the JSP container to ignore the comment
part from compilation. That is, the commented part of source code is
not considered for the content parsed for ‘response’.
<html>
<body>
<%-- This JSP comment part will not be included in the response
object --%>
</body>
</html>
69
4.8 SUMMARY
*****
70
5
JAVA SERVER PAGES-2
Unit Structure
5.0 Objective
5.1 Introduction
5.2 Action elements
5.3 Implicit objects
5.4 Scope
5.5 character quoting conventions
5.6 unified expression language
5.7 Summary
Reference for further reading
Unit End Exercises
5.0 OBJECTIVE
5.1 INTRODUCTION
● There are many JSP action tags or elements. Each JSP action tag is
used to perform some specific tasks.
● The action tags are used to control the flow between pages and to use
Java Bean.
● There are 9 jsp implicit objects. These objects are created by the web
container that are available to all the jsp pages.
● The available implicit objects are out, request, config, session,
application etc.
71
● Each JSP action tag is used to perform some specific tasks.
● The action tags are used to control the flow between pages and to use
Java Bean.
In this example, we are forwarding the request to the printdate.jsp file with
parameter and printdate.jsp file prints the parameter value with date and
time.
index.jsp
<html>
<body>
<h2>this is index page</h2>
<jsp:forward page="printdate.jsp" >
<jsp:param name="name" value="ABC" />
</jsp:forward>
</body>
</html>
printdate.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime());
%>
<%= request.getParameter("name") %>
</body>
</html>
In this example, index.jsp file includes the content of the printdate.jsp file.
index.jsp
<html>
<body>
<h2>this is index page</h2><jsp:include page="printdate.jsp" />
<h2>end section of index page</h2>
</body>
</html>
printdate.jsp
<html>
<body>
<% out.print("Today
is:"+java.util.Calendar.getInstance().getTime()); %>
</body>
</html>
package mypack;
public class Test{
public static void main(String args[])
{
Employee e=new Employee();//object is created
e.setName("Subodh");//setting value to the object
System.out.println(e.getName()); }}
75
3. page: specifies that you can use this bean within the JSP page. The
default scope is page.
4. request: specifies that you can use this bean from any JSP page that
processes the same request. It has a wider scope than the page.
5. session: specifies that you can use this bean from any JSP page in the
same session whether it processes the same request or not. It has a
wider scope than request.
6. application: specifies that you can use this bean from any JSP page in
the same application. It has a wider scope than session.
7. class: instantiates the specified bean class but it must have no-arg or no
constructor and must not be abstract.
8. type:provides the bean a data type if the bean already exists in the
scope. It is mainly used with class or beanName attributes. If you use
it without class or beanName, no bean is instantiated.
9. beanName:instantiates the bean using the
java.beans.Beans.instantiate() method.
4. implicit objects:
There are 9 jsp implicit objects. These objects are created by the web
container that are available to all the jsp pages.
The available implicit objects are out, request, config, session,
application etc.
A list of the 9 implicit objects is given below:
Object Type
Out JspWriter
Request HttpServletRequest
Response HttpServletResponse
Config ServletConfig
application ServletContext
Session HttpSession
pageContext PageContext
page Object
exception Throwable
A. JSP out:
● For writing any data to the buffer, JSP provides an implicit object
named out. It is the object of JspWriter. In case of servlet you need to
write:
77
PrintWriter out=response.getWriter();
index.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime());
%>
</body>
</html>
B. JSP request:
The JSP request is an implicit object of type HttpServletRequest i.e.
created for each jsp request by the web container. It can also be used to
set, get and remove attributes from the jsp request scope.
C. JSP response:
JSP response is an implicit object of type HttpServletResponse. The
instance of HttpServletResponse is created by the web container for
each jsp request.
Example of response implicit object
index.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
welcome.jsp
<%
response.sendRedirect("http://www.google.com");
%>
78
D. JSP config:
In JSP, config is an implicit object of type ServletConfig.
This object can be used to get an initialization parameter for a
particular JSP page.
The config object is created by the web container for each jsp page.
index.html
<form action="welcome">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
web.xml file
<web-app>
<servlet>
<servlet-name>ABC</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>
<init-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ABC</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
welcome.jsp
<%
out.print("Welcome "+request.getParameter("uname"));
String driver=config.getInitParameter("dname");
out.print("driver name is="+driver);
%>
E. JSP application:
In JSP, application is an implicit object of type ServletContext.
The instance of ServletContext is created only once by the web
container when application or project is deployed on the server.
Example:
index.html
<form action="welcome">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
79
</form>
web.xml file
<web-app>
<servlet>
<servlet-name>ABC</servlet-name>
<jsp-file>/welcome.jsp</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ABC</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
<context-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>
</web-app>
welcome.jsp
<%
out.print("Welcome "+request.getParameter("uname"));
String driver=application.getInitParameter("dname");
out.print("driver name is="+driver);
%>
F. session:
In JSP, session is an implicit object of type HttpSession.
The Java developer can use this object to set,get or remove attributes or
to get session information.
Example:
index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
session.setAttribute("user",name);
80
<a href="second.jsp">second jsp page</a>
%>
</body>
</html>
second.jsp
<html>
<body>
<%
String name=(String)session.getAttribute("user");
out.print("Hello "+name);
%>
</body>
</html>
G. pageContext:
In JSP, pageContext is an implicit object of type PageContext class.
The pageContext object can be used to set,get or remove attribute from
one of the following scopes:
1. Page
2. request
3. Session
4. Application
Example:
index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
pageContext.setAttribute("user",name,PageContext.SESSION_SCOPE);
<a href="second.jsp">second jsp page</a>
%>
</body>
81
</html>
second.jsp
<html>
<body>
<%
String name=(String)pageContext.getAttribute
("user",PageContext.SESSION_SCOPE);
out.print("Hello "+name);
%>
</body>
</html>
5. Scope:
The availability of a JSP object for use from a particular place of the
application is defined as the scope of that JSP object.
Every object created in a JSP page will have a scope. Object scope in
JSP is segregated into four parts and they are page, request, session and
application.
a) Page:
‘page’ scope means the JSP object can be accessed only from
within the same page where it was created.
The default scope for JSP objects created using <jsp:useBean> tag
is page.
JSP implicit objects out, exception, response, pageContext, config
and page have ‘page’ scope.
b) Request:
A JSP object created using the ‘request’ scope can be accessed
from any pages that serves that request.
More than one page can serve a single request.
The JSP object will be bound to the request object.
Implicit object request has the ‘request’ scope.
c) Session:
‘Session scope means the JSP object is accessible from pages that
belong to the same session from where it was created.
The JSP object that is created using the session scope is bound to
the session object.
Implicit object session has the ‘session’ scope.
82
d) Application:
A JSP object created using the ‘application’ scope can be accessed
from any pages across the application.
The JSP object is bound to the application object.
Implicit object application has the ‘application’ scope.
Syntax Purpose
<\% Used in template text (static HTML) where you
really want "<%".
%\> Used in scripting elements where you really want
"%>".
\' A single quote in an attribute that uses single quotes.
Remember, however, that you can use either single
or double quotes, and the other type of quote will
then be a regular character.
\" A double quote in an attribute that uses double
quotes. Remember, however, that you can use either
single or double quotes, and the other type of quote
will then be a regular character.
%\> %>in an attribute.
<\% <% in an attribute.
\ Used as a delimiter.
<%-- A JSP comment. Ignored by JSP-to- scriptlet
comment-- translator. Any embedded JSP scripting elements,
%> directives, or actions are ignored.
<!-- An HTML comment. Passed through to resultant
comment-- HTML. Any embedded JSP scripting elements,
> directives, or actions are executed normally.
Expression Language(EL):
The Expression Language (EL) provides a way to simplify expressions
in JSP.
It is a simple language used for accessing implicit objects and Java
classes, and for manipulating collections in an elegant manner.
EL provides the ability to use run-time expressions outside of JSP
scripting elements.
83
"Unified" Expression Language:
JavaServer Pages each has its own expression language.
The expression language included in JSP provides greater flexibility
to the web application developer.
Deferred evaluation means that the technology using the unified EL
takes over the responsibility of evaluating the expression from the JSP
engine and evaluates the expression at the appropriate time during the
page lifecycle.
But the JSP EL is designed for immediate evaluation of expressions.
The Expression Language (EL) simplifies the accessibility of data
stored in the Java Bean component, and other objects like request,
session, application etc.
There are many implicit objects, operators and reserve words in EL.
Syntax for Expression Language (EL)
${ expression }
There are many implicit objects in the Expression Language. They are as
follows:
84
Example:
index.jsp
<form action="process.jsp">
Enter Name:<input type="text" name="name" /><br/><br/>
<input type="submit" value="go"/>
</form>
process.jsp
Welcome, ${ param.name }
Example of Expression Language that prints the value set in the session
scope
In this example, we print the data stored in the session scope using EL.
For this purpose, we have used a sessionScope object.
Index.jsp
Precedence of Operators in EL
There are many operators that have been provided in the Expression
Language.
1. [] .
2. ()
3. -(unary) not ! empty
4. * / div % mod
5. + - (binary)
6. <<= >>= lt le gtge
7. == != eq ne
8. && and
9. || or
10. ?:
Reverse words in EL
There are many reserved words in the Expression Language. They are as
follows:
lt le gt ge
eq ne true false
and or not instanceof
div mod empty null
85
SUMMARY
*****
86
UNIT IV
6
JAVA SERVER FACES
Unit Structure
6.1 Objective
6.2 Introduction
6.3 Need of MVC
6.4 What is JSF?
6.5 Components of JSF
6.6 JSF as an application
6.7 JSF lifecycle,
6.8 JSF configuration,
6.9 JSF web applications (login form, JSF pages)
6.10 Summary
Reference for further reading
Unit End Exercises
6.1 OBJECTIVE
6.2 INTRODUCTION
Module Description
Model Carries Data and login
View Shows User Interface
Controller Handles processing of an application.
A. Standard UI Components:
It contains a basic set of UI components like text fields, check boxes ,
list boxes, panel, label, radio button etc. These are called standard
components
B. Custom UI Components:
JSF lets create and use your own set of reusable components, These
components are called custom components.
JSF–Basic Tags
JSF provides a standard HTML tag library. These tags get rendered into
corresponding html output.
89
These tags need to use the following namespaces of URI in the html
node.
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html" >
Following are important Basic Tags in JSF:
90
Following are important Facelets Tags in JSF:
JSF–Convertor Tags:
JSF provides inbuilt converters to convert its UI component's data to
objects used in a managed bean and vice versa.
For example, these tags can convert a text into date objects and can
validate the format of input as well.
For these tags you need to use the following namespaces of URI in
html node.
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core" >
JSF–Validator Tags:
JSF provides inbuilt validators to validate its UI components. These
tags can validate length of field, type of input which can be a custom
object.
For these tags you need to use the following namespaces of URI in the
html node.
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core" >
91
Following are important Validator Tags in JSF :
JSF–Composite Components
JSF provides developers a powerful capability to define their own
custom components which can be used to render custom contents.
Facelets
● Facelets is a powerful but lightweight page declaration language that is
used to build JavaServer Faces views using HTML style templates and
to build component trees. Facelets features include the following:
Use of XHTML for creating web pages
92
Support for Facelets tag libraries in addition to JavaServer Faces
and JSTL tag libraries
Support for the Expression Language (EL)
Templating for components and pages
● Advantages of Facelets for large-scale development projects include
the following:
Support for code reuse through templating and composite
components
Functional extensibility of components and other server-side
objects through customization
Faster compilation time
Compile-time EL validation
High-performance rendering
93
Fig. 1 JavaServer Faces Standard Request-Response Lifecycle
95
Invoke Application Phase
○ In this phase the JavaServer Faces implementation handles any
application-level events, such as submitting a form or linking to
another page.
○ At this point, if the application needs to redirect to a different web
application resource or generate a response that does not contain
any JavaServer Faces components, it can call the
FacesContext.responseComplete method.
○ If the view being processed was reconstructed from state
information from a previous request and if a component has fired
an event, these events are broadcast to interested listeners.
○ Finally, the JavaServer Faces implementation transfers control to
the Render Response phase.
Render Response Phase
○ During this phase, JavaServer Faces constructs the view and
typical authority to the suitable resource for rendering the pages.
○ If the first request is this, the components that are represented on
the page will be added to the component tree. If this is not the first
request, the components are already added to the tree and need not
be added again.
○ If the request is a postback and errors were experienced during the
Apply Request Values phase, Process Validations phase, or Update
Model Values phase, the original page is rendered again during
this phase. If the pages consist h:message or h:messages tags, any
queued error messages are displayed on the page.
○ After the content of the view is relinquished, the state of the
response is saved so that upcoming requests can access it.
JSF configuration
web.xml faces-config.xml
96
web.xml
JSF requires the central configuration list web.xml in the directory
WEB-INF of the application. This is similar to other web-applications
which are based on servlets.
A FacesServlet is responsible for handling JSF applications.
FacesServlet is the central controller for the JSF application.
FacesServlet receives all requests for the JSF application and initializes
the JSF components before the JSP is displayed.
Initial format:
<?xml version="1.0"?>
<web-app>
..................................
..................................
..................................
</web-app>
faces-config.xml:
Second file faces-config.xml that will be in the same place where
web.xml is i.e. WEB-INF folder.
Here to take care of mentioning the version of xml as we did in the
web.xml file.
All tag elements will be within faces-config opening and closing tag
i.e. <faces-config>and </faces-config>.So the root element of this file
is <faces-config> tag.
"faces-config.xml" allows us to configure the application, managed
beans, convertors, validators, and navigation.
Initial format:
<?xml version="1.0"?>
<faces-config>
.................................
.................................
.................................
</faces-config>
97
This application will also introduce a UI component which is a submit
button.
Step 1: Create the table Users in mysql database as
CREATETABLEUsers(
uidint(20) NOTNULL AUTO_INCREMENT,
unameVARCHAR(60) NOTNULL,
passwordVARCHAR(60) NOTNULL,
PRIMARY KEY(uid));
INSERTINTOUsersVALUES(1,'adam','adam');
<h:commandButton
action="#{login.validateUsernamePassword}"
value="Login"></h:commandButton>
</h:form>
</h:body>
</html>
98
Step 4: Create the managed bean Login.java as;
package com.journaldev.jsf.beans;
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import com.journaldev.jsf.dao.LoginDAO;
import com.journaldev.jsf.util.SessionUtils;
@ManagedBean
@SessionScoped
public class Login implements Serializable {
99
}
//validate login
public String validateUsernamePassword() {
boolean valid = LoginDAO.validate(user, pwd);
if (valid) {
HttpSession session =
SessionUtils.getSession();
session.setAttribute("username", user);
return "admin";
} else {
FacesContext.getCurrentInstance().addMessage(
null,
new
FacesMessage(FacesMessage.SEVERITY_WARN,
"Incorrect
Username and Passowrd",
"Please enter
correct username and Password"));
return "login";
}
}
package com.journaldev.jsf.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.journaldev.jsf.util.DataConnect;
100
PreparedStatementps = null;
try {
con = DataConnect.getConnection();
ps = con.prepareStatement("Select uname,
password from Users where uname = ? and password = ?");
ps.setString(1, user);
ps.setString(2, password);
ResultSetrs = ps.executeQuery();
if (rs.next()) {
//result found, means valid inputs
return true;
}
} catch (SQLException ex) {
System.out.println("Login error -->" +
ex.getMessage());
return false;
} finally {
DataConnect.close(con);
}
return false;
}
}
package com.journaldev.jsf.util;
import java.sql.Connection;
import java.sql.DriverManager;
101
return null;
}
}
package com.journaldev.jsf.beans;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
.getExternalContext().getSession(false);
}
.getExternalContext().getSession(false);
return session.getAttribute("username").toString();
}
102
else
return null;
}
}
package com.journaldev.jsf.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public AuthorizationFilter() {
}
@Override
public void init(FilterConfigfilterConfig) throws
ServletException {
@Override
public void doFilter(ServletRequest request, ServletResponse
response,
FilterChain chain) throws IOException,
ServletException {
try {
HttpServletRequestreqt = (HttpServletRequest)
request;
HttpServletResponseresp = (HttpServletResponse)
response;
HttpSessionses = reqt.getSession(false);
103
if (reqURI.indexOf("/login.xhtml") >= 0
|| (ses != null
&&ses.getAttribute("username") != null)
|| reqURI.indexOf("/public/") >= 0
||
reqURI.contains("javax.faces.resource"))
chain.doFilter(request, response);
else
resp.sendRedirect(reqt.getContextPath() +
"/faces/login.xhtml");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
@Override
public void destroy() {
}
}
<navigation-rule>
<from-view-id>/login.xhtml</from-view-id>
<navigation-case>
<from-outcome>admin</from-outcome>
<to-view-id>/admin.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>
Login Page
105
6.10 SUMMARY
*****
106
107
7
ENTERPRISE JAVA BEAN (EJB)
Unit Structure
7.1 Objective
7.2 Introduction
7.3 Enterprise bean architecture,
7.4 Benefits of enterprise bean,
7.5 Types of beans,
7.6 Accessing beans ,
7.7 Packaging beans,
7.8 Creating web applications,
7.9 Creating enterprise bean,
7.10 Creating web client,
7.11 Creating JSP file,
7.12 Building and running web application
7.13 Summary
Reference for further reading
Unit End Exercises
7.1 OBJECTIVE
107
7.2 INTRODUCTION
The Enterprise JavaBeans (EJB) specification describes architecture
for the development and deployment of transactional, distributed
object applications based, server-side software components.
Organizations can develop their own components or purchase
components from third party vendors.
These server-side components, called enterprise beans, are distributed
objects that are hosted in Enterprise JavaBean containers and provide
remote services for clients distributed all-round the network.
108
An Enterprise Bean Server provides:
EJB Evolution:
EJB specification evolved significantly.
It is capable of embracing the requirement of many enterprises.
EJB is complicated due to:
○ Lack of good persistence strategy
○ Long and tedious deployment descriptors.
○ Limited capacity of testing.
There are two types of EJBs: session beans and message-driven beans.
1. Session Beans
2. Message-Driven Beans
Session Beans:
A session bean implements one or more business tasks.
A session bean might consist of methods that query and update data in
a relational table. Session beans are frequently used to implement
different services.
110
For example, an application developer implements one or several
session beans that retrieve and update inventory data in a database.
A session bean implements the javax.ejb.SessionBean interface,
following is the definition:
111
It is strictly a single invocation bean. It is active for reusable business
services that are not connected to any specific client, such as currency
calculations, mortgage rate calculations etc.
Stateless session beans may carry client-independent, read-only state
across a call. Succeeding calls are controlled by other stateless session
beans in the pool. The information is used only for the single
invocation.
Implementation Methods
Home Interface Extends javax.ejb.EJBHome and
requires a single create() factory
method, with no arguments, and a
single remove() method.
Remote Interface Extends javax.ejb.EJBObject and
defines the business logic
methods, which are implemented
in the bean implementation.
Bean implementation Implements SessionBean. This
class must be declared as public,
contain a public, empty, default
constructor, no finalize() method,
and implement the methods
defined in the remote interface.
Implementation Methods
Home Interface Extends javax.ejb.EJBHome and
requires one or more create()
factory methods, and a single
remove() method.
Remote Interface Extends javax.ejb.EJBObject and
defines the business logic
methods, which are implemented
in the bean implementation.
112
Message-Driven Beans:
Message-Driven Beans (MDB) provide a simple method to implement
asynchronous communication than using straight JMS. MDBs were
created to receive asynchronous JMS messages.
The container controls much of the setup required for JMS queues and
topics.
A MDB is the same as a stateless session bean because it does not save
conversational state and is used for handling various incoming requests.
Instead of handling direct requests from a client, MDBs handle requests
placed on a queue. Figure 1 shows how clients place requests on a
queue. The container takes the requests off of the queue and sends the
request to an MDB in its pool.
Method Description
onMessage(msg) The container dequeues a
message from the JMS queue
associated with this MDB and
gives it to this instance by
invoking this method.
setMessageDrivenContext(ctx) After the bean is created, the
setMessageDrivenContext
method is invoked.
ejbCreate() This method is used just like the
stateless session bean ejbCreate
method. No initialization should
be done in this method.
ejbRemove() Delete any resources allocated
within the ejbCreate method.
b. Business interface:
A Business interface is a standard java programming language interface
that contains the business methods in the enterprise bean.
A client can access a session bean through the methods defined in the
bean's interface or through the public methods of an enterprise bean
that has a no-interface view.
114
Packaging Enterprise Beans in WAR Modules
EJB provides the business logic of a web application.
WAR module simplifies deployment and application organization.
Enterprise beans may be packaged within a WAR module.
To include, the class files should be in the WEB-INF/classes directory.
To include a JAR file, add the JAR to the WEB-INF/lib directory of the
WAR module.
Enterprise beans do not require an ejb-jar.xml deployment descriptor.
JAR files that contain enterprise bean classes packaged within a WAR
module are not considered EJB JAR files.
JAR files are semantically equivalent to enterprise beans.
For example, The shopping cart bean exposes a local, no-interface view
and is defined as follows:
package com.example.cart;
@Stateless
public class CartBean { ... }
The credit card processing bean is packaged within its own JAR file,
cc.jar, exposes a local, no-interface view, and is defined as follows:
package com.example.cc;
@Stateless
public class CreditCardBean { ... }
Steps:
1. Create the enterprise bean: CurrencyConverterBean.
2. Create the application client: CurrencyConverterClient.
3. Create the web client in converter-war.
4. Deploy converter onto the server.
5. Run the application client.
6. Using a browser, run the web client.
115
7.9 CREATING ENTERPRISE BEAN
Enterprise Bean:
The enterprise bean in this example needs the following code:
● Remote business interface
● Enterprise bean class
Business Interface:
package com.sun.tutorial.javaee.ejb;
import java.math.BigDecimal;
import javax.ejb.Remote;
@Remote
public interface CurrencyConverter {
public BigDecimaldollarToYen(BigDecimal dollars);
public BigDecimalyenToEuro(BigDecimal yen);
}
Note the @Remote annotation decorating the interface definition. This lets
the container know that CurrencyConverterBean will be accessed by
remote clients.
package com.sun.tutorial.javaee.ejb;
116
import java.math.BigDecimal;
importjavax.ejb.*;
@Stateless
public class CurrencyConverterBean implements CurrencyConverter {
private BigDecimalyenRate = new BigDecimal("115.3100");
private BigDecimaleuroRate = new BigDecimal("0.0071");
packagecom.sun.tutorial.javaee.ejb;
importjava.math.BigDecimal;
importjavax.ejb.EJB;
publicCurrencyConverterClient(String[] args) {
117
}
System.exit(0);
} catch (Exception ex) {
System.err.println("Caught an unexpected exception!");
ex.printStackTrace();
}
}
}
<%!
private CurrencyConverter converter = null;
public void jspInit() {
try {
InitialContextic = new InitialContext();
converter = (CurrencyConverter)
ic.lookup(CurrencyConverter.class.getName());
} catch (Exception ex) {
System.out.println("Couldn’t create converter bean."+
ex.getMessage());
118
}
}
<body bgcolor="white">
<h1>CurrencyConverter</h1>
<hr>
<p>Enter an amount to convert:</p>
<form method="get">
<input type="text" name="amount" size="25">
<br>
<p>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
<%
String amount = request.getParameter("amount");
if ( amount != null &&amount.length() > 0 ) {
BigDecimal d = new BigDecimal(amount);
BigDecimalyenAmount = converter.dollarToYen(d);
%>
<p>
<%= amount %> dollars are <%= yenAmount %> Yen.
<p>
<%
BigDecimaleuroAmount =
converter.yenToEuro(yenAmount);
%>
<%= amount %> Yen are <%= euroAmount %> Euro.
<%
}
%>
</body>
</html>
119
7.12 BUILDING AND RUNNING WEB APPLICATION
120
Figure 3 Currency Converters Web Client
7.13 SUMMARY
Enterprise JavaBeans present a way to build components as well as a
means to make these components exist in a transactional, secure, and
distributed environment.
However, a single bean represents only one component - and
consequently only one part of a complete application.
EJB provides developers with flexibility in determining how these
components should be made to work together.
There are a number of ways in which Enterprise JavaBeans can be
made to work together to form a complete enterprise application.
Top Link can be integrated into each variety of EJB application
architecture to provide both the technology that enables these
architectures and the features that add value to them.
*****
121
UNIT V
8
HIBERNATE AND STRUTS
Unit Structure
8.1 Hibernate: Introduction
8.2 Hibernate
8.2 Structure of Hibernate.Cfg.Xml File (Hibernate Configurationfile)
8.3 Steps For Hibernateproject
8.2 HIBERNATE
Hibernate was developed with a goal to relieve the developers from 95%
of common data persistence related programming tasks by:
Making the developer feel as if the database contains plain Java
objects, without having them worry about how to get them out of [or
back into] databasetables.
Allowing the developers to focus on the objects and features of the
application, without having to worry about how to store them or find
them later.
To use Hibernate :
JavaBean classes [POJOs] that represents the table in the database are
created.
The instance variables of the class are mapped to the columns in the
database table.
Why Hibernate?:
Because of the following reasons:
Hibernate is Free under LGPL i.e. Hibernate can be used to
develop/package and distribute the applications for free.
It eliminates the need for repetitiveSQL.
It allows working with classes and objects instead of queries and result
sets which makes the approach more Object Oriented and less
Procedural.
Handles all Create, Read, Update, Delete [CRUD]operations.
Brings in portability across databases.
Supports IDEs such as Eclipse, NetBeans by providing a suite of plug-
ins.
Reduces the development time by supporting inheritance,
polymorphism, composition and the Java Collection framework.
Supports the multiple primary key generation including built-in
support for identity [Auto increment] columns, sequences, UUID
algorithm and HI/LO algorithm. Hibernate also includes support for
application assigned identifiers and composite keys.
Hibernate’s Dual Layer Cache Architecture [HDCLCA] delivers
thread safeness, nonblocking data access, session level cache, optional
second- level cache and optional query cache. Hibernate also works
well when other applications have simultaneous access to the database.
Supports connectionpooling
Supports wide range of database such as:
Oracle DB2 Sybase
MS SQLServer PostgreSQL MySQL
HypersonicSQL Mckoi SQL SAP DB
122
Session:
Session objects are lightweight and inexpensive to create. They
provide the main interface to perform actual database operations. All the
POJOs i.e. persistent objects are saved and retrieved with the help of a
Session object. Typically, session objects are created as needed and
destroyed when not required.
Transaction:
A Transaction represents a unit of work with the database. Any kind of
modifications initiated via the session object are placed with in a
transaction. A Session object helps creating a Transaction object.
Transaction objects are typically used for a short time and are closed by
either committing or rejecting.
Query:
Persistent objects are retrieved using a Query object. Query objects allow
using SQL or Hibernate Query Language [HQL] queries to retrieve the
actual data from the database and create objects.
Criteria
Persistent objects can also be retrieved using a Criteria object. Criteria
uses an object/method based means of constructing and executing a
request to retrieve objects.
<hibernateconfiguration>
<sessionfactory>
<property name=”hibernate.dialect”>
org.hibernate.dialect.MySQLDialect</property>
<property name=”hibernate.connection.driver_class”>
com.mysql.jdbc.Driver</property>
<property name=”hibernate.connection.url”>
jdbc:mysql://localhost/DBname</property>
<mapping resource=”guestbook.hbm.xml”/>
</sessionfactory>
124
</hibernateconfiguration>
Elements:
hibernate.dialect It represents the name of the SQL dialect for the
database
</class>
</hibernatemapping>
Elements:
<hibernatemapping> </hibernatemapping>
It is the base tag which is used to write hibernate mapping file, which is
used to map POJO class with database table.
<class> </class>
It represents name of the class and database table which we want to map
with each other. It has 2 parameters:
nameIt represents name of the class
125
tableIt represents name of the database table
<property> </property>
It is used to write the property which we want to map with database
column. It has 2 parameters:
nameIt represents name of the property
typeIt represents type of the property
<column> </column>
It is used to write the database column which we want to map with java
class property. It has 2 parameters:
nameIt represents name of the column
lengthIt represents maximum length of a column value
126
3. Right click on the project from the workspace → New → other →
(Select Hibernate category and Hibernate mapping files and POJOs
from Database file type ) → Next → Keep the default configuration
file name(hibernate.cfg) and Hibernate Reverse Engineering
File(hibernate.reveng) and type the package name(hibernate) → Finish
Guestbook.java
package hibernate;
public class Guestbook implements
java.io.Serializable { private Integer no;
private String
name; private
String msg;
private String
dt;
public Guestbook() {
}
public Integer
getNo() { return
this.no;
}
Guestbook.hbm.xml
<hibernate-mapping>
<class name="hibernate.Guestbook" table="guestbook" catalog="db">
<id name="no" type="java.lang.Integer">
<column name="no" />
<generator class="identity" />
</id>
try
{
ss.beginTransaction();
gbook=ss.createQuery("from
Guestbook").list();
}
catch(Exception e){ }
%>
<html>
<head>
<title>Guest View</title>
</head>
<body>
Guest View
Click here to go <a href="index.jsp"> BACK </a>
<br><br>
<%
Iterator
it=gbook.iterator();
while(it.hasNext())
{
Guestbook each=(Guestbook)it.next();
out.print(each.getDt()+" ");
out.print(each.getName()+"<br>");
out.print(each.getMsg()+"<br><hr>");
}
%
>
</body>
</html>
Output:
130
9
STRUTS
Unit Structure
9.1 Struts: Introduction
9.2 Strut’s framework core components
9.3 Installing and setting up struts
9.4 Getting started with struts.
The main Java based technologies that one commonly uses to develop
Web applications are Servlet and JavaServer Pages [JSP].
Both the technologies [Java Servlets and JSP] mix the application and the
business logic with the presentation layer and thus make maintenance
very difficult. This is not suitable for large enterprise applications. This
means there’s something still missing in these technologies which create
a gap.
FRAMEWORK
A framework helps automate all the tedious tasks of the domain and
provides an elegant architectural solution to the common workflow of the
domain.
It cuts time, out of the development process and makes developers more
productive by giving them prebuilt components to assemble Web
applications from.
Struts is not a technology, it’s a framework that can be used along with
Java based technologies.
132
The Struts framework is a strong implementation of the widely
recognized Model View Controller design pattern. The key focus of
MVC pattern is separation which is what is desired.
Struts
Struts [formerly located under the Apache Jakarta Project] was originally
developed by Craig McClanahan and donated to the Apache Foundation
in May, 2000. It was formerly known as Jakarta Struts. Struts is
maintained as a part of Apache Jakartaproject.
Struts comes with an Open-Source license which means it has no cost and
its users have free access to all its internal source code.
Today, the Apache Struts Project offers the two major versions of the
Struts framework:
133
Fig. 2
Filter Dispatcher
The controller is the first component that takes charge when
processing a request. In Struts 2 the Filter Dispatcher plays the
role of the Controller.
Actions
Action [the Action class] is heart and soul of the Struts 2
framework. It processes input and interacts with other layers of
the application.
It is associated with a HTTP request received from the user. Each HTTP
request [in form of a URL] is mapped to a specific Action. This Action
class holds the code spec that helps serve the user request.
Interceptors
Interceptors allow developing code spec that can be run before and/or after
the execution of an action.
A request usually processed as follows:
A user requests a resource that maps to an Action
The Struts 2 framework invokes the appropriate Action to serve the
request
134
If interceptors are written, available and configured, then:
Before the Action is executed, the invocation could be intercepted by
another object
After the Action executes, the invocation could be intercepted again
by another object
Why Interceptors?
Interceptors are one of the best aspects of the Struts 2 framework
Interceptors are mainly used to encapsulate common functionality in a
reusable form that can be applied to one or more Actions in the
application.
Developers can define code spec that can be executed before and/or after
the execution of an action. This thus Intercepting can be done:
Before the action
After the action
Value Stack/OGNL
Now that the Action and Interceptor components are covered, let’s move
on to the next component in the Struts 2 framework.
Value Stack
Value Stack is exactly what the name suggests a stack of objects.
The Value Stack is a storage area that holds all of the data associated with
the processing of a Request.
This continues until the last element in the stack is scanned. This is very
useful as the developer need not know where the attribute value currently
is. Is it available in:
The Action
The Model
The HTTP Request
135
The developer simply needs to know that such a value exists somewhere
and Struts 2 returns it!
OGNL supports:
Type conversion Calling methods
Collection manipulation Generation
Projection across collections Expression evaluation
Lambda expressions
In Struts 2, this task is split into the Result Type and the Result itself.
Results
Results and Result Types come into picture only after the processing of
the Action is complete.
Results define what happens next after the Action has been executed.
The method of the Action class that processes the Request returns a String
as the results. The value of the String is used to select a Result element.
This return value is mapped via the configuration file to an
implementation of the Result interface.
136
View Technologies
The most common way of rendering Results [View Technology] is
JavaServer Pages [JSP]. However, JSP is not the only view technology.
There are a few others that can replace JSP in a Struts 2 application:
Velocity Templates
Freemarker Templates
XSLT Transformations
Result Types
The response that the Result interface generates can vary between
different concrete class implementations which are nothing but Result
Types.
The Result Type provides the implementation details for the type of
information that is returned to the user.
137
<result name=”SUCCESS”>/welcome.jsp</result>
</action
>
</packa
ge>
</struts>
Elements:
<struts> .....................</struts>
It represents the base tag for struts.xml file. This file contains all of the
routing and configuration information for the Struts application.
<package> .....................</package>
It allows separation and modularization of the configuration. This is very
useful when you have a large project and project is divided into different
modules. It has 2 parameters:
<action>..................... </action>
It represents the action class. It has 2 parameters:
<result> .....................</result>
It represents the name of the result or a view. It has 1 parameter:
nameIt represent a result for which appropriate view will get displayed
138
III. Writing business login(Model)
A. Design Action bean
To add StructsActionForm bean, Right click on the project -> other -
> select(Struts and StrutsActionFormBean) ->next
Give the bean class name (bean1) -> select the package name from
the list ->Finish
Include the variables (username and email) into the action bean and
insert setter and gettermethod
B. Design Action
To add Action, Right click on the project -> other -> select(Struts
and StrutsAction) ->next
Give the class name (LoginAction) -> select the package from the
list -> type the action path as (/login) ->next
Select the action form bean(bean1) -> keep input resource blank ->
select the scope as request -> uncheck validate ActionForm Bean
checkbox ->Finish
Modify the execute()method.
A. Configuration File
Select the struts-config.xml file from the configuration files
Right click within the <action>tag
Select Struts ->Add forward
Select the forward name (success) and select the resource
file(success.jsp)
Repeat and Add all the forwards
B. Mapping file
Select the web.xml file from the configuration files
Click the page stag
Select the welcome files(login.jsp)
<html>
<head>
<title>Failure Page</title>
</head>
<body>
Wrong Email ID..
<br>Your entered details are
<br>Username
<bean:write name="bean1" property="username" />
<br>email
<bean:write name="bean1" property="email" />
</body>
</html>
Struts-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<struts-config>
<form-beans>
<form-bean name="bean1" type="com.myapp.struts.bean1"/>
140
</form-beans>
<global-exceptions>
</global-exceptions>
<global-forwards>
<forward name="welcome"path="/Welcome.do"/>
</global-forwards>
<action-mappings>
<action name="bean1" path="/login"
scope="request"
type="com.myapp.struts.loginaction1"
validate="false">
<forward name="login" path="/login.jsp"/>
<forward name="success" path="/success.jsp"/>
<forward name="failure" path="/failure.jsp"/>
</action>
<action path="/Welcome" forward="/welcomeStruts.jsp"/>
</action-mappings>
<controller
processorClass="org.apache.struts.tiles.TilesRequestProcessor"/>
<message-resources
parameter="com/myapp/struts/ApplicationResource"/>
</struts-config>
Bean1.java(form bean)
package com.myapp.struts;
141
import javax.servlet.http.HttpServletRequest;
import
org.apache.struts.action.ActionErro
rs; import
org.apache.struts.action.ActionMap
ping; import
org.apache.struts.action.ActionMes
sage;
public class bean1 extends org.apache.struts.action.ActionForm {
private String
username;
private String
email;
public String
getEmail() {
return email;
}
public void
setEmail(String email) {
this.email = email;
}
public String
getUsername() {
return username;
}
}
Loginaction1.java
package com.myapp.struts;
import
javax.servlet.http.HttpServletReque
st; import
javax.servlet.http.HttpServletRespo
nse; import
org.apache.struts.action.ActionFor
m; import
142
org.apache.struts.action.ActionFor
ward; import
org.apache.struts.action.ActionMap
ping;
public class loginaction1 extends
org.apache.struts.action.Action {
private static final String
SUCCESS = "success";
private static final String FAILURE = "FAILURE";
@Override
public ActionForward execute(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response)
throws Exception {
bean1
b1=(bean1)form;
String
m=b1.getEmail();
if (m == null || m.equals("") || m.indexOf("@")
== -1) { return
mapping.findForward(FAILURE);
}
else{
return mapping.findForward(SUCCESS);
}
}
}
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.co
m/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
143
<param-name>detail</param-name>
<param-value>2</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout> 30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<jsp-config>
<ta
glib
>
<taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-nested.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-nested.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-tiles.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
</ta
glib
>
</jsp-
config
>
</web-app>
144
Output:
*****
145
UNIT VI
10
WEBSERVICES, JAVAMAIL AND JNDI
Unit Structure
10.1 Objectives
10.2 Introduction
10.3 Webservices
10.3.1 SOAP
10.3.2 Building a web services using JAX-WS
10.4 Java Mail
104.1 Mail protocols
10.4.2 Components of the JavaMail API
10.4.3 Starting JavaMail API
10.5 JNDI
10.5.1 Naming Service and Directory Service
10.5.2 JNDI and Resources of JNDI
10.6 Summary
References
Questions
10.1 OBJECTIVES
10.2 INTRODUCTION
148
3. The Javamail API provides protocol-independent and platform-
independent framework for sending and receiving mails.
4. A fundamental element in every application is the capability to find
and locate components and services.
5. The component name correspond to the actual name, typically much
more difficult to remember and manage. A well-known naming service
is provided on Internet by DNS.
10.3.1 SOAP:
1. There are three major web service components
1. SOAP
2.WSDL
3.UDDI
10.1 SOAP:
1. SOAP is an acronym for simple object Access protocol.
2. It is a XML-based protocol for accessing web services.
3. It is a W3C recommendation for communication between
applications.
4. It is XML based, so it is platform independent and language
independent. In other words, it can be used with java, .NET or PHP
language or any platform.
149
2. The below diagram of SOAP architecture shows the various blocks of
a SOAP message
3. The SOAP message is nothing but a mere XML document which has
the below components.
4. An Envelope element that identifies the XML document as a SOAP
message-This is the containing part of the SOAP message and is used
to encapsulate all the details in the SOAP message. This is the root
element in the SOAP message.
5. A Header element that contains header information-The header
element can contain information such as authentication credentials
which can be used by the calling application.
6. A Simple SOAP service example of a complex type is shown below
6.1 A body element that contains call and response information- This
element is what contains the actual data which needs to be sent between
the web service and the calling application.
<soap:Body>
<GetTutorialInfo>
<TutorialName>Web Services</TutorialName>
150
<TutorialDescription>All about web
services</TutorialDescription>
</GetTutorialInfo>
</soap:Body>
2.1 The client would format the information regarding the procedure call
and any arguments into a SOAP message and sends it to the server as part
of an HTTP request. This process of encapsulating the data into a SOAP
message was known as Marshalling.
2.2 The server would then unwrap the message sent by the client, see what
the client requested for and then send the appropriate response back to the
client as a SOAP message. The practice of unwrapping a request sent by
the client is known as Demarshalling.
152
2. Document Style
1.7 Document style web service can be validated against predefined
schema
1.8 In document style, SOAP message is sent as a single document.
1.9 Document style message is loosely coupled
1.10 In document style, SOAP message loose the operation name.
1.11 In document style, parameters are sent in XML format.
The first 3 files are created for server side and 1 application for client side
JAX-WS Server code
File Helloworld.java
1. package com.javatpoint;
2. import javax.jws.WebMethod;
3. import javax.jws.WebService;
4. import javax.jws.soap.SOAPBinding;
5. import javax.jws.soap.SOAPBinding.Style;
6. //Service Endpoint Interface
7. @WebService
8. @SOAPBinding(style = Style.RPC)
9. public interface HelloWorld{
10. @WebMethod String getHelloWorldAsString(String name);
11. }
File HelloWorldImpl.java
1. package com.javatpoint;
2. import javax.jws.WebService;
3. //Service Implementation
4. @WebService(endpointInterface = "com.javatpoint.HelloWorld")
5. public class HelloWorldImpl implements HelloWorld{
6. @Override
153
7. public String getHelloWorldAsString(String name) {
8. return "Hello World JAX-WS " + name;
9. }
10. }
File Publisher.java
1. package com.javatpoint;
2. import javax.xml.ws.Endpoint;
3. //Endpoint publisher
4. public class HelloWorldPublisher{
5. public static void main(String[] args) {
6. Endpoint.publish("http://localhost:7779/ws/hello", new Hello
WorldImpl());
7. }
8. }
After running the publisher code, we can see the generated WSDL file by
visiting the URL
http://localhost:7779/ws/hello?wsdl
JAX-WS Client Code
File HelloWorldClient.java
package com.javatpoint;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
public class HelloWorldClient{
public static void main(String[] args) throws Exception {
URL url = new URL("http://localhost:7779/ws/hello?wsdl");
//1st argument service URI, refer to wsdl document above
//2nd argument is service name, refer to wsdl document above
QName qname = new QName("http://javatpoint.com/", "HelloWorldI
mplService");
Service service = Service.create(url, qname);
HelloWorld hello = service.getPort(HelloWorld.class);
System.out.println(hello.getHelloWorldAsString("javatpoint rpc"));
}
}
154
Output
HelloWorld JAX-WS Javatpoint rpc
2 POP:
1. POP is an acronym for Post Office Protocol, also known as POP3. It
provides a mechanism to receive the email.
2. It provides support for single mail box for each user. We can use
Apache James server, cmail server etc. as an POP server.
3. But if we purchase the host space, an POP server is by default
provided by the host provider. For example, the pop server provided
by the host provider for my site is mail.javatpoint.com. This protocol
is defined in RFC 1939.
3. IMAP
1 IMAP is an acronym for Internet Message Access Protocol. IMAP is
an advanced protocol for receiving messages.
2 It provides support for multiple mail box for each user, in addition to,
mailbox can be shared by multiple users. It is defined in RFC 2060.
155
4. MIME:
1 Multiple Internet Mail Extension (MIME) tells the browser what is
being sent e.g. attachment, format of the messages etc. It is not known
as mail transfer protocol but it is used by your mail program.
1 Get the Session object- That stores all the information of host like host
name, username, password etc. The javax.mail.Session class provides two
methods to get the object of session, Session.getDefaultInstance() method
and Session.getInstance() method. We can use any method to get the
session object
157
2. Compose the message- The javax.mail.Message class provides
methods to compose the message. But it is an abstract class so its subclass
javax.mail.internet.MimeMessage class is mostly used.
For sending the email using JavaMail API, you need to load two jar files
Mail.jar and activation.jar
158
1. import java.util.*;
2. import javax.mail.*;
3. import javax.mail.internet.*;
4. import javax.activation.*;
5.
6. public class SendEmail
7. {
8. public static void main(String [] args){
9. String to = "sonoojaiswal1988@gmail.com";//change accordi
gly
10. String from = "sonoojaiswal1987@gmail.com";change accordi
ngly
11. String host = "localhost";//or IP address
12.
13. //Get the session object
14. Properties properties = System.getProperties();
15. properties.setProperty("mail.smtp.host", host);
16. Session session = Session.getDefaultInstance(properties);
17.
18. //compose the message
19. try{
20. MimeMessage message = new MimeMessage(session);
21. message.setFrom(new InternetAddress(from));
22. message.addRecipient(Message.RecipientType.TO,new Inte
netAddress(to));
23. message.setSubject("Ping");
24. message.setText("Hello, this is example of sending email ");
25.
26. // Send message
27. Transport.send(message);
28. System.out.println("message sent successfully....");
29.
30. }catch (MessagingException mex) {mex.printStackTrace();}
31. }
32. }
To run above code we need to load two jar files. There are 4 ways
to load the jar file. One of the way is set classpath. Let’s see how to run
this example
159
Load the Jar file set classpath=mail.jar;activation.jar;.;
Compile the source javac SendEmail.java
file
Run by java SendEmail
5. JNDI:
1. The java Naming and Directory Interface(JNDI) is an application
programming interface(API) that provides naming and directory
functionality to applications written using the Java programming
language.
2. It is defined to be independent of any specific directory service
implementation. Thus a variety of directories- new, emerging and
already deployed can be accessed in a common way.
3. Architecture
160
3 A naming service is an application that contains a set of objects, or
references to objects,
with corresponding names, Such correspondances are called bindings.
161
need user-specified factory class elements, JNDI name attributes, etc.
In this section, we will discuss how to configure JNDI connection
factory resources, for J2EE resources, and how to access these
resources.
5.2 Within Application Server, you can create, delete and list resources as
well as list-jndi-enttites.
5.3 Creating Custom Resources
1. In the left pane of the Admin Console, open the Sun Java System
Application Server instance for the JNDI configuration to be
modified.
2. Open the JNDI tab and click Custom Resources. If any custom
resources have been created already, they are listed in the right
pane. To create a new custom resource, click New. Open the JNDI
tab and click New. A page for adding a new custom resource
appears.
3. In the JNDI Name field, enter the name to use to access the resource.
This name will be registered in the JNDI naming service.
4. In the Resource Type field, enter a fully qualified type definition, as
shown in the example above. The Resource Type definition follows
the format, xxx.xxx.
5. In the Factory Class field, enter a factory class name for the custom
resource to be created. The Factory Class is the user-specified name
for the factory class. This class implements the
javax.naming.spi.ObjectFactory interface.
6. In the Description field, enter a description for the resource to be
creating. This description is a string value and can include a maximum
of 250 characters.
7. Mark the Custom Resource Enabled checkbox, to enable the custom
resource.
8. Click OK to save your custom resource.
163
4. Mark the External Resource Enabled checkbox, to enable the external
resource.
5. Click Save to save the changes to the external resource.
SUMMARY
REFERENCES
QUESTIONS
*****
164