SlideShare ist ein Scribd-Unternehmen logo
1 von 93
Life Cycle of Servlet
init(ServletConfig);
service(ServletRequest,
ServletResponse);
destroy();
servlet
GenericServlet HttpServlet
doGet(HttpServletRequest,
HttpServletResponse);
doPost(HttpServletRequest,
HttpServletResponse);
…….
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
HelloWorld
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld 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("<body>");
out.println("<head>");
out.println("<title>Hello CS764!</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello CS764!</h1>");
out.println("</body>");
out.println("</html>");
out.close();
}
}
<html><head></head>
<body>
<a href="../servlet/HelloWorld">
<h1>Execute HelloWorld Servlet</h1>
</a>
</body>
</html>
<html>
<head>
<title>Hello CS764!</title></head>
<body>
<h1>Hello CS764!</h1>
</body>
</html>
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
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
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
Generic Servlet vs. HTTP Servlet
GenericServlet
service ( )Server
Client
HTTPServlet
service ( )HTTP
Server
Browser
request
response
doGet ( )
doPost ( )
request
response
ServletRequest class
• Encapsulates the clientserver 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
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>.
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
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.
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.
ServletResponse class
• Encapsulates the serverclient 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
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()
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
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
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
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
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.
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.
SESSION TRACKING TECHNIQUE
• There are four techniques used in Session
tracking:
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
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
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);
//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);} }}
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);}}}
• 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.
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">
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);
//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);}}}
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);} } }
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(&).
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);
//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();
//getting value from the query string
String n=request.getParameter("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e)
{
System.out.println(e);}
}
}
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.
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);
out.print("<a href='servlet2'>visit</a>");
out.close();
}catch(Exception e){System.out.println(e);} }
SERVLET2
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletRe
sponse response)
try
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
}
Apache Tomcat
Representation and Management of
Data on the Web
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)
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
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
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
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
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
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>
JDBC
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.
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.
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
JDBC Driver
• JDBC Drivers
• JDBC-ODBC Bridge Driver
• Native-API Driver
• Network Protocol Driver
• Thin Driver
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)
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.
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.
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.
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.
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
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
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");
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");
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();
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));
• }
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();
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.
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");
Insertion Operation
• String sql="insert into
RegistrationTable(Name,EmailId,Gender,Address,Contact,BikeName,Passw
ord)values(?,?,?,?,?,?,?)";
• try{
• Class.forName("com.mysql.jdbc.Driver");
• Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/Bike","root","r
oot");
• PreparedStatement pt=con.prepareStatement(sql);
• pt.setString(1,jTextField1.getText());
• pt.setString(2,jTextField2.getText());
• if(jRadioButton1.isSelected()){
• String rad_male = jRadioButton1.getText();
• pt.setString(3,rad_male);
• }else
• String rad_female = jRadioButton2.getText();
• pt.setString(3,rad_female); }
• pt.setString(4,jTextArea1.getText());
• pt.setString(5,jTextField3.getText());
• pt.setString(6,jTextField4.getText());
• pt.setString(7,jTextField5.getText());
• int n=pt.executeUpdate();
• if(n==1) {
• JOptionPane.showMessageDialog(null,"Record Inserted" );}
• else{
• JOptionPane.showMessageDialog(null,"Record Not Inserted");}
Output for insertion
Deletion Operation
• try{
• String s1=jTextField1.getText();
• String sql ="delete from registrationtable where Name = '"+s1+"'";
• Class.forName("com.mysql.jdbc.Driver");
• Connection con
=DriverManager.getConnection("jdbc:mysql://localhost/Bike","root","root
");
• PreparedStatement pt =con.prepareStatement(sql);
Cont…
• int d=pt.executeUpdate();
• if(d==1){
• JOptionPane.showMessageDialog(null,"Record Deleted"); }
• } catch(Exception ex){
• ex.printStackTrace(); }
Before Deletion
After Deletion
Here am deleting the record where BookingId = 9
Retreiving Records
• try{
• String sql="select * from registrationtable where Name= ? ";
• Class.forName("com.mysql.jdbc.Driver");
• Connection con
=DriverManager.getConnection("jdbc:mysql://localhost/Bike","root","root
");
• PreparedStatement pt = con.prepareStatement(sql);
• pt.setString(1,jTextField1.getText());
• ResultSet rs= pt.executeQuery();
Cont…
• if(rs.next()){
• String s1 =rs.getString(1);
• String s2 =rs.getString(2);
• String s3 =rs.getString(3);
• String s4 =rs.getString(4);
• String s5 =rs.getString(5);
• String s6 =rs.getString(6);
Cont…
• jTextField1.setText(s1);
• jTextField2.setText(s2);
• if(jRadioButton1.getText().contentEquals(s3)){
• jRadioButton1.setSelected(true);
• }
• else{
• jRadioButton2.setSelected(true);
• }
Cont…
• jTextArea1.setText(s4);
• jTextField3.setText(s5);
• jTextField4.setText(s6);
• }
• // this.getFrame().setResizable(false);
• }
• catch(Exception ex){
• ex.printStackTrace();
• }
Output for retrieving
Update Operation
• try{
• String s1=jTextField1.getText();
• String s2=jTextField1.getText();
• String radio="";
• if(jRadioButton1.isSelected()){
• radio=jRadioButton1.getText();}
• else{
• radio=jRadioButton2.getText(); }
• String s3= jTextArea1.getText();
Cont…
• String s4=jTextField3.getText();
• String s5=jTextField4.getText();
• String sql ="update registrationtable set
EmailId='"+s2+"',Gender='"+radio+"',Address='"+s3+"',Contact='"+s4+"',
BikeName='"+s5+"'where Name='"+s1+"'";
• Class.forName("com.mysql.jdbc.Driver");
• Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/Bike"
,"root","root");
• PreparedStatement st=con.prepareStatement(sql);
• int n=st.executeUpdate();
• if(n==1) {
• JOptionPane.showMessageDialog(null, "UPDATED SUCESSFULLY");}}
• catch(Exception ex){
• ex.printStackTrace(); }
Before updating
After Updating
Here am updated the address and contact where BookingId = 7
Exception
• SQLException.
• ClassNotFoundException.
SQLException Methods
• getErrorCode()
• getMessage()
• getSQLState()
• getNextException()
• printStackTrace()
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";
Cont…
• public static void main(String[] args) {
• try {
• Class loadedClass = Class.forName(CLASS_TO_LOAD);
• System.out.println("Class " + loadedClass + " found successfully!");}
• catch (ClassNotFoundException ex){
• System.err.println("A ClassNotFoundException was caught: " +
ex.getMessage());
• ex.printStackTrace(); }}}
• 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.
Thank you

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycle
 
