Transcript Slide 1

Why server side programming ?
What is java servlet ?
Practical applications of java servlets
– Developing ecommerce
– Web site that open up large legacy system
on internet
– Distributed object application on web
Alternatives for servlets
• CGI
creates new process for each CGI request
implemented in perl (require interpreter for every req. )
• server side java script
Javascript into precompiled HTML pages.
Nerscape’s Enterprise and fasttrack server
• ASP
Not precompiled tied to specific web server IIS
Why servlet?
• Efficient
» Initialization only first time, then it call’s service
• Persistent
» Maintain state between requests( It stay resident in memory)
• Portable
» Because they are in java.
• Robust
» Well define exception handling.
• Extensible
» Polymorphism and inheritance
• Secure
» Server side
» Java security manager
Java servlet architecture
<<interface>>
Javax.servlet.Servlet
----------------------------------------------------------Init( )
getServletConfig( )
service( )
getServletInfo( )
Destroy()
Javax.servlet.http.HttpServlet
------------------------------------------------------------------------doDelete()
doGet()
doOptions()
doPost()
doPut()
doTrace()
getLastModified()
service()
<<interface>>
Javax.servlet.ServletConfig
----------------------------------------------------------getInitParameter( )
getServletContex( )
getInitParameterNames( )
Javax.servlet.GenricServlet
------------------------------------------------------------------------getInitParameter( )
getServletContext( )
getInitParameterNames( )
log( )
init()
getServletConfig()
service()
getServletInfo()
destory()
<<interface>>
Javax.io.Serializable
-----------------------------------------------------------
Genericservlet and HttpServlet
• No main() it calls servlets service() method.
• GenericServlet.service()
Public abstract void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException
• Httpservlet.sevice()
Public abstract void service(HttpServletRequest rq, HttpServletResponse rs)
throws ServletException, IOException
It’s already implemented . Depending upon METHOD stored in request it
overrides doGet() or doPost()
Life cycle of servlet
• java.servlet.Servlet interface
– init()
» Call immediately after server initialize.
» It initializes resources that will be using for request.
» Public void init(ServletConfig config) throws Servletexception
– service()
» Handle all request send by client. starts aftre init()
» Public abstract void service (ServletRequest req,
ServletResponse res)
throws ServletException, IOException
– destory()
»
»
»
»
End of servlet life
Return all resource eg close database connection
Good place to save persistent information
Public void destory();
Simple servlet to display hello
// simple servlet to display “Hello again servlet “
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AgainHello extends javax.servlet.http.HttpServlet
implements javax.servlet.Servlet
{
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<hr/>");
out.print("<h3>Hello again Servlet</h3>");
}
}
import javax.servlet.ServletException;
import javax.servlet.http. *;
public class AgainHello extends javax.servlet.http.HttpServlet
implements javax.servlet.Servlet
{
public void init (ServletConfig config) throws servletException
{
super.init(config)
}
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<table border=2><tr><th>Doller</th><th>Rs.</th></tr>");
for(i=1;i<10;i++)
out.print(“<tr><td>“ + i + “</td><td>“ + i*50 + “</td></tr>”);
}}
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response); }
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response); }
public String getServletInfo()
{ return “Description for request method Created by A. Yeole
on 3-6-2006 ";
}
}
Java servlet architecture
<<interface>>
Javax.servlet.Servlet
------------------------------
<<interface>>
Javax.servlet.ServletConfig
-----------------------------------------------------------
Javax.servlet.GenricServlet
-------------------------------------------------------------------------
Javax.servlet.http.HttpServlet
-------------------------------------------------------------------------
AgainHello
<<interface>>
Javax.io.Serializable
-----------------------------------------------------------
The methods overridden by
AgainHello
•
•
•
•
init()
doGet()
doPost()
getServletInfo()
Httpservlet request object
•
•
•
•
•
getCookies();
getMethod();
getPathInfo();
getServletPath();
getContextPath();
//myservlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AgainHello extends javax.servlet.http.HttpServlet
implements javax.servlet.Servlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Servlet myservlet at " + request.getContextPath () +
"</h1>");
out.println("<p> servlet path : : " + request.getServletPath() +" </p>");
out.println("<p>the name of this servlet : : " + getServletInfo() +" </p>");
}
public String getServletInfo() {
return “Description for request methode Created by A. Yeole on 3-6-2006 ";
}
}
Html form has action servlet
// html file myhtml.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN">
<html>
<head>
<title></title>
</head>
<body>
<form action="myservlet“ method=“GET" >
<input type="submit" value="click me" name="b1" />
</form>
<form action="myservlet" method="POST" enctype="multipart/formdata">
<input type="submit" value="click me post" /> </form>
</body>
</html>
// file myservlet.java
import java.io.*; import java.net.*; import javax.servlet.*; import javax.servlet.http.*;
public class myservlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet myservlet</title>");
out.println("</head>");
out.println("<body>");
out.print("<h1>MY FAVORITE SUBJECTS</h1>");
out.print("<li>Operating Systems</li>");
out.print("<li>Java</li>");
out.print("<li>Maths</li>");
out.println("</body>");
out.println("</html>");
out.print("<li>C</li>");
out.close(); }
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response); }
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response); } }
Retrieving form data in a servlet
• Three methods are used to retrieve request
parameters are the ServletRequest’
• Public Enumeration ServletRequest.getParameterNames();
• Public String ServletRequest.getParameter(String name);
• Public String[] ServletRequest.getParameterValues(String n);
//form.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
</head>
<body>
<form name="form1" action="formservlet">
<br> Email : <input type="text" name="email" value="" size="20" /><br>
<br> Are U registered user :
<input type="radio" name="reg" value="registered" checked="checked" />Yes
<input type="radio" name="reg" value="unregistered" />No<br><br>
<input type="submit" value="submit" name="submit" /><br>
</form>
</body>
</html>
//formservlet.java prog for reading data from form
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.http.HttpServletRequest;
public class formservlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>"); out.println("<head>"); out.println("</head>");
out.println("<body>");
String email = request.getParameter("email");
String rg = request.getParameter("reg");
out.println("<p>the mail id u have entered : : " + email +" </p>");
if (rg.equals("registered"))
out.println("<h1> Registered user </h1>");
if (rg.equals("unregistered"))
out.println("<h1> UnRegistered user </h1>");
out.println("</body>");
out.close(); }
Use of getParameterNames()
Enumeration p = request.getParameterNames();
String s;
While(p.hasMoreElements())
{
s = (String)p.nextElement();
out.printnl(s + “ : “ + request.getParameter(s) );
}
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class servlet2 extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading All Request Parameters";
out.println( "<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>" + title + "</H1>\n" +
"<TABLE BORDER=1 ALIGN=CENTER>\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" +
"<TH>Parameter Name<TH>Parameter Value(s)");
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.println("<TR><TD>" + paramName + "\n<TD>");
String[] paramValues = request.getParameterValues(paramName);
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0)
out.print("<I>No Value</I>");
else
out.print(paramValue);
} else {
out.println("<UL>");
for(int i=0; i<paramValues.length; i++) {
out.println("<LI>" + paramValues[i]);
}
out.println("</UL>");
}
}
out.println("</TABLE>\n</BODY></HTML>");
out.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
public String getServletInfo() {
return "Short description"; }
}
Listing All Form Data
// content of response - excel
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ApplesOranges extends javax.servlet.http.HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
response.setContentType("application/vnd.ms-excel");
PrintWriter out = response.getWriter();
out.println("\tQ1\tQ2\tQ3\tQ4\tTOTAL");
out.println("Apples\t78\t87\t29\t10\t=Sum(b2:e2)");
out.println("Oranges\t77\t86\t93\t10\t=Sum(b3:e3)");
}
}
Parsing initialization parameters
• Initialization parameters are not part of
request.
• they are passed to the servlet when it first
loaded. Therefore u have access to them
in init() method.
• The value of these parameter does not
change until the servlet reloaded.
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class myservlet1 extends HttpServlet {
private String message;
private String defaultMessage = "No message.";
private int repeats = 1;
public void init(ServletConfig config) throws ServletException {
message = config.getInitParameter(“company");
}
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println(“Wel come to ” + message);
out.close(); }
}
What is jdbc
•
It is a pure java API used to execute sql
statements.
•
Basic step :
1.
2.
3.
4.
Open connection to database
Execute sql statement
Process the result
Close connection
• JDBC driver is JDBC ODBC bridge
provided by sun jdk1.1 and later.
• It provides jdbc access to database trough
odbc.
Application space
Java application
JDBC ODBC bridge
ODBC driver
Database
Installing and setting up ODBC
bridge
Control panel
Establishing database connection
1. load JDBC driver
2. make connection
1. load JDBC driver
• The class name of the JDBC-ODBC bridge driver is
sun.jdbc.odbc.JdbcOdbcDriver. When a driver is loaded,
it registers itself with Drivermanager which is then used
to get the Connection.
1. new JdbcOdbcDriver();
Will load a new driver object, calling its
constructor.
2.Other way is class.forName(“JdbcOdbcDriver”)
“forName” method of the “class” in “java.lang
package”
2.Make connection
• We connect to database using the static method getConnection()
method of DriverManager class that returns a connection .
• To get a connection, we need to specify a url for the actual database
we wish to use. The form of this url is specific to the driver we are
using. With the driver loaded, we can use the properties file above to
get the database url. Using the Sun JDBC-ODBC bridge driver, the
url of the database is jdb:odbc:xxx where xxx is the ODBC data
source name registered for your database.
String url = "jdbc:odbc:anjali";
String user="";
String password ="";
Connection con =DriverManager.getConnection(url,user,password);
Open connection to database. you will be using it to create JDBC
statements to the database.
Using statment
• A Statement is obtained from a Connection:
Statement stmt = con.createStatement() ;
• Once you have a Statement, you can use it to execute, and control
the execution of, various kinds of SQL queries.
Use stmt.executeUpdate with a string argument containing the text
of an SQL update query (INSERT, DELETE or UPDATE). This
returns an integer count of the number of rows updated.
Use stmt.executeQuery with a string argument containing the text of
an SQL SELECT query. This returns a ResultSet object which is
used to access the rows of the query results.
• int count = stmt.executeUpdate("INSERT INTO
Customers " + "(CustomerFirstName,
CustomerLastName, CustomerAddress) " "VALUES
('Tony', 'Blair', '10 Downing Street, London')") ;
•
ResultSet rs = stmt.executeQuery("SELECT * FROM
Customers") ; // do something with count and RS
Retrieving Information
• When executing an SQL statement that returns
results, we use the executeQuery method which
returns Resultset containing the row of data that
satisfy the query
Executing
ResultSet rs = stmt.exectueQuery
(“SELECT * FROM customer”);
returns the rows containing the names, add of all
entries in customer.
Working with ResultSets
• If you do not know exactly the table
structure (the schema) of the ResultSet,
you can obtain it via a ResultSetMetaData
object
ResultSetMetaData rsmd = rs.getMetaData() ;
int colCount = rsmd.getColumnCount() ;
for (int i = 1 ; i <= colCount ; i++)
{
if (i > 1)
out.print(", ");
out.print(rsmd.getColumnLabel(i)) ;
}
out.println() ;
• Sim.java
PreparedStatement
•
The PreparedStatement interface inherits from
Statement .
1. Instances of PreparedStatement contain an SQL
statement that has already been compiled.
2. The SQL statement contained in a PreparedStatement
object may have one or more IN parameters.
Because PreparedStatement objects are precompiled, their
execution can be faster than that of Statement objects.
• Being a subclass of Statement,
PreparedStatement inherits all the
functionality of Statement. In addition, it adds
a set of methods that are needed for setting
the values to be sent to the database in place
of the placeholders for IN parameters. Also,
the three methods execute, executeQuery,
and executeUpdate are modified so that they
take no argument.
• Pre.java
Transactions
• Transactions are a mechanism to group
operations together so that either all of them
complete together successfully or none of them
do.
When a Connection is obtained, by default its
AutoCommit property is set to true. This means that
every query execution is committed immediately after it
is executed and before the next one is executed. To
enable grouping of operations in transactions, you have
to switch the AutoCommit property off:
con.setAutoCommit(false) ;
Now you have to obtain new statement objects from the
connection (the old ones won't work), and query or
update as usual. When all operations that you want to
group together have completed, you must commit the
updates to the database:
con.commit() ;
At this point you can continue with more
operations which will be grouped into a new
transaction or you can switch AutoCommit back
on:
con.setAutoCommit(true) ;
anything goes wrong during a transaction (e.g.
an Exception is thrown or an error means that
you cannot complete your group of operations)
then you have to undo all operations in your
transaction so far:
con.rollBack() ;
//formservlet.java prog for database connectivity
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.http.HttpServletRequest;
public class formservlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>"); out.println("<head>"); out.println("</head>");
out.println("<body>");
String email = request.getParameter("email");
String rg = request.getParameter(“name");
try
{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:anjali","","");
Statement stmt = con.createStatement();
int rs = st.executeUpdate(“insert into directory values(“’+email+”’,”’+rg+””)”);
Out.println(“record insetred “);
Statement stmt1 = con.createStatement();
ResultSet rs1= st1.executeQuery(“select * from directory”);
While (rs1.next())
{
Out.println(“ ” + rs1.getString(“email”) + “ “ + rs1.getString(“phone”) );
Out.println(<br>);
}
Con.close();
}
out.println("</body>");
out.close(); }
• Session Tracking
HttpSession object
• Using sessions in servlets is quite
straightforward.
• involves
– looking up the session object associated with the
current request.
– creating a new session object when necessary.
– looking up information associated with a session.
– storing information in a session, and
– discarding completed or abandoned sessions.
Looking up the HttpSession object
associated with the current request.
• This is done by calling the getSession method of
HttpServletRequest. If this returns null, you can
create a new session, but this is so commonly done
that there is an option to automatically create a new
session if there isn't one already. Just pass true to
getSession.
• HttpSession session = request.getSession(true);
Looking up Information Associated
with a Session.
• HttpSession objects live on the server;
they're just automatically associated with
the requester.
• These session objects have a built-in data
structure that let you store any number of
keys and associated values
• getAttribute,
• setAttribute
Although the data that was explicitly associated with a session is the part
you care most about, there are some other pieces of information that are
sometimes useful as well.
•
getId. This method returns the unique identifier generated for each session.
It is sometimes used as the key name when there is only a single value
associated with a session, or when logging information about previous
sessions.
•
isNew. This returns true if the client (browser) has never seen the session,
usually because it was just created rather than being referenced by an
incoming client request. It returns false for preexisting sessions
•
getCreationTime. This returns the time, in milliseconds since the epoch, at
which the session was made. To get a value useful for printing out, pass the
value to the Date constructor or the setTimeInMillis method of
GregorianCalendar.
•
getLastAccessedTime. This returns the time, in milliseconds since the
epoch, at which the session was last sent from the client.
•
getMaxInactiveInterval. This returns the amount of time, in seconds, that a
session should go without access before being automatically invalidated. A
negative value indicates that the session should never timeout.
• Httpsession1.java
– last access date
• Httpsession2.java
– No of access