Adv Java
Adv Java
1. Introduction
2. Architecture of an Enterprise Application
3. JDBC
4. JDBC Architecture
5. Database Connectivity steps
6. Database Connectivity using jdbc-odbc
7. Program, Advantages and Disadvantages of Type 1
Driver(Bridge Driver)
8. Submitting SQL statements to the database
9. Program to insert record into the database
10. Type 4 Driver
11. Program and Advantages of Type 4 Driver
12. Driver Manager, Connection and Statement objects
13. Program on database connectivity using File (Generic) concept
14. Steps in retrieving data from database
15. ResultSet object
16. Differences between Statement and PreparedStatement object
17. Steps to implement PreparedStatement
18. Architecture of Web Application
19. Limitations of a Web Server
20. Types of internet programs
21. Servlets
22. Pre requisites for a servlet execution
23. Difference between Web Container and Web Server
24. Servlet Development
25. Servlet Life Cycle (Protocol Independent)
26. Web Application Development Steps
27. Web Application Deployment Steps
28. Different names and functions of a Servlet
29. Program on Servlets
30. Background Process after submitting the form
31. Initialization Parameters
32. Program on Initialization Parameters
33. ResultSetMetaData interface
34. Stored Procedure
35. Program on Callable Statement
36. Generic Servlet in depth
37. ServletContext
38. Program on ServletContext
39. HttpServlet Basics
40. Difference between GET and POST
41. Life Cycle of HttpServlet
42. Program on HttpServlet implementation
43. Servlet Collaboration
44. RequestDispatcher, Forward and Include
45. Program on RequestDispatcher
46. Filters
47. Development and Deployment of Filters
48. Program on Filters
49. Filters in depth
50. JSP Introduction
51. Life Cycle of JSP
52. JSP constituents
53. implicit objects
54. Programs on Jsp
55. Java Beans
56. Using Java Beans in Jsp
57. Program on Java Beans
58. Various scopes of Java Beans in Jsp
59. Jsp architecture
60. MVC architecture
61. Program on MVC architecture
62. Difference between include directive and include standard
action
63. Program on Jsp include directive and include standard action
64. Session Tracking
65. Cookies
66. Program on cookies mechanism
67. HttpSession
68. URL rewriting
69. Difference between Standard action and Custom action
70. Custom tag development
71. Steps to develop Custom tag
72. Custom tag in depth
73. Program on Custom tag
74. Life Cycle and Flow Chart of Custom tag
75. Types of ResultSet
76. Batch Updates
77. Type 2 and Type 3 Drivers
78. Java Server pages Standard Template Library (JSTL)
79. Programs on JSTL
Topics:
JDBC
Servlets
JSP
Beans
Expression Language
JSTL
Introduction:
JAVA:-
Usage:-
Enterprise Application:-
Client tier.(Browser)
Presentation tier.(Web-Server)
Business tier.((Rules)
Data tier.(Data)
Data tier
Client tier: - In an Enterprise Application, the client tier is mostly the
browser.
End-user of the application interacts with the entire Enterprise Application
using this tier.
Technology used: - HTML, Java Script.
Presentation tier: - This acts as an interface between client tier and the
business tier.
Major responsibilities are as follows:-
Business tier: - This tier of the Enterprise application holds the core
business rules implementation. This tier receives request from the
Presentation tier for Business Logic Execution.
Major technology used is EJB.
JDBC Architecture
1) Java Client
2) JDBC API
3) Driver
4) Driver Manager/ Data Source
5) Database Server
JDBC Architecture
JDBC API
DriverManager/Data Source
Driver
Database Server
DriverManager
Connectivity Approaches
DataSource
“sun.jdbc.odbc.JdbcOdbcDriver”
Once we are done with database operations we have to close this connection
by calling close () on Connection.
/* Program to connect to the Oracle database server using Type 1 driver
(Bridge Driver) */
import java.sql.*;
class HybridConnectivity
{
public static void main (String args []) throws Exception
{
//Step 1:- Loading the Driver
Class.forName (“sun.jdbc.odbc.JdbcOdbcDriver”);
System.out.println (“Driver is loaded, instantiated and registered with the
DriverManager”);
String URL=”jdbc:odbc:student”;
Con.close ();
System.out.println (“Connection closed”);
}
}
JDBC
method
calls
-- Bridge
` -- Driver
--
-- Database
-- ODBC SQL Engine
-- function
-- calls
-- Vendor
-- dependent
-- ODBC
-- Driver
Database Server calls
Client Java Database Server
Application
Class.forName(“Driver class”);
DriverManager.getConnection (“jdbc: odbc: DSNName”);
Note: Almost all we never submit DDL Statements from the Java
Program to the Database Server.
Statement Interface
PreparedStatement Sub-Interface
CallableStatement Sub-Interface
con.close ();
import java.sql.*;
JDBC
method
calls
-- Pure Driver
--
--
--
-- SQL Db engine
--
--
--
--
--
--
Steps
JDBC driver are manufactured by the database vendors but not sun.
Performance is more.
Can by used in Internet and Intranet Application.
import java.sql.*;
class JdbcConnectivity
{
public static void main (String [] args) throws Exception
{
// Loading Driver
Class.forName (“oracle.jdbc.driver.OracleDriver”);
System.out.println (“Driver is created, instantiated and registered with
DriverManager”);
st.close ();
con.close ();
}
}
Note:
We should specify to the JVM where from this class has to be loaded.
Otherwise ClassNotFoundException rises.
Classpath:-
D:\oracle\ora8i\jdbc\lib\classes111.zip (or)
D:\oracle\ora8i\jdbc\lib\classes12.zip
Search for the following file in our system to prepare for the
connection URL for oracle thin driver:
D:\oracle\ora8i\network\admin\tsnnames.ora
This method can load any java class into memory dynamically. It
cannot create the object of that class and cannot register the object to
anybody.
To release the network resources those are consumed by the client to have
the Socket connection with Database Server.
//Program to perform delete and update operations from the java program:
Import java.sql.*;
Class UpdateOperation
{
Public static void main(String args[]) throws Exception
{
Class.forName(“oracle.jdbc.driver.OracleDriver”);
Connection
con=DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:Serv
er”, “scott”, “tiger”);
Statement st=con.createStatement();
int rows;
}
}
File Concept
Java.util.properties object
import java.sql.*;
import java.util.*;
import java.io.*;
class GenericConnectivity
{
public static void main (String [] args) throws Exception
{
Properties p=new Properties ();
FileInputStream fis=new FileInputStream (“dbprops.txt”);
p.load (fis);
String driver=p.getProperty (“d”);
String url= p.getProperty (“cu);
String user= p.getProperty (“u”);
String pwd= p.getProperty (“p”);
Class.forName (driver);
Connection con=DriverManager.getConnection (url, user, pwd);
System.out.println (“Connected”);
con.close ();
}
}
Dbprops.txt file:
D=oracle.jdbc.driver.OracleDriver
Cu=jdbc:oracle:thin:@localhost:1521:Server
U=”Scott”
P=”tiger”
Get Connection
Close Resultset
More
YES NO
Rows
Close Statement
Close Connection
Java.sql.Statement interface has one important method that is used to submit
SELECT statements.
What is ResultSet?
It is an interface.
An object of some class that implements ResultSet interface is created by the
Driver and its reference is returned to java program.
RS
Records
No Record Place
It is the responsibility of the Programmer to move the cursor to the record
existing location of the ResultSet.
import java.sql.*;
class RetrieveData
{
public static void main (String [] args) throws Exception
{
Class.forName (“oracle.jdbc.driver.OracleDriver”);
Connection con=DriverManager.getConnection
(“jdbc:oracle:thin:@localhost:1521:Serverid”, “Scott”, “tiger”);
System.out.println (“Connected”);
Statement st=con.createStetment ();
ResultSet rs=st.executeQuery (“Select * from student where rollno=844”);
If (rs.next ())
{
int r=rs.getInt (1);
String n=rs.getString (2);
int m=rs.getInt (3);
System.out.println(r+ ““+n + ““+m);
else
System.out.println (“Not found”);
rs.close ();
st.close ();
con.close ();
}
}
}
Retrieving all the records from the student table:
Note: for the getXXX () methods of the ResultSet, we have to supply the
column numbers based on the records of ResultSet object but not based on
database table columns.
Note: ‘In’ parameters are those parameters whose values are not supplied at
query compilation time but supplied at execution time. At the time of
compilation instead of values, place holders (?) are kept.
Steps to implement PreparedStatement:
Class.forName ()
DriverManager.getConnection ()
ps.close ();
con.close ();
Web Application Development:
Technologies:
Once we can develop a Web Application, we are Java Professionals and our
main role will be Web-Component Developers.
Web-Application:
Architecture of Web:
Related
Http HTML
request Program <Html>
fetching from -
Hard Disk -
-
Http -
response & sending to -
Client -
Program -
<Html>
Web Client:
It is Software.
The main functionality of the Server:
Note:
Browser is a Web Page Requesting Program and Web Server is web page
fetching.
Web Page:
It is an html document.
2. Dynamic Web Pages are not pre-existing html documents i.e., these
web pages are programs and on the fly created whenever the request
comes from the Client. A Servlet or a JSP creates the Dynamic Web
Content Programmatically. They are known as Dynamic because their
content changes with end user interaction.
Limitations of a Web Server:
A web server provides http connection to the web clients. Its basic
limitations are that it can fetch web pages to the clients. If they are present in
the system of the server machine i.e., pre existing web pages. It cannot
handle complex Client requests that involves end users input with this
limitation following scenarios can’t be handled by the Web Server.
User Authentication
Online Bill Payments
Online Reservations
Online Banking
Web Server should be able to handle any kind of http request. Whenever the
request involves end user’s input on its own it cannot process that request.
CGI-Perl
Asp
Servlets
JSP etc.
A) We need
Servlet API
Web Container that provides execution environment for Servlets
Classpath: After loading the Tomcat Server, set the classpath to the
following jar file
C:\Apache\tomcat\common\lib\servlet-api.jar
Q) What is a Web Container? What is the difference between Web
Container and Web Server?
A) It is a Server Software, i.e., Web Server along with Servlet engine and
JSP engine.
Request
S
E
R
V
L
Response E
T
Web Container
Database
Server
Servlet Development
javax.servlet.*
javax.servlet.http
Protocol independent
Protocol dependent
Indirectly means that calling this interface in our servlet which is already
implemented or extended in other classes or interfaces.
Ex: GenericServlet implements Servlet interface.
Servlet
GenericServlet
Our Servlet
In Direct we have problem
1. Instantiation
2. Initialization
3. Service
4. Destruction
Our Servlet life cycle
More
YES Requests?
Servlet is
Running
NO
Servlet is Is Servlet
NO Undeploye
Running
d?
Destruction
Phase
YES
c.newInstance ()
Instance of ordinary class are called as objects but servlet, ejb, Java
Bean’s instances are not called as objects, but they are called
Components.
Class A
{
A ()
{
System.out.println (“Instance of class A created”);
}
}
Public class B
{
Public static void main (String args []) throws Exception {
Class c=Class.forName (“A”);
c.newInstance ();
}
}
2. Initialization Phase:
When Container creates the instance of the Servlet, that Servlet instance
does not possess any Servletness. It cannot process any Client Request
because it does not have any idea about the Server environment. It is the
responsibility of the Container to provide such information to the Servlet
and fetch Servletness to the instance.
3. Servicing Phase:
Servlet engine receives the request from http service that includes Client info
and the data sent by the Client. Based on this information, Servlet engine
creates two Proprietary objects that implement ServletRequest and
ServletResponse interfaces respectively.
Container calls service method as the Servlet instance by supplying these
two objects as arguments.
4. Destruction Phase:
import javax.servlet.*;
import java.io.*;
Html document
Image files
Servlets
Jsps
Other helper classes
Xml document(s)
Step 1:
*.html
JSPs
Image files
Servlet class files
WEB-INF
lib *.jar
web.xml
The root directory acts as Web Application’s root context. It has 2 parts.
I. Public Area: Directly under the root directory all the web resources
that can be accessed from the client are placed.
a. Htmls
b. JSPs
c. Image files
II. Private Area: Directly under the root directory we should create a
directory by the name WEB-INF whose contents are exclusively
meant for the container access. These files cannot be accessed from
the client.
Step 2:
Step 3:
Step 1:
Create the war file. War file is a special kind of jar file. According to
specification, every Web Application has to be packaged into a war file.
Step 2:
Step 3:
http://localhost:8080/manager/html
Upon that request, we get a web page (Tomcat Web Application Manager)
Step 4:
In the Tomcat Web Application Manager tool, we have to select the war file
to deploy. Specify the location of the war file and click on the deploy button.
Q) What are the functions of a servlet in general?
3. Generate the dynamic content and drive the output to the client
Step 1:
GreetingApp
Greet.html
WEB-INF
classes
nit
servlets
GreetingServlet.class
web.xml
Step 2:
Greet.html
<html>
<body bgcolor=cyan>
<form action=”. /gotit”>
Name :< input type=”text” name=”t1”><br>
<input type=”submit”>
</form>
</body>
</html>
GreetingServlet.java
Package nit.servlets;
Import javax.servlet.*;
}//service()
}//GreetingServlet
Compilation
>javac –d . GreetingServlet.class
Step 3:
Web.xml
<web-app>
<servlet>
<servlet-name>Greet</servlet-name>
<servlet-class>nit.servlets.GreetingServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Greet</servlet-name>
<url-pattern>/gotit</url-pattern>
</servlet-mapping>
</web-app>
Root Directory
A) As the part of html form, the action attribute value specifies the address
of the web component, to which the form request has to be submitted. In the
above example
Dot indicates the current Web Application from which this web-page is
retrieved i.e.
http://localhost:8080/greetingapp
The other part indicates the public name of the servlet. This name is
specified as <url-pattern>/gotit</url-pattern> in the web.xml. Therefore we
used that name in the action attribute.
Url-pattern gives public name to the servlet. This is mapped to alias name.
Q) How does the response generated by the servlet reach the Client?
A) Never ever, servlet directly sends the output to the Browser. The dynamic
content generated in the servlet i.e., given to the web server via servlet
engine. Web-server sends that dynamic content to the Browser.
Q) What is the significance of ServletRequest and ServletResponse
objects in the Client request processing by the Servlet?
A) Servlet captures the incoming client data and Http header information
through request object.
Servlet is writing response header between the server and the request
sending browser. Stream object is created by using the response object only.
Initialization parameters:
Name, value pair of strings supplied to the servlet from the descriptor
(web.xml) is called as initialization parameters.
<init-param>
<param-name>name</param-name>
<param-value>value</param-value>
</init-param>
String getInitParameter (String name) - this method takes the init param
name and returns the corresponding value.
<servlet>
<servlet-name></servlet-name>
<servlet-class></servlet-class>
<init-param>
<param-name>name</param-name>
<param-value>value</param-value>
</init-param>
</servlet>
A) InitparamApp
emp.html
WEB-INF
classes
DatabaseServlet.class
lib
Classes12.jar
web.xml
http://localhost:8080/InitParamApp/emp.html
emp.html
<html>
<body>
<form action=”. /dbs”>
Id : <input type=text name=txtId><br>
Name: <input type=text name=txtName><br>
Salary<input type=text name=txtSalary><br>
<input type=”submit”>
<form>
</body>
</html>
web.xml
<web-app>
<servlet>
<servlet-name>init</servlet-name>
<servlet-class>Database Servlet</servlet-class>
<init-param>
<param-name>d</param-name>
<param-value>oracle.jdbc.driver.OracleDriver</param-value>
</init-param>
<init-param>
<param-name>url</param-name>
<param-value>jdbc:oracle:thin:@localhost:1521:server</param-value>
</init-param>
<init-param>
<param-name>user</param-name>
<param-value>scott</param-value>
</init-param>
<init-param>
<param-name>pwd</param-name>
<param-value>tiger</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>init</servlet-name>
<url-pattern>/dbs</url-pattern>
</servlet-mapping>
</web-app>
DatabaseServlet.java
import javax.servlet.*;
import java.io.*;
import java.sql.*;
}
catch (Exception e)
{
}
}
public void service (ServletRequest req, ServletResponse res) throws
ServletException, IOException {
try
{
res.setContentType ("text/html");
PrintWriter pw=res.getWriter();
pw.println ("<html>");
pw.println ("<body bgcolor=wheat>");
pw.println ("<center>");
Statement st=con.createStatement ();
ResultSet rs=st.executeQuery ("select * from emp where
ename="+req.getParameter ("empno"));
ResultSetMetaData metadata=rs.getMetaData ();
int count=metadata.getColumnCount ();
if (rs.next ())
{
pw.println ("<h2>EMPLOYEE DETAILS</h2>");
pw.println ("<table border=1 cellpadding=3 cellspacing=0>");
pw.println ("<tr>");
for (int i=1;i<=count;i++)
pw.println ("<th align=right width=100>"+metadata.getColumnName (i)
+"</th>");
pw.println("</tr>");
pw.println ("<tr>");
for (int i=1; i<count; i++)
pw.println ("<td align=right width=100>"+rs.getString (i)+"</td>");
pw.println ("</tr>");
pw.println ("</table>");
}
else
pw.println ("<h3>Employee record not found</h3>");
pw.println ("</center>");
pw.println ("</body>");
pw.println ("</html>");
pw.close ();
}//try
catch (Exception e)
{
System.out.println ("Some Exception");
System.out.println (e);
}
}//service ()
Java.sql.ResultSetMetaData interface:
Stored Procedure:
import java.sql.*;
class StoredProcedure
{
public static void main (String args[])
{
Connection con=null;
try
{
Class.forName ("oracle.jdbc.driver.OracleDriver");
System.out.println ("Driver Loaded. ...”);
String url="jdbc:oracle:thin:@90.0.0.4:1521:oracle";
con=DriverManager.getConnection (url,"scott","tiger");
System.out.println ("Connection Established.......");
CallableStatement cst=con.prepareCall ("{call proc2 (?,?)}");
cst.registerOutParameter (2, Types.VARCHAR);
cst.setInt (1, 1001);
cst.execute ();
String str=cst.getString (2);
System.out.println ("Employee Name:"+str);
cst.close ();
}
catch (ClassNotFoundException cfe)
{
System.out.println ("Driver class not found");
System.out.println (cfe);
}
catch (SQLException e)
{
System.out.println ("SQL"+e);
}
finally
{
try
{
if (con!=null)
{
con.close ();
}
}//try
catch (SQLException e)
{
System.out.println ("SQL final"+e);
}
}//finally
}//main ()
}//end of class
import java.sql.*;
class StoredProcedureSample
{
public static void main (String args [])
{
try
{
int accno=Integer.parseInt (args[0]);
Class.forName ("oracle.jdbc.driver.OracleDriver");
System.out.println ("Driver Loaded....");
Connection con=DriverManager.getConnection
("jdbc:oracle:thin:@90.0.0.4:1521:oracle","scott","tiger");
System.out.println ("Connection Established.....");
CallableStatement cst=con.prepareCall ("{call addinterest(?,?}");
System.out.println ("Callable Statement created....");
cst.registerOutParameter (2, Types.FLOAT);
cst.setInt (1, accno);
cst.execute ();
System.out.println ("Stored procedure executed....");
System.out.println ("New Balance of A/c "+ accno+"is:
Rs."+cst.getFloat (2));
cst.close ();
con.close ();
}
catch (ArrayIndexOutOfBoundsException aie)
{
System.out.println ("Supply Account number please");
System.out.println ("USAGE: java StoredProcedureSample 1001");
}
catch (Exception e)
{
System.out.println (e);
}
}//main ()
}//class
java.io.Serializable
java.servlet.Servlet
javax.servlet.ServletConfig
i.e., whatever methods ServletConfig object possess all those methods can
directly be called on the Servlet interface.
Serializable Servlet ServletConfig
GenericServlet
Our Servlet
A)
a) Compile time error
b) No error at compilation
c) Runtime error
d) No runtime error
A servlet can view the Web Application and its contents via ServletContext
object. Servlet can communicate with the Container via ServletContext
object. ServletContext objects is only one per Web Application, where as
ServletConfig object is one per Servlet.
I. String getServerInfo ()
II. Log (String information)
III. RequestDisaptcher getRequestDispatcher (String path)
Q) Web Application on ServletContext?
A)
ServletContextApp
Data.html
WEB-INF
Web.xml
Classes
StorageServlet.class
RetrieveServlet.class
http://localhost:8080/ServletContextApp/data.html
//data.html
<html>
<body bgcolor=pink>
<center>
<h1>PERSONAL DETAILS</h1>
<form action=”./store”>
EMAIL ID<input type=text name= “email”><br>
PHONE<input type=text name=”phone”><br><br>
<input type=submit value=SUBMITDETAILS>
</form>
</center>
</body>
</html>
//web.xml
<web-app>
<context-param>
<param-name>admin</param-name>
<param-value>[email protected]</param-value>
</context-param>
<servlet>
<servlet-name>storage</servlet-name>
<servlet-class>StorageServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>retrieval</servlet-name>
<servlet-class>RetrieveServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>storage</servlet-name>
<url-pattern>/store</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>retrieval</servlet-name>
<url-pattern>/retrieve</url-pattern>
</servlet-mapping>
</web-app>
//StorageServlet.java
import javax.servlet.*;
import java.io.*;
public class StorageServlet extends GenericServlet
{
public void service (ServletRequest request, ServletResponse response)
throws IOException, ServletException
{
String email=request.getParameter ("email");
String phone=request.getParameter ("phone");
response.setContentType ("text/html"):
PrintWriter pw=response.getWriter ();
ServletContext sc=getServletContext ();
sc.setAttribute ("mail”, email);
sc.setAttribute ("telephone”, phone);
String adminmail=sc.getInitParameter ("admin");
pw.println ("<html>");
pw.println ("<body bgcolor=wheat>");
pw.println ("<h3>Web site admin available at "+adminmail+"</h3>");
pw.println ("<h2><a href=./retrieve>GET YOUR DETAILS HERE</h2>
pw.println ("</body>");
pw.println ("</html>");
pw.close ();
}
}
//RetrieveServlet.java
import javax.servlet.*;
import java.io.*;
public class RetrieveServlet extends GenericServlet
{
public void service (ServletRequest request, ServletResponse response)
throws
IOException, ServletException
{
response.setContentType ("text/html"):
PrintWriter pw=response.getWriter ();
ServletContext sc=getServletContext();
String mail=(String)sc.getAttribute("mail");
String phone=(String)sc.getAttribute("telephone");
String adminmail=sc.getInitParameter ("admin");
pw.println ("<html>");
pw.println ("<body bgcolor=cyan>");
pw.println ("<h2>YOUR PERSONAL DETAILS</h2>");
pw.println ("<h3>EMAIL ID:"+mail+"</h3>");
pw.println ("<h3>TELEPHONE#:"+phone+"</h3>");
pw.println ("<h3>Web site admin available at "+adminmail+"</h3>");
pw.println ("</body>");
pw.println ("</html>");
pw.close ();
}
}
HttpServlet Basics:
Web Client and Web Server communicate with each other by using protocol.
Therefore they are known as Http Client and Http Server respectively.
HttpRequest
HttpResponse
Depending upon the way the request is made by the Client to the Server, the
request is famously categorized into 2 areas known as HttpRequest methods.
GET
POST
It is default method
We need to explicitly specify it
This request can be made either
by typing the url directly or by Only with html form this
clicking on hyperlink or through request is possible.
a form
Primary purpose of this method It is basically meant for posting data
is to get data from the server. into the server for updations.
Therefore it should not be used for
data updations.
Request headers have no body. Any It has body. Data is not appended to
data should be associated to request the url
line in the form of query string
Sensitive information like password We can send
and credit card information should
not e sent through this method.
Amount of data transfer from client No limitations
to server is limited.
It is idempotent(no side effects) It is not idempotent(side effects can
raise as we update the database)
Side Effects:
If due to network delay, we are typing/clicking the same button again and
again then the data can have effect repetitively
Q) How to write (create) a form that makes get request/ post request?
A) <form action= “ “ method = “post”
If we don’t specify the method attribute in the html form tag, by default it is
get request method only.
Servlet
GenericServlet
HttpServlet
Our Servlet
Life cycle of HttpServlet
HttpServlet provides http specific behoviour to our own servlet. That is the
reason why our servlet can provide complete support for the Web
Server(HttpServer)
When we are discussing HttpServlet life cycle means we are discussing our
own servlet that extends HttpServlet.
HttpServlet Life Cycle:
If
More administrator
request undeploys
? Servlet
In the public service method a call is made for the protected service ()
method.
Converting ServletRequest and ServletResponse to HttpServletRequest and
HttpServletResponse
Calls its own protected service(httpServletRequest req,HttpServletResponse
res) methods belongs to HttpServlet class only.
HttpServlet class has given following default implementation for the
protected service method:
Protected void service(HttpServletRequest req,HttpServletresponse res)
throws ServletException,IOException
{
String requestmethod=req.getmethod()
If(requestmethod.equals(“GET”))
doGet(req,res);
If(requestmethod.equals(“POST”);
doPost(req,res);
}
Depending upon the incoming http request method from the Browser, either
doGet() or doPost() method is called.
The following is the default implementation for these methods given by the
HttpServlet
Protected void doGet(HttpServletRequest request,HttpServletResponse
response) throws ServletException,IOException
{
PrintWriter pw=response.getWriter();
Pw.println(“GET REQUEST ISW NOT SUPPORTED”);
Pw.close();
}
Protected void doPost(HttpServletRequest request,HttpServletResponse
response) throws ServletException,IOException
{
PrintWriter pw=response.getWriter();
Pw.println(“POST REQUEST ISW NOT SUPPORTED”);
Pw.close();
}
Init()
Init(ServletConfig config)
Public void service(ServletRequest req,ServletResponse res)
Protected void service(HttpServletRequest req,HttpServletResponse res)
Calls 2 more service methods-doGet() and dpPost() depending on the
evaluating the request object call doGet/doPost
getInitparameters
getServletNames
getServlet
LoginApp
login.html
WEB-INF
web.xml
classes
LoginServlet.class
http://localhost:8080/LoginApp/login.html
login.html
<html>
<body bgcolor="pink">
<center><h2>LOGIN TO WEB APPLICATION</h2>
<form action=". /login" method="post">
USER NAME : <input type="text" name ="user"><br>
PASSWORD : <input type="password" name="pwd"><br><br>
<input type="submit" value="CLICK HERE">
</form>
</center>
</body>
</html>
web.xml
<web-app>
<servlet>
<servlet-name>authenticate</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>authenticate</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
LoginServlet.java
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class LoginServlet extends HttpServlet
{
public void doPost (HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
String user=request.getParameter ("user");
String pwd=request.getParameter ("pwd");
response.setContentType ("text/html");
PrintWriter pw=response.getWriter ();
if (user. equals (pwd))
{
pw.println ("<html>");
pw.println ("<body bgcolor=cyan>");
pw.println ("<h2>Welcome to our Shopping Mall</h2>");
pw.println ("</body>");
pw.println ("</html>");
}
else
{
pw.println ("<html>");
pw.println ("<body bgcolor=pink>");
pw.println ("<h3>Invalid user name</h3>");
pw.println ("<a href=login.html>TRY AGAIN</a>");
pw.println ("</body>");
pw.println ("</html>");
}
pw.close ();
}
}
Web Application on RequestDispatch
Directory Structure
RequestDispatch
emp.html
caption.html (to use it in second servlet)
WEB-INF
web.xml
classes
GrossServlet.java
NetServlet.java
http://localhost:8080/RequestDispatch/emp.html
emp.html
<html>
<body bgcolor=”wheat”>
<center>
<form action=”. /gross”>
Employee Basic <Input type=text name=”basic”> <br>
<input type=”submit”>
</form>
</center>
</body>
</html>
caption.html
<html>
<body bgcolor=”cyan”>
<marquee>
<font size=6 color=green>
Welcome to HR systems
</font>
</marquee>
</body>
</html>
GrossServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
IOException, ServletException {
String b= request.getParameter("basic");
float basic = Float.parseFloat(b);
float da=0.5f*basic;
float hra=0.4f*basic;
float gross = basic+hra+da;
Float f= new Float (gross);
request.setAttribute("gross", f);
ServletContext sc=getServletContext();
RequestDispatcher rd=sc.getRequestDispatcher("/net");
rd.forward(request, response);
}
}
NetServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
IOException, ServletException {
Float gross=(Float) request.getAttribute("gross");
float net = gross.floatValue() - 500;
response.setContentType("text/html");
PrintWriter out=response.getWriter();
getServletContext().getRequestDispatcher("/caption.html").include(request,r
esponse);
out.println("<html>");
out.println("<body bgclor=wheat>");
out.println("<h3> Employee net salary is : " + net +"</h3>");
out.println("</body");
out.println("</html>");
out.close();
}
}
web.xml
<web-app>
<servlet>
<servlet-name>source</servlet-name>
<servlet-class>GrossServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>target</servlet-name>
<servlet-class>NetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>source</servlet-name>
<url-pattern>/gross</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>target</servlet-name>
<url-pattern>/net</url-pattern>
</servlet-mapping>
</web-app>
Also do: -
Convert this to include mechanism in source.
Use include instead of forward method in source.
Filters
A Filter is not a Web Resource by itself i.e., Client never addresses the
request to the Filter. For that matter, Client does not know that Filter exists.
Similarly Web Component (Servlet/ jsp) also does not know that a Filter
exists.
Any request before reaching the Servlet is passed through Filter object.
Similarly any response coming from the Servlet passes through the Filter
before it is delivered to the Client.
S
E
R
V
L
E
T
Res Res Res
Filter 1 Filter 2
After receiving the request on its own can give the response back to
the Client without forwarding the request to the Servlet.
After receiving the request it can forward the request to the Servlet for
processing
A Filter has life cycle similar to the Servlet life cycle. Servlet Container
creates the instance of our own developed Filter class at the time of Web
Application installation.
Servlet Engine creates the FilterConfig instance. Container calls the init ()
method on the Filter instance by supplying the config object. FilterConfig
instance is capable of retrieving init parameters and context information
(similar to the ServletConfig)
Deployment of a Filter
FilterApp
login.html
relogin.html
WEB-INF
classes
WelcomeServlet.class
AuthenticateFilter.class
web.xml
http://localhost:8080/FilterApp/login.html
Note:
Filter should be registered before Servlet.
web.xml
<web-app>
<filter>
<filter-name>authenticate</filter-name>
<filter-class>AuthenticateFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>authenticate</filter-name>
<url-pattern>/login</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>welcome</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>welcome</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
login.html
<html>
<body bgcolor=cyan>
<center>
<form action=". /login" method=POST>
User Name : <input type=text name="user">
<br> Password : <input type=password name="pwd"><br>
<input type=submit value="login here">
</form>
</center>
</body>
</html>
relogin.html
<html>
<body bgcolor=cyan>
<center>
<h2>INVALID USER OR PASSWORD</h2>
<form action="./login" method=POST>
User Name : <input type=text name="user">
<br> Password : <input type=password name="pwd"><br>
<input type=submit value="login here">
</form>
</center>
</body>
</html>
AuthenticateFilter.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class AuthenticateFilter implements Filter
{
FilterConfig fc;
public void init (FilterConfig config) throws ServletException
{
fc=config;
System.out.println("Filter is instantiated and initialized");
}//init()
public void doFilter (ServletRequest request, ServletResponse response,
FilterChain chain) throws ServletException, IOException
{
String user=request.getParameter ("user");
String pwd=request.getParameter ("pwd");
if (user. equals (pwd))
chain.doFilter (request, response);//forward to Servlet
else
{
response.setContentType ("text/html");
ServletContext sc=fc.getServletContext ();
RequestDispatcher rd=sc.getRequestDispatcher ("/relogin.html");
rd.forward (request, response);
}//Filter sending response to client
}//doFilter
public void destroy ()
{
fc=null;
}
}
WelcomeServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
<filter>
<filter-name>x </filter-name>
<filter-class> </filter-class>
</filter>
<filter>
<filter-name>y</filter-name>
<filter-class> </filter-class>
</filter>
<filter-mapping>
<filter-name>x</filter-name>
<servlet-name>registration name of servlet</servlet-name>
[Can also give url-pattern]
</filter-mapping>
<filter-mapping>
<filter-name>y</filter-name>
<servlet-name>registration name of servlet</servlet-name>
[Can also give url-pattern]
</filter-mapping>
Java Server Pages
JSP is a specification.
A JSP page is a Web Component.
It is as active Web Resource in a Web Application
A jsp serves the Web-Client
A jsp produces the dynamic Web-Context.
A jsp is meant for extending the functionality of Web-Server.
A jsp contains html plus java code.
Disadvantages of Servlets:
Advantages of jsp:
Almost all the disadvantages of servlets are addressed in this server side
technology.
Translation phase
Compilation phase
Instantiation phase
Initialization phase
Servicing phase
Destruction phase
jsp_Init ()
_jspService ()
jspDestroy ()
Whenever client is making a request to the jsp file, jsp engine performs two
things:
Translation Compilation
Once container generated .class file is created, jsp engine role ends.
After translation and compilation phases servlet engine takes the control and
the other 4 phases are similar to normal servlet life cycle.
Tabular representation of jsp Life Cycle:
setProperty
custom getProperty
1) Scripting elements:
I. Declaration:
For example:
II. Expression:
Note:
Inside the jsp expression, java expression statement should not end with
a semicolon [;]
For example:
<% = a+b %>
III. Scriptlet:
Anything that starts with <% and ends with %> is a scriptlet according to
JSP specification.
Ex:
<% for (int i=0;i<0;i++)
System.out.println (“hello”);
Int a=10;
%>
Comments in a jsp:
When jsp o/p is sent to the browser and when we view the source from view
menu, we can’t see the jsp comments but can see html comments.
Jsp comments can’t be sent to the browser. Wherever jsp comments are
declared, we can declare the html comments.
(*conditions apply)
<%! void x ()
{
request.getParameter (“hello”);
}
%>
Inservlet class
{
Void x ()
{
request.getParameter (“-“);
}
_jspService()
{
}
}
}
These objects are known as implicit Objects in a jsp, implicit objects are
available only for expressions and scriptlets but not for declarations.
9 implicit objects (case sensitive):
1. out: It is the output stream for the jsp. This object is of type
javax.servlet.jsp.JspWriter class
But it is not available as normal text can be included in html only. If any
information calculated by servlet and given back to browser in that case we
can use this statement.
<%! Void x ()
{
Print (“hai”);
}
%>
4. application: javax.servlet.ServletContext
5. config: javax.servlet.ServletConfig
config.getInitParameter (-----);
6. session: javax.servlet.httpSession
request.getSession () in servlet to get session but in jsp it is directly
available.
Just like this. refers to current object, a present servlet instance can be
referred as page.
This is available only to those jsp which possibly error thrown while act as
error pages. All jsp will not get this object (*conditions apply policy come
here).
This object is not available to every jsp. Those jsp which act as error
handling pages can get this implicit object.
WelcomeJspApp
welcome.jsp
WEB-INF
web.xml
classes
http://localhost:8080/WelcomeJspApp/welcome.jsp
web.xml
<web-app>
</web-app>
welcome.jsp
<html>
<body bgcolor=cyan>
<h2>First JSP Example</h2>
<%
out.println ("welcome to jsp");
%>
</body>
</html>
Jsps are placed in the public area of the root directory of the Web
Application.
Never ever jsp is sent to the client. Jsp is the server side component. The
output (html) generated by the jsp is sent to the client.
SecondJspApp
two.jsp
WEB-INF
web.xml
classes
http://localhost:8080/SecondJspApp/two.jsp
two.jsp
<html>
<body bgcolor = wheat>
<%! int count=0;
String names [] = {"adil","baber"};
private String getName (int index)
{
return names [index];
}
%>
<h2>Number of times this page visited <%= ++count %> </h2>
<h3>The user is <%= getName (1) %>< /h3>
</body>
</html>
third.jsp:
<html>
<body bgcolor = wheat>
<h2>DATE AND TIME <%= new java.util.Date () %> </h2>
<h2>SERVER DETAILS : <%= application.getServerInfo () %>< /h2>
<% for (int i=1; i<=5; i++)
{
%>
<h2> WELCOME TO JSP</h2>
<%
}
%>
</body>
</html>
Web Application in which a jsp captures the form data, generates the
dynamic web content and sends the output to the Client
GreetingApp
user.html
greet.jsp
WEB-INF
web.xml
classes
http://localhost:8080/greetingApp/user.html
user.html
<html>
<body bgcolor=yellow>
<form action="./greet.jsp">
User : <input type=text name=t><br>
<input type=submit>
</body>
</html>
greet.jsp
<html>
<body bgcolor=wheat>
<h2>hello <%= request.getParameter ("t") %>< /h2>
</body>
</html>
USING JAVA BEANS IN A JSP
Java Bean: A java bean is a specialized java class with some standard
naming conventions.
A normal java class becomes a bean class if we define the class according to
java bean specifications.
Note:
Java beans make use of Servlet or jsp. On its own the beans will not execute.
A jsp contains java and html. We need to limit the java from directly in jsp
and send it to indirectly at background.
A jsp contains template text for presentation and direct java code to provide
dynamism for the page. There are some draw backs in this approach:
To minimize or totally eliminate java code from the foreground of the jsp we
have many approaches:
First approach:
MyApp
Html
Jsp
WEB-INF
Classes
Xyz.class- write application logic here
Second approach
1) useBean
2) setProperty
3) getProperty
1) useBean:
The above instruction when received by the jsp engine, 2 things happen:
2) setProperty:
3) getProperty:
This standard action is used to retrieve beans state with an xml kind of
syntax without need of writing any java code directly in the jsp. This is of
the following form:
Q) Between bean fields ans html form ields god synchronization exists.
Exlain?
Html form
Emp No
Name
Salary
CLICK
Web Application
BeanApp
Book.html
View.jsp
WEB-INF
web.xml
Classes
Bookpack
Book.class
Book.html
<html>
<body>
<center>
<H2>Book Details Form</H2>
<form action ="View.jsp">
ISBN: <input type="text" name="isbn"><br>
Title: <input type="text" name="title"><br>
<input type="submit" value="submit book details">
</center>
</body>
</html>
Book. java
package Bookpack;
public class Book implements Serializable
{
private int isbn;
private String title;
public void setIsbn (int isbn)
{
this.isbn=isbn;
System.out.println (“Bean is populated”);
}
public int getIsbn ()
{
return isbn;
}
public void setTitle (String title)
{
this.title=title;
}
public String getTitle ()
{
return title;
}
}
web.xml
<web-app>
</web-app>
View.jsp
<html>
<body bgcolor=cyan>
<center>
<h1>Book details from the bean </h1>
<%@ page import="Bookpack.Book" %>
<jsp: setProperty name="b" property ="*" />
<h2>Book ISBN: <jsp: getProperty name="b" property ="isbn" /></h2>
<h2>Book Title: <jsp: getProperty name="b" property ="title" /></h2>
<br><br>
<input type="submit">
</center>
</body>
</html>
Once control went to jsp and bean is instantiated
If any constructions will execute when the setProperty are called using * all
the setXXX () properties are called.
Note:
In the above jsp we have used page directive. This directive is used here to
import the package of the book bean class.
Every jsp implicitly imports 4 packages
1. java.lang.*
2. javax.servlet.*
3. javax.servlet.http.*
4. javax.servlet.http.jsp.*
As far as synchronization of bean fields and html form fields are concerned,
we used the following statement in the View.jsp
<jsp: setProperty name=”b” property=”*” />
The above instruction makes the container implicitly calling all the setter
methods of the bean instance whose reference is “b”. But one condition here
is that request parameters names (text field name) and bean variable names
must match for using *.
Values:
1. page
2. request
3. application
4. session
Q) Why is the bean not shareable across pages if its scope is page?
Q) Develop and deploy a Web Application in which two jsps sharing the
same bean (state) when the scope is “request”?
A) SharingbeanApp
Emp.html
Source.jsp
Target.jsp
WEB-INF
web.xml
Classes
Emppack
Employee. class
http://localhost:8080/sharingbeanApp/emp.html
Package emppack;
Public class Employee implements Serializable
{
private int empno;
private String name;
public void setEmpno(int empno)
{
this.empno=empno;
}
public int getEmpno()
{
return empno;
}
public void setName(String name)
{
this.name=name;
}
public int getName()
{
return name;
}
}//Employee
c:>/javac –d . Employee.java
Source code of emp.html
<html>
<body>
<center>
<h1>EMPLOYEE DETAILS FORM</h1>
<form action=”source.jsp”>
EMPLOYEE NO<input type=”text” name=”empno”><br>
EMP NAME<input type=”text” name=”name”><br>
<input type=”submit”>
</form>
</center>
</body>
</html>
<html>
<body bgcolor =”wheat”>
<%@ page import=”emppack.Employee” %>
<jsp:useBean id=”emp” class=”emppack.Employee” scope=”request” />
<center>
<h1>EMPLOYEE DATA</h1>
<h1>EMPLOYEE NUMBER : <jsp:getProperty name=”emp”
property=”empno” /></h1>
<h1>EMPLOYEE NAME : <jsp:getProperty name=”emp”
property=”name” /></h1>
</center>
</body>
</html>
web.xml
<web-app>
</web-app>
Note:
When the scope is request, the bean instance is not only bound to the
reference variables but also it is stored in the request object. When control is
switched to another jsp using forward mechanism, the second jsp gets the
same request object in which the bean and the state is stored. In the second
jsp when we make use of useBean, new instance is not created; the existing
bean is retrieved from the source jsp.
jsp 2
5
4
Java
Bean
3
Web Client Web Container
DATABASE
In this architecture, jsp is the core element. It is responsible for receiving the
client request, instantiating the bean, populating the bean, retrieving the
database data from the bean and driving the output to the client.
Servlets
2
jsp Java
5 Bean
6
3
Web Client Web Container
DATABASE
A) Refer to Hand-out
MVCApp
Emp.html
View.jsp
WEB-INF
web.xml
Classes
Nit
Servlets
ControllerServlet.class
Beanpack
Employee.class
http://localhost:8080/MVCApp/emp.html
<html>
<body bgcolor=”./mvc”>
</html><html>
<body bgcolor="cyan">
<form action="./mvc">
<center>
EMPLOYEE NUMBER<input type="text" name="eno"><br><br>
<input type=SUBMIT value="SNDEMPNO">
</center>
</body>
</html>
package beanpack;
import java.sql.*;
public class Employee implements java.io.Serializable
{
Connection con;
private int empno;
private String name;
private float salary;
public Employee()
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl",
"scott","tiger");
}
catch(Exception e)
{
}
public void setEmpno(int empno)
{
this.empno=empno;
results();
}
public int getEmpno()
{
return this.empno;
}
public void setName(String name)
{
this.name=name;
}
public String getName()
{
return this.name();
}
public void setSalary(float salary)
{
this.salary=salary;
}
public float getSalary()
{
return this.salary;
}
public void results()
{
try
{
Statement s=con.createStatement();
ResultSet rs=s.executeQuery("select * from employee where
empno="+empno);
rs.next();
name=rs.getString("name");
salary=rs.getFloat("salary");
}
catch(Exception e)
{
}
}
}//class
package nit.servlet;
import javax.servlet.*;
import javax.servlet.*;
import beanpack.Employee;
import java.io.*;
public class ControllerServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException,IOException
{
int empno=Integer.parseInt(request.getParameter("eno");
Employee ebean=new Employee();
ebean.setEmpno(empno);
getServletContext().setAttribute("ebean",ebean);
getServletContext().getRequestDisapatcher("/view.jsp").forward(request,res
po
nse);
}
}
<html>
<body>
EMPLOYEE DETAILS<br><br>
<%@ page import="beanpack.Employee" %>
<jsp:useBean id="ebean" class="beanpack.Employee"
scope="application" />
EMPNO : <jsp:getProperty name="ebean" property="empno" /><br>
NAME : <jsp:getProperty name="ebean" property="name" /><br>
SALARY : <jsp:getProperty name="ebean" property="salary" /><br>
</body>
</html>
<web-app>
<servlet>
<servlet-name>controller</servlet-name>
<servlet-class>nit.servlets.ControllerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>controller</servlet-name>
<url-pattern>/mvc</url-pattern>
</servlet-mapping>
</web-app>
Web Application development and deployment steps :
1) include directive: when we use directive the source code of the included
file (target) is copied into current jsp at translation time.
2) include standard action: the response of the target jsp is included in the
current jsp’s response at request processing time.
Q) What are the differences between include directive and include
standard action?
A)
S.No Criteria Directive Standard Action
http://localhost:8080/includedirApp/source.jsp
<html>
<body>
<marquee><font color=”green” size=8> WELCOME TO OUR
SITE</font></marquee>
</body>
</html>
<html>
<body>
<br><br>
<br><br>
<br><br>
<br><br>@copy Naresh Information Technologies
</body>
</html>
<html>
<body bgcolor=cyan>
<%@ include file=”header.jsp” %>
<h1>HERE GOES THE BODY OF THE JSP</h1>
<@ include file=”footer.html” %>
</body>
</html>
web.xml
<web-app>
</web-app>
IncludeactionApp
Source.jsp
Target.jsp
WEB-INF
Web.xml
Classes
http://localhost:8080/includeactionApp/source.jsp
Source code of source.jsp
<html>
<body bgcolor=”wheat”>
<h1>INCLUDE ACTION USAGE</h1>
<jsp:include page=”target.jsp”>
<jsp:param name=”user” value=”[email protected]” />
</jsp:include>
</body>
</html>
<html>
<body bgcolor=wheat>
<h1><% out.println(“request.getParameter(“user”)); %></h1>
</html>
Session tracking
When http client makes a request to the http server, it gives response to the
client. Once request-response cycle is over, client is disconnected form the
server. This nature poses some challenges to the Web Application
developers.
Client interaction with the Web Application must be Stateful. Then only,
across series of requests a client is uniquely recognized and previous data
can be associated with the current request.
Session tracking is the ability of the Container to recognize the Client and its
associated data across multiple series of interactions.
Cookies
Httpsession
url rewriting
cookies mechanism
a cookie is a name value pair of textual information created bythe server and
exchanged between client and server with every interaction
Javax.servlet.http.Cookie
Javax.servlet.http.HttpServletRequest interface
Javax.servlet.http.HttpServletResponse interface
Response.addCookie(c);
CookieApp
CookieExample.html
Welcome.html
Web-INF
Web.xml
Classes
CreateCookie.class
CheckCookie.class
http://localhost:8080/CookieApp/CookieExample.html
<html>
<body bgcolor=cyan>
<center>
<h2>WELCOME TO SHOPPING MALL</h2>
<form action=”./create” method=”post”>
<b>User Name</b>
<input type=text name=”user” > <br> <br>
<input type=submit value=”welcome” > <br> <br>
</center>
</body>
</html>
<html>
<body>
<marquee>
<font color=green size=6>
WELCOME TO SHOPPING MALL
</marquee>
</body>
</html>
Import java.io.*;
Import javax.servlet.*;
Import javax.servlet.http.*;
Public class CreateCookie extends HttpServlet
{
Public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException,IOException
{
String name=req.getParameter(“user”);
Res.setContentType(“text/html”);
PrintWriter pw=res.getWriter();
Cookie c=new Cookie(“user”,name);
Res.addCookie(c);
Pw.println(“<html>”);
Pw.println(“<body bgcolor=wheat><center>”);
Req.getRequestDispatcher(“welcome.html”).include(req,res);
Pw.println(“<h2><a href=”./check”>SHOPPING GOES HERE</a></h2>”);
Pw.println(“</center></body></html>”);
Pw.close();
}
}
Import java.io.*;
Import javax.servlet.*;
Import javax.servlet.http.*;
Public class CreateCookie extends HttpServlet
{
Public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException,IOException
{
Res.setContentType(“text/html”);
PrintWriter pw=res.getWriter();
Cookie c[]=req.getCookies();
Pw.println(“<html>”);
Pw.println(“<body bgcolor=wheat><h2>”);
For(int i=0;i<length;i++)
{
Cookie c1=c[i];
If(c1.getName().equals(“user”))
{
Pw.println(“Hai”+c1.getValue() + ! Hope enjoying shopping here </h2>”)
Break;
}
}
Pw.println(“</body></html>”);
Pw.close();
}
}
Web.xml
<web-app>
<servlet>
<servlet-name>create</servlet-name>
<servlet-class>CreateCookie</servlet-class>
</servlet>
<servlet>
<servlet-name>check</servlet-name>
<servlet-class>CheckCookie</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>create</servlet-name>
<url-pattern>/create</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>check</servlet-name>
<url-pattern>/check</url-pattern>
</servlet-mapping>
</web-app>
A) c.setMaxAge(0);
CookieApp
Userdetails.html
Readdetails.jsp
Getcookies.jsp
userdetails.html
<html>
<body bgcolor=wheat>
<form action=”./readdetails.jsp”>
Email ID: <input type=text name=”mail”><br>
Phone: <input type=text name=”phone”><br><br>
<input type=submit value=”submit details”>
</form>
</body>
</html>
Source code of readdetails.jsp
<%
String emailid=request.getParameter(“mail”);
String phone=request.getParameter(“phone”);
Cookie c1=new Cookie(“mail”,emailed);
Cookie c2=new Cookie(“phone”,phone);
Response.addCookie(c1);
Response.addCookie(c2);
Out.println(“<a href=”./getcookies.jsp”>CLICK HERE TO GET YOUR
DETAILS</a>””);
%>
<%
Cookie c[]=request.getCookies();
Out.println(“EMAIL ID:” +c[0].getValue());
Out.println(“PHONE NUMBER:+”c[1].getValue());
%>
Step 2: Retrieve the client data in the current request and add it to the
session object.
session.setAttribute (String name, Object value);
Step 4: When the end user explicitly wants to logout, destroy the session
object.
When the response is given to the client, container sends the associated
session id through response header. For sending session id, cookie
mechanism is internally used.
Q) What is seesion time-out in Session tracking?
A) For each client one session object is dedicated. It will consume few
server resources. Between the last client request and current system time,
if a specified amount of time is lapsed which is known as max inactive
interval, container destroys the session object associated with that client.
This is known as session time-out. When the session object is destroyed,
session id as well as client state gets discarded.
By default tomcat gives 30 minutes for session time-out. We
can also configure session time in two ways:
Declaratively
Programatically
<session-config>
<session-timeout>
45
</session-timeout>
</session-config>
rewritingApp
WEB-INF
Web.xml
Classes
SessionDetailsServlet.class
web.xml
<web-app>
<servlet>
<servlet-name>details</servlet-name>
<servlet-class>SessionDetailsServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>details</servlet-name>
<url-pattern>/details</url-pattern>
</servlet-mapping>
</web-app>
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
Custom Action
1) Standard actions
2) Custom actions
1) Standard actions
Standard actions are runtime instructions given by the jsp author to the jsp
whose meaning is already known to the container. The advantage of these
actions is that by using xml kind of syntax tags, we can get the functionality.
There is no need of writing java code directly in the jsp. This makes jsp
development easier, flexible, and maintainable.
2) Custom actions
Standard actions are excellent in their functionality but they ate confined to
few areas. In practical industry strength Web Applications, this limited
functionality is not sufficient.
Complex functionality has to be provided. Hence the need of our own
defined actions.
Q) What are the differences between standard action and custom actions?
1) Tag
I. Prefix
II. Action name
For example,
<jsp: forward>
2) Tag Handler
It is a java class that provides the action (functionality) for the tag.
3) Tag library Descriptor
In this file tags and their properties are described. Mapping between tags
and corresponding tag handlers specified. Tag library information is
specified.
4) Tag library
SetPageContext(PC)
SetAttributes()
………………
Tag.EVAL_BODY_INCLUDE
DoStartTag()
Container evaluates
the body of the tag
Tag.EVAL_PAGE Tag.SKIP_PAGE
DoEndTag()
customtagapp
WEB-INF
Web.xml
Tld
Ourtaglib.tld
Classes
Hellopack
HelloHandler.class
http://localhost:8080/customtagapp/hello.jsp
<html>
<body bgcolor=wheat>
<%@ taglib prefix="nit" uri="http://www.nit.com/customtags" %>
<h3><nit:hello />WELCOME TO CUSTOM TAGS</h3>
</body>
</html>
<web-app>
<taglib>
<taglib-uri>
http://www.nit.com/customtags
</taglib-uri>
<taglib-location>
/WEB-INF/tld/ourtaglib.tld
</taglib-location>
</taglib>
</web-app>
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>nit</short-name>
<tag>
<name>hello</name>
<tag-class>hellopack.Hellohandler</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
package hellopack;
import jaax.servlet.jsp.*;
import jaax.servlet.jsp.tagext.*;
import java.io.*;
public class HelloHandler extends TagSupport
{
public int doStartTag() throws JspException
{
try
{
JspWriter out=pageContext.getOut();
out.println("hello");
}
catch(IOException e)
{
System.out.println(e);
}
return SKIP_BODY;
}
}
A) Refer to hand-out.
Whenever attributes are there for a tag, we have to do two things in the Tag Handler.
Declare those many private variables as there are attributes.
For each variable, one setter method.
Step 2: In the tld file we have to make entries regarding the attributes
<tag>
</tag>
ClassicTagWithAttributes
Greet.jsp
WEB-INF
Web.xml
Tld
Ourtaglib.tld
Classes
Greetpack
GreetingHandler.class
<html>
<body bgcolor=wheat>
<%@ taglib prefix="nit" uri="htp://www.nit.com/customtags" %>
<h2><nit:greet name="Adil" Age="23" /></h2>
</body>
</html>
<web-app>
<taglib>
<taglib-uri>
http://www.nit.com/customtags
</taglib-uri>
<taglib-location>
/WEB-INF/tld/ourtaglib.tld
</taglib-location>
</taglib>
</web-app>
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>nit</short-name>
<tag>
<name>greet</name>
<tag-class>greetpack.GreetingHandler</tag-class>
<body-content>empty</body-content>
<attribute>
<name>name</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>age</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
Databaseapp
Results.html
Results.jsp
WEB-INF
Web.xml
Mytaglib.tld
Classes
Students
Resultshandler.class
http://localhost:8080/databaseapp/results.html
<html>
<body bgcolor=cyan>
<%@ taglib uri=”customtags” prefix=”nit” %>
<h2>ENTRANCE SCORE CARD</h2>
<h3><nit:results /></h3>
</body>
</html>
<web-app>
<taglib>
<taglib-uri>customtags</taglib-uri>
<taglib-location>/WEB-INF/mytaglib.tld</taglib-location>
</taglib>
</web-app>
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>nit</short-name>
<tag>
<name>results</name>
<tag-class>students.ResultsHandler</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
Package students;
Import javax.servelt.jsp.*;
Import javax.servlet.jsp.tagext.*;
Import java.sql.*;
Public class ResultsHandler extends TagSupport
{
Connection connection;
Public ResultsHandler()
{
Try
{
Class.forName(“oracle.jdbc.driver.OracleDriver”);
Connection=DriverManager.getConnection(“jdbc:oracle:thin:@localhost:15
21:orcl”,”scott”,”tiger”);
}
Catch(Exception e)
{
}
Public int doStarttag() throws JspoException
{
Try
{
JspWriter out=pageContext.getOut();
String htNo=pageContext.getRequest().getparameter(“htNo”);
Statement st=connection.createStatement();
ResultSet rs=st.executeQuery(“select * from entrance where htNo=”+htNo);
Rs.next();
Out.println(“HAL:L TICKET NUMBER :” +htNo);
Out.println(“CANDIDATE NAME:”+rs.getString(2));
Out.println(“MARKS:”+rs.getString(3));
Rs.close();
St.close();
}
Catch(Exception e)
{
}
Return SKIP_BODY;
}//doStartTag()
Public void release()
{
Try
{
If(connection!=null)
Connection.close();
}
Catch(Exception e)
{
}
}//release
}
Life Cycle and Flow Chart of Iteration Tag:
Tag
Interface
Extends
Implements
IterationTag TagSupport
Interface
setAttributes()
………………
EVAL_BODY_INCLUDE
doStartTag(
)
Container evaluates
the body of the tag
EVAL_BODY_AG
AIN SKIP_BO
DY
doAfterBody
()
EVAL_PAGE SKIP_PAGE
doEndTag()
Evaluate the rest of the jsp Return from the current jsp
without evaluating
Q) Web Application on IterationTag
A) Refer to the hand-out.
Iterationapp
Loop.jsp
WEB-INF
Web.xml
Tld
Mytaglib.tld
Classes
Iterationpack
IterationTagHandler.class
http://localhost:8080/iterationapp/loop.jsp
<html>
<body bgcolor=pink>
<%@ taglib prefix=”nit” uri=”customtags” %>
<nit:iterate count=”5” > THIS IS EVALUATED
REPETITIVELY</nit:iterate>
</body>
</html>
<web-app>
<taglib>
<taglib-uri>customtags</taglib-uri>
<taglib-location>/WEB-INF/tld/mytaglib.tld</taglib-location>
</taglib>
</web-app>
Source code of mytaglib.tld
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>nit</short-name>
<Tag>
<name>iterate</name>
<tag-class>iterationpack.IterationTagHandler</tag-class>
<body-content>JSP</body-content>
<attribute>
<name>count</name>
<required>true</required>
</attribute>
</Tag>
</taglib>
Package iterationpack;
Import javax.servlet.jsp.*;
Import javax.servlet.jsp.tagext.*;
Public class IterationTagHandler extends TagSupport
{
Private int count;
Public void setCount(int count)
{
This.count=count;
}
Public int doStartTag() throws JSpException
{
If(count>0)
Return EVAL_BODY_INCLUDE;
Else
Return SKIP_BODY;
}
Public int doAfterBody() throws JSpException
{
If(--count>0)
Return EVAL_BODY_AGAIN;
Else
Return SKIP_BODY;
}
}
TYPES OF RESULTSET
A) Normal way of creating the ResultSet object is Non Scrollable and Non
Updatable ResultSet.
Statement st=con.createStatement
(ResultSet.SCROLLABILITYCONSTANT,
ResultSet.UPDATABILITYCONSTANT);
Note:
Once we create the Statement objects in such a specialized manner, they can
produce scrollable or updatable ResultSet objects.
A) Statement st=con.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
Or
Statement st=con.createStatement
(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
A) Statement st=con.createSatement
(ResultSet.TYPE_SCROLL_FORWARDONLY,
ResultSet.CONCUR_UPDATABLE);
A) There are few benefits if we can move the cursor in both the directions. If
we can move the cursor to the required row.
We can create a GUI tool using which we can browse through the records of
the ResultSet object.
Even after reading the row of the ResultSet object, we can read the data
again.
We can move to a particular row in order to update it.
Next()
Previous()
Relative(-/+ number)
Absolute(-/+ number)
First()
Last()
beforeFirst()
afterLast()
Int getRow()
Booloean isLast()
Boolean isFirst()
Boolean isBeforeFirst()
Boolean isAfterlast()
Class.forName();
Connection con=DM.getConnection();
Statement
st=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultS
et.CONCUR_READ_ONLY);
ResultSet rs=st.executeQuery(“select * from employee”);
Rs.last();
Int noofrows=rs.getRow();
A) The ResultSet object which contain a set of records is open to all the
applications. If the modifications made to the ResultSet are also available to
the external program then we say that the ResultSet is sensitive or else
insensitive.
Every ResultSet object is associated with a special row known as insert row.
It is considered as a special buffer into which we can compose column
values of a record.
Step 1: Move the cursor to the buffer row( insert row) to compose the
column values.
Rs.moveToInsertRow();
Step 2: Compose the new row with column values. We call updateXXX()
methods to do this job.
Record will be deleted both from the REsultSet and database (table) . The
above all things are not all used in real time projects, but will be useful in
GUI tools.
Batch Updates
Batch Update is a facility offered by the JDBC. By using this facility we can
submit SQL Statements as a batch to the database server to perform update
operations.
OLTP(Online Transaction Processing)
Batch Processing- Number of trips to the server can be reduced.
This is the advantage of Batch Processing
To implement Batch Update concepts we have 2 methods.
1. addBatch(String DMLStmt)
2. int[] executeBatch()
Statement object is associated with a list (some internal data structure). This
list is initially empty. We can add any number of SQL Statements to the list.
St.addBatch(“insert……..”);
St.addBatch(“update……”);
St.addBatch(“delete…….”);
This array would contain various compartments, each compartment for each
Statement. Each compartment would contain a number that would indicate
the number of rows that are effected by each of the Batch Statement.
OLTP- When the user expects the response to be given immediately after he/
she gives request.
Ex: ATM
Statement st=con.createStatement();
St.addBatch(“insert into Student values(1, ‘Adil’);
St.addBatch(“delete from Student where sno=1”);
St.addBatch(“Update student set sname= ‘adil’ where sno=2”);
Int affectedRows[] =st.executeBatch();
Int rows=0;
For(int i=0;i<affectedRows.length;i++)
Rows+=affectedRows[i];
System.out.println(“Number of rows affected : “ +rows);
1. SQLException
2. BatchUpdateException
For some reasons if any of the SQL Statement is unable to be excuted, the
method throws BatchUpdateException
In the batch is any SQL Statement returns other than integer, i.e., DDL or
DRL Statement, this method throws SQLException
Simple Transaction Management
Or
Try
{
Statement st =con.createStatement();
St.executeUpdate(“Update cur_acct set bal=bal-40000 where
acct_no=501”);
St.executeUpdate(“update sav_acct set bal=bal+40000 where
acct_no=956”);
}
Catch(Exception e)
{
System.out.println(e);
}
Note: When SQL Statements are submitted through java i.e., JDBC
and once the result is given then changes are made permanent to the
database. This is the advantage of submitting SQL Statements through java.
In SQL, i.e., at the SQL prompt whatever changes are made to the database
they aree not permanent, if we want to make the changes permanent we need
to use commit.
In case of transaction failure changes are rolled back.
Every transaction has 2 boundaries. Controlling these boundaries is known
as transaction demarcation or transaction management.
The 2 boundaries of the transaction are:
1. Beginning of the Transaction
2. End of the Transaction
In java when the Connection is established with the database the Connection
object is opened with auto commit mode enabled. As a result each SQL
Statement submitted to the database behaves as an individual transaction.
Therefore, we cannot logically group SQL Statements into one unit of
interaction.
In order to group a set of SQL Statements into one unit we have to disable
the commit mode of the Connection object.
Con.setAutoCommit(false);
Try
{
Statement st=con.createStatement();
Connection con=DM.getConnection();
Con.setAutoCommit(false); //making the changes permanent is stopped
St.executeUpdate(“update cur_acct set bal=bal-40000 where acct_no=501”);
St.executeUpdate(“update sav_acct set bal=bal+40000 where
acct_no=956”);
Con.commit();//ending the transaction
}
Catch(Exception e)
{
Con.rollBack();
}
Once the above method call is made our unit of interaction ( transaction)
starts.
In order to end a transaction we have to call either
Con.commit() – successful ending
or con.rollback() – unsuccessful ending
try
{
Connection con=DM.getConnection();
Statement st=con.createStatement();
con.setAutoCommit(false);
st.excuteUpdate("update cur set bal=bal-40000 where acct_no=501");
st.excuteUpdate("update sav set bal=bal+40000 where acct_no=956");
con.commit();
}
catch(Exception e)
{
try
{
con.rollback();//this will again raise exception
}
catch(Exception e)
{
System.out.println(e);
}
}
Type 2 Drivers
Database Server
Native Library
Client Server
This driver converts JDBC method calls of the Client Application (JDBC
program) into database server vendor dependent library calls
Disadvantages:
Example:
Connection URL:
Type 3:
Core library
Database accessing library
Xml data processing library
I18n and formatting library
Step 1: Copy 2 jar files into the lib directory of our Web application root
directory.
Standard.jar
Jstl.jar
The batch update facility provided by the JDBC 2.0 core API allows a
Statement object to submit multiple update commands together as a
single unit, or batch, to the underlying DBMS. This ability to submit
multiple updates as a batch rather than having to send each update
individually can improve performance greatly in some situations.
try {
stmt.addBatch("INSERT INTO employees VALUES (" +
"1000, 'Joe Jones')");
stmt.addBatch("INSERT INTO departments VALUES (260,
'Shoe')");
stmt.addBatch("INSERT INTO emp_dept VALUES (1000, '260')");
} catch(BatchUpdateException b) {
System.err.println("Update counts of successful commands: ");
int [] updateCounts = b.getUpdateCounts();
for (int i = 0; i < updateCounts.length; i ++) {
System.err.print(updateCounts[i] + " ");
}
System.err.println("");
}
If a printout was generated and looked similar to the following, the first two
commands succeeded and the third one failed.
JDBC drivers are not required to support batch updates, so a particular driver
might not implement the methods addBatch, clearBatch, and
executeBatch. Normally a programmer knows whether a driver that
he/she is working with supports batch updates, but if an application wants to
check, it can call the DatabaseMetaData method
supportsBatchUpdates to find out. In the following code fragment, a
batch update is used only if the driver supports batch updates; otherwise,
each update is sent as a separate statement. The connection's auto-commit
mode is disabled so that in either case, all the updates are included in one
transaction.
con.setAutoCommit(false);
if(dbmd.supportsBatchUpdates) {
stmt.addBatch("INSERT INTO . . .");
stmt.addBatch("DELETE . . .");
stmt.addBatch("INSERT INTO . . .");
...
stmt.executeBatch();
} else {
System.err.print("Driver does not support batch updates; ");
System.err.println("sending updates in separate statements.");
stmt.executeUpdate("INSERT INTO . . .");
stmt.executeUpdate("DELETE . . .");
stmt.executeUpdate("INSERT INTO . . .");
...
con.commit();