Servlet/JSP course chapter 1: Introduction to servlets
Servlet/JSP course chapter 1: Introduction to servletsServlet/JSP course chapter 1: Introduction to servlets
Servlet/JSP course chapter 1: Introduction to servlets
 
Servlets
ServletsServlets
Servlets
 
Servlets
ServletsServlets
Servlets
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
Java - Servlet - Mazenet Solution
Java - Servlet - Mazenet SolutionJava - Servlet - Mazenet Solution
Java - Servlet - Mazenet Solution
 
Servlet lifecycle
Servlet lifecycleServlet lifecycle
Servlet lifecycle
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
 
Java servlets
Java servletsJava servlets
Java servlets
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Servlets
ServletsServlets
Servlets
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Servlets
ServletsServlets
Servlets
 
JEE Programming - 04 Java Servlets
JEE Programming - 04 Java ServletsJEE Programming - 04 Java Servlets
JEE Programming - 04 Java Servlets
 
Servlets
ServletsServlets
Servlets
 
Java rmi example program with code
Java rmi example program with codeJava rmi example program with code
Java rmi example program with code
 

Ähnlich wie SERVIET

Web Technologies -- Servlets 4 unit slides
Web Technologies -- Servlets   4 unit slidesWeb Technologies -- Servlets   4 unit slides
Web Technologies -- Servlets 4 unit slidesSasidhar Kothuru
 
J2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentJ2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentjoearunraja2
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.pptkstalin2
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteTushar B Kute
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdfArumugam90
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servletssbd6985
 
Integrating Servlets and JSP (The MVC Architecture)
Integrating Servlets and JSP  (The MVC Architecture)Integrating Servlets and JSP  (The MVC Architecture)
Integrating Servlets and JSP (The MVC Architecture)Amit Ranjan
 
SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4Ben Abdallah Helmi
 
