Servlet API life cycle methods
init(): called when servlet is instantiated; must return before any other methods will be called
service(): method called directly by server when an HTTP request is received; default service() method calls doGet() (or related methods covered later)
destroy(): called when server shuts down
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
SERVIET
1.
2. Life Cycle of Servlet
init(ServletConfig);
service(ServletRequest,
ServletResponse);
destroy();
servlet
GenericServlet HttpServlet
doGet(HttpServletRequest,
HttpServletResponse);
doPost(HttpServletRequest,
HttpServletResponse);
…….
3. 3
Servlet Life Cycle
• Servlet API life cycle methods
– init(): called when servlet is instantiated; must
return before any other methods will be called
– service(): method called directly by server
when an HTTP request is received; default
service() method calls doGet() (or related
methods covered later)
– destroy(): called when server shuts down
6. The Servlet API
• javax.servlet
– Basic servlet API definitions.
– What are the inputs and outputs to/from Servlet
– Not tied to any specific protocol (e.g., HTTP)
– These low-level classes/interfaces usually are not used
• javax.servlet.http
– HTTP-related definitions
– Extension of the basic interfaces to handle the HTTP
protocol functionality
– This package will be heavily used
7. Servlet classes
• GenericServlet class
– implements Servlet
– also implements Serializable, ServletConfig
– implements all Servlet methods
• HttpServlet class
– extends the GenericServlet class
– provides a framework for handling the HTTP protocol
– has its own subclasses of ServletRequest and
ServletResponse that do HTTP things
8. HttpServlet methods
• HTTPServlet class provides helper methods for
handling HTTP requests
– doGet (GET and HEAD)
– doPost (POST)
– doPut, doDelete (rare)
– doTrace, doOptions (not overridden)
• The service() method dispatches the requests to the
appropriate do* methods
9. Generic Servlet vs. HTTP Servlet
GenericServlet
service ( )Server
Client
HTTPServlet
service ( )HTTP
Server
Browser
request
response
doGet ( )
doPost ( )
request
response
10. ServletRequest class
• Encapsulates the clientserver communication
• Allows the Servlet access to
– Names of the parameters passed in by the client
– The protocol being used by the client
– The names of the remote host that made the request
and the server that received it
– The input stream, ServletInputStream, through which
the servlet gets data from clients
• Subclasses of ServletRequest allow the servlet to
retrieve more protocol-specific data
– HttpServletRequest for accessing HTTP-specific header
information
11. ServletRequest - Client Info
• getRemoteAddr()
– Returns the IP address of the client that sent the request
• getRemoteHost()
– Returns the fully qualified host name of the client that sent
the request
• getProtocol()
– Returns the protocol and version of the request as a string
<protocol>/<major version>.<minor version>.
12. ServletRequest - URL Info
• getScheme()
– Returns the scheme of the URL used in this request, for
example "http", "https", or "ftp".
• getServerName()
– Returns the host name of the server receiving the request
• getServerPort()
– Returns the port number on which this request was
received
• getServletPath()
– Returns the URL path that got to this script, e.g.
“/servlet/com.foo.MyServlet”
– Useful for putting in a <FORM> tag
13. ServletRequest - Contents
• getContentLength()
– Returns the size of the request data
• getContentType()
– Returns the MIME type of the request data
• getInputStream()
– Returns an input stream for reading binary data in the
request body.
• getReader()
– Returns a buffered reader for reading the request body.
14. ServletRequest - Parameters
• String getParameter(String)
– Returns a string containing one value of the specified
parameter, or null if the parameter does not exist.
• String[] getParameterValues(String)
– Returns the values of the specified parameter as an
array of strings, or null if the named parameter does not
exist.
– Useful for parameters with multiple values, like lists
• Enumeration getParameterNames()
– Returns the parameter names as an enumeration of
strings, or an empty enumeration if there are no
parameters or the input stream is empty.
15. ServletResponse class
• Encapsulates the serverclient communication
– Gives the servlet methods for replying to the client
– Allows the servlet to set the content length and MIME
type of the reply
– Provides an output stream, ServletOutputStream
through which the servlet can send the reply data
• Subclasses of ServletResponse give the servlet
more protocol-specific capabilities.
– HttpServletResponse for manipulating HTTP-specific
header information
16. ServletResponse
• Embodies the response
• Basic use:
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(
"<HTML><BODY>Hello</BODY></HTML>");
• setContentType() is usually called before calling
getWriter() or getOutputStream()
17. ServletResponse - Output
• getWriter()
– for writing text data
• getOutputStream()
– for writing binary data
– or for writing multipart MIME
• And many other methods, similarly to the methods of
ServletRequest
• Refer the documentation
18. import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServWelcome extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>First Servlet Program</TITLE></HEAD>");
out.println("<BODY>");
out.println("<H1>Welcome to Servlets</H1>");
out.println("</BODY>");
out.println("</HTML>");
out.close();
}
}
Servlet Example Servlets are not part of the standard SDK,
they are part of the J2EE
Servlets normally extend HttpServlet
Details of the HTTP request from the client
The response to be sent to the client
Set the response type to text/html (this is
normal)
This HTML text is
sent to the client
Do not forget to close the
connection with the client
19. Servlet Architecture Overview
• Servlet Interface
– methods to manage servlet
• GenericServlet
– implements Servlet
• HttpServlet
– extends GenericServlet
– exposes HTTP-specific
functionality
Servlet
extends
doGet()
doPost()
service()
...
Override one or more of:
doGet()
doPost()
service()
...
Clas
s
Interface
Class
Class
Clas
s
extendsHttpServlet
implements
GenericServlet
UserServlet
20. REQUEST METHODS
• GET- This method gets the resource at the requested
URL.
• POST- Asks the server to accept the body info attached. It
is like GET request with extra info sent with the request.
• HEAD- Asks for only the header part with no body.
• PUT- Says to put the body at the requested URL
• DELETE- Says to delete the resource at the requested URL.
• OPTIONS- Asks for a list of the HTTP methods to which
the thing at the request URL can respond.
• TRACE-Asks for the loopback of the request message
21. DIFFERENCE BETWEEN GET AND POST
GET:
• GET/test/demo_form.jsp?name1=value1&name2=value2
HTTP/1.1
• In GET method the data is exposed in the URL and only a limited
amount of data is sent. Because the data is sent in the URL.
POST:
• POST/test/demo_form.jsp HTTP/1.1
• In POST method the data is not exposed in the URL and large
amount of data is sent. Because the data is sent in the body.
22. SESSION TRACKING
• Session simply means a particular interval of time.
• Session Tracking is a way to maintain state (data) of an
user. It is also known as session management in
servlet.
• It is used to recognize the particular user.
23. SESSION TRACKING TECHNIQUE
• There are four techniques used in Session
tracking:
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
24. COOKIES
• A cookie is a small piece of information that is
persisted(client-side) between the multiple client requests.
• There are two types of cookies in servlets.
1. Non-persistent cookie
2. Persistent cookie
• javax.servlet.http.Cookie class provides the functionality
of using cookies
25. EXAMPLE
SERVLET1
public class FirstServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletRespon
se response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
//creating cookie object
Cookie ck=new Cookie("uname",n);
26. //adding cookie in the response
response.addCookie(ck);
//creating submit button
out.print("<form action='servlet2'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
}catch(Exception e){System.out.println(e);} }}
27. SERVLET2
public class SecondServlet extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletRespon
se response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();
}catch(Exception e){System.out.println(e);}}}
28. • In this example,We are storing the name of the
user in the cookie object and accessing it in
another servlet.
• As we know well that session corresponds to
the particular user.
• So if you access it from too many browsers
with different values, you will get the different
value.
29. HIDDENFIELD
• Hidden Form Field a hidden (invisible)
textfield for maintaining the state of user.
• We store the information in the hidden field
and get it from another servlet.
• To store value in hidden field
<input type="hidden" name="uname"
value=“Java">
30. EXAMPLE
SERVLET1
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
31. //creating form that have invisible textfield
out.print("<form action='servlet2'>");
out.print("<input type='hidden' name='uname'
value='"+n+"'>");
out.print("<input type='submit' value='go'>")
out.print("</form>");
out.close();
}
catch(Exception e)
{System.out.println(e);}}}
32. SERVLET2
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
/ /Getting the value from the hidden field
String n=request.getParameter("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);} } }
33. URL REWRITING
• Append a token or identifier to the URL of the next Servlet or the next
resource.
• Parameter name/value pairs can be sent using the following format:
url?name1=value1&name2=value2&??
• A name and a value is separated using an equal = sign, a parameter
name/value pair is separated from another parameter using the
ampersand(&).
34. EXAMPLE
SERVLET1
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResp
onse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
35. //appending the username in the query string
out.print("<a href='servlet2?uname="+n+"'>visit</a>");
out.close();
}catch(Exception e){System.out.println(e);} }
SERVLET2
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServl
etResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
36. //getting value from the query string
String n=request.getParameter("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e)
{
System.out.println(e);}
}
}
37. HTTP SESSION
• Container creates a session id for each user.
• The container uses this id to identify the
particular user.
• An object of HttpSession can be used to
perform two tasks:
1. bind objects
2. view and manipulate information about a session,
such as the session identifier, creation time, and last
accessed time.
38. EXAMPLE
SERVLET1
public void doGet(HttpServletRequest request, HttpServletRespo
nse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
HttpSession session=request.getSession();
session.setAttribute("uname",n);
42. What is Tomcat?
• Tomcat is a Servlet container (Web server that
interacts with Servlets)
• Tomcat implements the Servlet and the Java Server
Pages (JSP) specifications of Sun Microsystems
• Tomcat is an open-source, non commercial project
– Licensed under the Apache Software License
• Tomcat is written in Java (OS independent)
43. A Servlet Example
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("<html><head><title>Hello</title></head>");
out.println("<body>");
out.println("<h2>" + new java.util.Date() + "</h2>");
out.println("<h1>Hello World</h1></body></html>");
}
} HelloWorld.java
http://localhost/dbi/hello
44. A JSP Example
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2><%= new java.util.Date() %></h2>
<h1>Hello World</h1>
</body>
</html> hello.jsp
http://localhost/dbi/hello.jsp
45. Tomcat Directory Structure
Tomcat-Home
bin common
Tomcat-Base
webapps work
lib classesROOT myApp1 myApp2server.xml
WEB-INF
lib classesweb.xml
server sharedlogsconf
lib classes
46. Installing Tomcat
• Create a directory for tomcat base
– For example: mkdir ~/tomcat-base
• Set the environment variable CATALINA_BASE to
your tomcat-base directory
– For example: setenv CATALINA_BASE ~/tomcat-base
– Insert this line into your .cshrc file
• Run ~dbi/tomcat/bin/setup
• $CATALINA_BASE is now a regular Tomcat base
directory, and Tomcat is ready to run
47. Running Tomcat
• To start tomcat use ~dbi/tomcat/bin/catalina run
• Or, in background, ~dbi/tomcat/bin/catalina start
• To stop tomcat use ~dbi/tomcat/bin/catalina stop
• To see the default page of Tomcat from your browser
use the URL http://<machine-name>:<port>/
– machine-name is the name of the machine on which Tomcat
runs and port is the port you chose for Tomcat
• You can also use http://localhost:<port>/ if your
browser runs on the same machine as Tomcat
48.
49. Choosing a port for Tomcat
• In the file $CATALINA_HOME/conf/server.xml you
will find the element Connector of Service
“Catalina”
• Choose a port (greater than 1024) and change the
value of the port attribute to your chosen one:
<Server>
…
<Service name="Catalina”>
<Connector port="8090"/>
…
</Service>
…
</Server>
51. JDBC
What is JDBC
• The java Database Connectivity(JDBC)API is the industry standard for
database independent connectivity between the java programming
language and wide range of database.
• Java API is used to connect and execute query to the database. JDBC API
uses jdbc drivers to connects to the database.
52. Why JDBC & What is API
Why we use JDBC?
• Before JDBC, ODBC API was used to connect and execute query to the
database.
• But ODBC API uses ODBC driver that is written in C language which is
platform dependent and unsecured.
• That is why Sun Microsystem has defined its own API (JDBC API) that uses
JDBC driver written in Java language.
53. API
What is API
• API (Application programming interface) is a document that contains
description of all the features of a product or software.
• It represents classes and interfaces that software programs can follow to
communicate with each other.
• An API can be created for applications, libraries, operating systems, etc
55. JDBC Drivers
JDBC Driver is a software component that enables java application to interact
with the database.There are 4 types of JDBC drivers:
• JDBC-ODBC bridge driver
• Native-API driver (partially java driver)
• Network Protocol driver (fully java driver)
• Thin driver (fully java driver)
56. JDBC-ODBC bridge driver
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database.
The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC
function calls. This is now discouraged because of thin driver.
57. Native-API driver
• The Native API driver uses the client-side libraries of the database. The
driver converts JDBC method calls into native calls of the database API. It
is not written entirely in java.
58. Network Protocol driver
• The Network Protocol driver uses middleware (application server) that
converts JDBC calls directly or indirectly into the vendor-specific database
protocol. It is fully written in java.
59. Thin driver
• The thin driver converts JDBC calls directly into the vendor-specific
database protocol. That is why it is known as thin driver. It is fully written
in Java language.
60. RDBMS
• MySQL
• Driver Name : com.mysql.jdbc.Driver
• URL Format : jdbc:mysql://hostname/ databaseName
• ORACLE
• Driver Name : oracle.jdbc.driver.OracleDriver
• URL Format : jdbc:oracle:thin:@hostname:port Number:databaseName
61. 5 Steps to connect to the database in java
• Register the driver class
• Create the connection object
• Create the Statement object
• Execute the query
• Close the connection object
62. Register the driver class
• The forName() method of Class class is used to register the driver class. This
method is used to dynamically load the driver class.
Syntax of forName() method
• public static void forName(String className)throws
ClassNotFoundException
• Example to register the OracleDriver class
• Class.forName("oracle.jdbc.driver.OracleDriver");
63. Create the connection object
• The getConnection() method of DriverManager class is used to establish connection with the
database.
• Syntax of getConnection() method
1) public static Connection getConnection(String url)throws SQLException
2) public static Connection getConnection(String url,String name,String password) throws S
QLException.
Example to establish connection with the Oracle database
• Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");
64. Create the Statement object
• The createStatement() method of Connection interface is used to create
statement. The object of statement is responsible to execute queries with
the database.
Syntax of createStatement() method
• public Statement createStatement()throws SQLException
Example to create the statement object
• Statement stmt=con.createStatement();
65. Execute the query
• The executeQuery() method of Statement interface is used to execute queries
to the database. This method returns the object of ResultSet that can be used
to get all the records of a table.
Syntax of executeQuery() method
• public ResultSet executeQuery(String sql)throws SQLException
Example to execute query
• ResultSet rs=stmt.executeQuery("select * from emp");
• while(rs.next()){
• System.out.println(rs.getInt(1)+" "+rs.getString(2));
• }
66. Close the connection object
• By closing connection object statement and ResultSet will be closed
automatically. The close() method of Connection interface is used to close
the connection.
Syntax of close() method
• public void close()throws SQLException
Example to close connection
• con.close();
67. Statement, Prepared Statement, Callable
Statement
• Statement
• Use for general-purpose access to your database. Useful when you are
using static SQL statements at runtime. The Statement interface cannot
accept parameters.
• Prepared Statement
• Use when you plan to use the SQL statements many times. The
PreparedStatement interface accepts input parameters at runtime.
• Callable Statement
• Use when you want to access database stored procedures. The
CallableStatement interface can also accept runtime input parameters.
68. Example to Connect Java Application with
mysql database
• import java.sql.*;
• class MysqlCon{
• public static void main(String args[]){ try{
• Class.forName("com.mysql.jdbc.Driver");
• Connection con=DriverManager.getConnection(
• "jdbc:mysql://localhost:3306/sonoo","root","root");
• //here sonoo is database name, root is username and password
• Statement stmt=con.createStatement();
• ResultSet rs=stmt.executeQuery("select * from emp");
90. Example
• SQLException
• String sql= "insert into
RegistrationTable(Name,EmailId,Gender,Address,Contact,BikeName,Passw
ord)values(?,?,?,?,?,?, )";
• //java.sql.SQLException: Parameter index out of range (7 > number of
parameters, which is 6).
• ClassNotFoundException.
• public class ClassNotFoundExceptionExample {
• private static final String CLASS_TO_LOAD = "main.java.Utils";
92. • Verify that the name of the class is correct and that the
appropriate .jar file exists in your classpath. If not, you must explicitly add
it to your application’s classpath.