SCWCD : The servlet model : CHAP : 2
SCWCD  : The servlet model : CHAP : 2SCWCD  : The servlet model : CHAP : 2
SCWCD : The servlet model : CHAP : 2Ben Abdallah Helmi
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/ServletSunil OS
 
Lecture 2: Servlets
Lecture 2:  ServletsLecture 2:  Servlets
Lecture 2: ServletsFahad Golra
 
SCWCD : The servlet model CHAP : 2
SCWCD : The servlet model CHAP : 2SCWCD : The servlet model CHAP : 2
SCWCD : The servlet model CHAP : 2Ben Abdallah Helmi
 

Ähnlich wie SERVIET (20)

Web Technologies -- Servlets 4 unit slides
Web Technologies -- Servlets   4 unit slidesWeb Technologies -- Servlets   4 unit slides
Web Technologies -- Servlets 4 unit slides
 
J2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentJ2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environment
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Servlet1.ppt
Servlet1.pptServlet1.ppt
Servlet1.ppt
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdf
 
Servlets
ServletsServlets
Servlets
 
Servlet
ServletServlet
Servlet
 
servlet_lifecycle.pdf
servlet_lifecycle.pdfservlet_lifecycle.pdf
servlet_lifecycle.pdf
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
Integrating Servlets and JSP (The MVC Architecture)
Integrating Servlets and JSP  (The MVC Architecture)Integrating Servlets and JSP  (The MVC Architecture)
Integrating Servlets and JSP (The MVC Architecture)
 
SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4
 
SCWCD : The servlet model : CHAP : 2
SCWCD  : The servlet model : CHAP : 2SCWCD  : The servlet model : CHAP : 2
SCWCD : The servlet model : CHAP : 2
 
W3 C11
W3 C11W3 C11
W3 C11
 
Basics Of Servlet
Basics Of ServletBasics Of Servlet
Basics Of Servlet
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Lecture 2: Servlets
Lecture 2:  ServletsLecture 2:  Servlets
Lecture 2: Servlets
 
Servlet11
Servlet11Servlet11
Servlet11
 
SCWCD : The servlet model CHAP : 2
SCWCD : The servlet model CHAP : 2SCWCD : The servlet model CHAP : 2
SCWCD : The servlet model CHAP : 2
 

Mehr von sathish sak

TRANSPARENT CONCRE
TRANSPARENT CONCRETRANSPARENT CONCRE
TRANSPARENT CONCREsathish sak
 
Stationary Waves
Stationary WavesStationary Waves
Stationary Wavessathish sak
 
Electrical Activity of the Heart
Electrical Activity of the HeartElectrical Activity of the Heart
Electrical Activity of the Heartsathish sak
 
Electrical Activity of the Heart
Electrical Activity of the HeartElectrical Activity of the Heart
Electrical Activity of the Heartsathish sak
 
Software process life cycles
Software process life cyclesSoftware process life cycles
Software process life cycles sathish sak
 
Digital Logic Circuits
Digital Logic CircuitsDigital Logic Circuits
Digital Logic Circuitssathish sak
 
Real-Time Scheduling
Real-Time SchedulingReal-Time Scheduling
Real-Time Schedulingsathish sak
 
Real-Time Signal Processing: Implementation and Application
Real-Time Signal Processing:  Implementation and ApplicationReal-Time Signal Processing:  Implementation and Application
Real-Time Signal Processing: Implementation and Applicationsathish sak
 
DIGITAL SIGNAL PROCESSOR OVERVIEW
DIGITAL SIGNAL PROCESSOR OVERVIEWDIGITAL SIGNAL PROCESSOR OVERVIEW
DIGITAL SIGNAL PROCESSOR OVERVIEWsathish sak
 
FRACTAL ROBOTICS
FRACTAL  ROBOTICSFRACTAL  ROBOTICS
FRACTAL ROBOTICSsathish sak
 
POWER GENERATION OF THERMAL POWER PLANT
POWER GENERATION OF THERMAL POWER PLANTPOWER GENERATION OF THERMAL POWER PLANT
POWER GENERATION OF THERMAL POWER PLANTsathish sak
 
mathematics application fiels of engineering
mathematics application fiels of engineeringmathematics application fiels of engineering
mathematics application fiels of engineeringsathish sak
 
ENVIRONMENTAL POLLUTION
ENVIRONMENTALPOLLUTIONENVIRONMENTALPOLLUTION
ENVIRONMENTAL POLLUTIONsathish sak
 

Mehr von sathish sak (20)

TRANSPARENT CONCRE
TRANSPARENT CONCRETRANSPARENT CONCRE
TRANSPARENT CONCRE
 
Stationary Waves
Stationary WavesStationary Waves
Stationary Waves
 
Electrical Activity of the Heart
Electrical Activity of the HeartElectrical Activity of the Heart
Electrical Activity of the Heart
 
Electrical Activity of the Heart
Electrical Activity of the HeartElectrical Activity of the Heart
Electrical Activity of the Heart
 
Software process life cycles
Software process life cyclesSoftware process life cycles
Software process life cycles
 
Digital Logic Circuits
Digital Logic CircuitsDigital Logic Circuits
Digital Logic Circuits
 
Real-Time Scheduling
Real-Time SchedulingReal-Time Scheduling
Real-Time Scheduling
 
Real-Time Signal Processing: Implementation and Application
Real-Time Signal Processing:  Implementation and ApplicationReal-Time Signal Processing:  Implementation and Application
Real-Time Signal Processing: Implementation and Application
 
DIGITAL SIGNAL PROCESSOR OVERVIEW
DIGITAL SIGNAL PROCESSOR OVERVIEWDIGITAL SIGNAL PROCESSOR OVERVIEW
DIGITAL SIGNAL PROCESSOR OVERVIEW
 
FRACTAL ROBOTICS
FRACTAL  ROBOTICSFRACTAL  ROBOTICS
FRACTAL ROBOTICS
 
Electro bike
Electro bikeElectro bike
Electro bike
 
ROBOTIC SURGERY
ROBOTIC SURGERYROBOTIC SURGERY
ROBOTIC SURGERY
 
POWER GENERATION OF THERMAL POWER PLANT
POWER GENERATION OF THERMAL POWER PLANTPOWER GENERATION OF THERMAL POWER PLANT
POWER GENERATION OF THERMAL POWER PLANT
 
mathematics application fiels of engineering
mathematics application fiels of engineeringmathematics application fiels of engineering
mathematics application fiels of engineering
 
Plastics…
Plastics…Plastics…
Plastics…
 
ENGINEERING
ENGINEERINGENGINEERING
ENGINEERING
 
ENVIRONMENTAL POLLUTION
ENVIRONMENTALPOLLUTIONENVIRONMENTALPOLLUTION
ENVIRONMENTAL POLLUTION
 
RFID TECHNOLOGY
RFID TECHNOLOGYRFID TECHNOLOGY
RFID TECHNOLOGY
 
green chemistry
green chemistrygreen chemistry
green chemistry
 
NANOTECHNOLOGY
  NANOTECHNOLOGY	  NANOTECHNOLOGY
NANOTECHNOLOGY
 

Kürzlich hochgeladen

Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...masabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxAnnaArtyushina1
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Bert Jan Schrijver
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
tonesoftg
tonesoftgtonesoftg
tonesoftglanshi9
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburgmasabamasaba
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 

Kürzlich hochgeladen (20)

Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%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
  • 4. HelloWorld import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld 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("<body>"); out.println("<head>"); out.println("<title>Hello CS764!</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Hello CS764!</h1>"); out.println("</body>"); out.println("</html>"); out.close(); } }
  • 5. <html><head></head> <body> <a href="../servlet/HelloWorld"> <h1>Execute HelloWorld Servlet</h1> </a> </body> </html> <html> <head> <title>Hello CS764!</title></head> <body> <h1>Hello CS764!</h1> </body> </html>
  • 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 clientserver 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 serverclient 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);
  • 39. out.print("<a href='servlet2'>visit</a>"); out.close(); }catch(Exception e){System.out.println(e);} } SERVLET2 public class SecondServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletRe sponse response) try { response.setContentType("text/html"); PrintWriter out = response.getWriter();
  • 41. Apache Tomcat Representation and Management of Data on the Web
  • 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>
  • 50. JDBC
  • 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
  • 54. JDBC Driver • JDBC Drivers • JDBC-ODBC Bridge Driver • Native-API Driver • Network Protocol Driver • Thin Driver
  • 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");
  • 69. Insertion Operation • String sql="insert into RegistrationTable(Name,EmailId,Gender,Address,Contact,BikeName,Passw ord)values(?,?,?,?,?,?,?)"; • try{ • Class.forName("com.mysql.jdbc.Driver"); • Connection con=DriverManager.getConnection("jdbc:mysql://localhost/Bike","root","r oot");
  • 70. • PreparedStatement pt=con.prepareStatement(sql); • pt.setString(1,jTextField1.getText()); • pt.setString(2,jTextField2.getText()); • if(jRadioButton1.isSelected()){ • String rad_male = jRadioButton1.getText();
  • 71. • pt.setString(3,rad_male); • }else • String rad_female = jRadioButton2.getText(); • pt.setString(3,rad_female); } • pt.setString(4,jTextArea1.getText()); • pt.setString(5,jTextField3.getText()); • pt.setString(6,jTextField4.getText()); • pt.setString(7,jTextField5.getText());
  • 72. • int n=pt.executeUpdate(); • if(n==1) { • JOptionPane.showMessageDialog(null,"Record Inserted" );} • else{ • JOptionPane.showMessageDialog(null,"Record Not Inserted");}
  • 74. Deletion Operation • try{ • String s1=jTextField1.getText(); • String sql ="delete from registrationtable where Name = '"+s1+"'"; • Class.forName("com.mysql.jdbc.Driver"); • Connection con =DriverManager.getConnection("jdbc:mysql://localhost/Bike","root","root "); • PreparedStatement pt =con.prepareStatement(sql);
  • 75. Cont… • int d=pt.executeUpdate(); • if(d==1){ • JOptionPane.showMessageDialog(null,"Record Deleted"); } • } catch(Exception ex){ • ex.printStackTrace(); }
  • 77. After Deletion Here am deleting the record where BookingId = 9
  • 78. Retreiving Records • try{ • String sql="select * from registrationtable where Name= ? "; • Class.forName("com.mysql.jdbc.Driver"); • Connection con =DriverManager.getConnection("jdbc:mysql://localhost/Bike","root","root "); • PreparedStatement pt = con.prepareStatement(sql); • pt.setString(1,jTextField1.getText()); • ResultSet rs= pt.executeQuery();
  • 79. Cont… • if(rs.next()){ • String s1 =rs.getString(1); • String s2 =rs.getString(2); • String s3 =rs.getString(3); • String s4 =rs.getString(4); • String s5 =rs.getString(5); • String s6 =rs.getString(6);
  • 80. Cont… • jTextField1.setText(s1); • jTextField2.setText(s2); • if(jRadioButton1.getText().contentEquals(s3)){ • jRadioButton1.setSelected(true); • } • else{ • jRadioButton2.setSelected(true); • }
  • 81. Cont… • jTextArea1.setText(s4); • jTextField3.setText(s5); • jTextField4.setText(s6); • } • // this.getFrame().setResizable(false); • } • catch(Exception ex){ • ex.printStackTrace(); • }
  • 83. Update Operation • try{ • String s1=jTextField1.getText(); • String s2=jTextField1.getText(); • String radio=""; • if(jRadioButton1.isSelected()){ • radio=jRadioButton1.getText();} • else{ • radio=jRadioButton2.getText(); } • String s3= jTextArea1.getText();
  • 84. Cont… • String s4=jTextField3.getText(); • String s5=jTextField4.getText(); • String sql ="update registrationtable set EmailId='"+s2+"',Gender='"+radio+"',Address='"+s3+"',Contact='"+s4+"', BikeName='"+s5+"'where Name='"+s1+"'"; • Class.forName("com.mysql.jdbc.Driver"); • Connection con=DriverManager.getConnection("jdbc:mysql://localhost/Bike" ,"root","root");
  • 85. • PreparedStatement st=con.prepareStatement(sql); • int n=st.executeUpdate(); • if(n==1) { • JOptionPane.showMessageDialog(null, "UPDATED SUCESSFULLY");}} • catch(Exception ex){ • ex.printStackTrace(); }
  • 87. After Updating Here am updated the address and contact where BookingId = 7
  • 89. SQLException Methods • getErrorCode() • getMessage() • getSQLState() • getNextException() • printStackTrace()
  • 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";
  • 91. Cont… • public static void main(String[] args) { • try { • Class loadedClass = Class.forName(CLASS_TO_LOAD); • System.out.println("Class " + loadedClass + " found successfully!");} • catch (ClassNotFoundException ex){ • System.err.println("A ClassNotFoundException was caught: " + ex.getMessage()); • ex.printStackTrace(); }}}
  • 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.