SlideShare a Scribd company logo
1 of 170
Download to read offline
Pune Vidyarthi Griha’s
COLLEGE OF ENGINEERING, NASHIK
“SERVER SIDE
TECHNOLOGYIES”
By
Prof. Anand N. Gharu
(Assistant Professor)
PVGCOE Computer Dept.
18 Jan 2020Note: Thematerial to preparethis presentation hasbeentaken from internet andare generatedonly
for students referenceandnot for commercialuse.
Outline
Introduction to Server Side technology and TOMCAT,
Servlet: Introduction to Servlet, need and advantages, Servlet
Lifecycle, Creating and testing of sample Servlet, session
management.
JSP: Introduction to JSP, advantages of JSP over Servlet ,
elements of JSP page: directives, comments, scripting
elements, actions and templates, JDBC Connectivity with JSP.
Servlets & Tomcat
OutLine
Servlet Introduction
Servlet Lifecycle
Servlet Architecture
Software Requirement to run Servlet
Tomcat Introduction
Tomcat Configuration in Eclipse
Steps to run servlets in Eclipse
Sample code
Session Management
What areServlets?
• Servlet is server side java application which is used to create
dynamic web pages.
• Java Servlets are programs that run on a Web or Application
server and act as a middle layer between a requests coming from a
Web browser or other HTTP client and databases or applications
on the HTTP server.
• Using Servlets, you can collect input from users through web page
forms, present records from a database or another source, and
create web pages dynamically.
Client vs Server side Scripting
Client vs Server side technology
Servlet vs CGI
Advantages of Servlet overCGI
• Portability
• Powerful
• Efficiency
• Safety
• Integration
• Extensibility
• Inexpensive
• Secure
• performance
Advantages of Servlet overCGI
• Performance is significantly better.
• Servlets execute within the address space of a Web server. It is not
necessary to create a separate process to handle each client request.
• Servlets are platform-independent because they are written in Java.
• servlets are trusted.
• The full functionality of the Java class libraries is available to a servlet.
• Invocation or calling of servlet is highly efficient than CGI
• Servlet can handle number of complex task which were difficult for
CGI.
Advantages of Servlet overCGI
Advantages of Servlet overCGI
ServletsArchitecture
ServletsPackages
• Java Servlets are Java classes run by a web server that has an
interpreter that supports the Java Servlet specification.
• Servlets can be created using the packages
• javax.servlet
• javax.servlet.http
OutLine
Servlet Introduction
Servlet Lifecycle
Servlet Architecture
Software Requirement to run Servlet
Tomcat Introduction
Tomcat Configuration in Eclipse
Steps to run servlets in Eclipse
Sample code
Servlet LifeCycle
• Load Servlet
• Create servlet instance
• Call init ( ) once
• Call service ( )
• Call destroy ( ) once
Servlet LifeCycle
• The servlet is initialized by calling the init() method.
• The servlet calls service() method to process a client's request.
• The servlet is terminated by calling the destroy() method.
• Finally, servlet is garbage collected by the garbage collector of
the JVM.
The init( )Method
• The init method is called only once. It is called only when the servlet is
created, and not called for any user requests afterwards.
• So, it is used for one-time initializations.
• When a user invokes a servlet, a single instance of each servlet gets created,
with each user request resulting in a new thread that is handed off to doGet or
doPost as appropriate.
• The init() method simply creates or loads some data that will be used
throughout the life of the servlet.
• The init method definition looks like this −
public void init() throws ServletException {
// Initialization code...
}
The service( )Method
• The service() method is the main method to perform the actual task. The
servlet container (i.e. web server) calls the service() method to handle
requests coming from the client( browsers) and to write the formatted
response back to the client.
• When server receives a request for a servlet, the service() method
checks the HTTP request type (GET, POST) and calls doGet, doPost,
methods as appropriate.
• Here is the signature of this method −
• public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException { }
The doGet()Method
• A GET request results from a normal request for a URL or from an
HTML form that has no METHOD specified and it should be
handled by doGet() method.
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
The doPost()Method
• A POST request results from an HTML form that specifically lists
POST as the METHOD and it should be handled by doPost()
method.
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
The destroy()Method
• The destroy() method is called only once at the end of the life
cycle of a servlet.SS
• This method gives your servlet a chance to close database
connections, halt background threads, and perform other such
cleanup activities.
• After the destroy() method is called, the servlet object is
marked for garbage collection.
• The destroy method definition looks like this −
public void destroy() {
// Finalization code...}
doget VS dopost
doget VS dopost
OutLine
Servlet Introduction
Servlet Lifecycle
Servlet Architecture
Software Requirement to run Servlet
Tomcat Introduction
Tomcat Configuration in Eclipse
Steps to run servlets in Eclipse
Sample code
Session Management
ArchitectureDiagram
• First the HTTP requests coming to the
server are delegated to the servlet
container.
• The servlet container loads the servlet
before invoking the service()S method.
• Then the servlet container handles
multiple requests by spawning multiple
threads, each thread executing the
service() method of a single instance
of the servlet.
OutLine
Servlet Introduction
Servlet Lifecycle
Servlet Architecture
Software Requirement to run Servlet
Tomcat Introduction
Tomcat Configuration in Eclipse
Steps to run servlets in Eclipse
Sample code
Session Management
Requirements
Before running Servlet your
machine requires following tools
• 1> Eclipse (IDE-integrated development environment)
• 2> Tomcat (Web Server)
OutLine
Servlet Introduction
Servlet Lifecycle
Servlet Architecture
Software Requirement to run Servlet
Tomcat Introduction
Tomcat Configuration in Eclipse
Steps to run servlets in Eclipse
Sample code
Session Management
Apache-Tomcat
• Apache Tomcat, often referred to as Tomcat Server, is an open-source
Java Servlet Container developed by the Apache Software Foundation
(ASF).
• Tomcat implements several Java EE specifications including Java
Servlet, JavaServer Pages (JSP), Java EL, and WebSocket, and
provides a "pure Java" HTTP web server environment in which Java
code can run.
Tomcat-Components
Catalina
Coyote
Jasper
Cluster
High availability
Web application
Tomcat-Components
Catalina
• Catalina is Tomcat's servlet container.
• Catalina implements Sun Microsystems's specifications for servlet and
JavaServer Pages (JSP).
• In Tomcat, a Realm element represents a "database" of
usernames, passwords, and roles assigned to those users.
• Catalina to be integrated into environments where such authentication
information is already being created and maintained, and then use that
information to implement Container Managed Security as described
in the Servlet Specification.
Tomcat-Components
Coyote
• Coyote is a Connector component for Tomcat that supports the HTTP
1.1 protocol as a web server.
• This allows Catalina, nominally a Java Servlet or JSP container, to also
act as a plain web server that serves local files as HTTP documents.
• Coyote listens for incoming connections to the server on a specific TCP
port and forwards the request to the Tomcat Engine to process the
request and send back a response to the requesting client.
Tomcat-Components
Jasper
• Jasper is Tomcat's JSP Engine.
• Jasper parses JSP files to compile them into Java code as servlets (that can
be handled by Catalina). At runtime, Jasper detects changes to JSP files and
recompiles them.
• From Jasper to Jasper 2, important features were added:
• JSP Tag library pooling - Each tag markup in JSP file is handled by a tag handler
class.
• Background JSP compilation - While recompiling modified JSP Java code, the
older version is still available for server requests.
• Recompile JSP when included page changes - Pages can be inserted and
included into a JSP at runtime
• JDT Java compiler - Jasper 2 can use the Eclipse JDT Java compiler
Tomcat-Components
• These components are added from Tomcat 7.0 version
• Cluster
• This component has been added to manage large applications.
• High availability
• A high-availability feature has been added to facilitate the
scheduling of system upgrades (e.g. new releases, change
requests) without affecting the live environment.
• Web application
• It has also added user- as well as system-based web applications
enhancement to add support for deployment across the variety of
environments.
OutLine
Servlet Introduction
Servlet Lifecycle
Servlet Architecture
Software Requirement to run Servlet
Tomcat Introduction
Tomcat Configuration in Eclipse
Steps to run servlets in Eclipse
Sample code
Session Management
Howtoconfiguretomcatserverin
Eclipse ?(One time Requirement)
• If you are using Eclipse IDE first time, you need to configure the
tomcat server First.
S
• For configuring the tomcat server in eclipse IDE,
• click on servers tab at the bottom side of the IDE -> right click on
blank area -> New -> Servers -> choose tomcat then its version ->
next -> click on Browse button -> select the apache tomcat root
folder previous to bin -> next -> addAll -> Finish.
How to configuretomcat
server in Eclipse?
How to configuretomcat
server in Eclipse?
How to configuretomcat
server in Eclipse?
How to configuretomcat
server in Eclipse?
How to configuretomcat
server in Eclipse?
How to configuretomcat
server in Eclipse?
How to configuretomcat
server in Eclipse?
How to configuretomcat
server in Eclipse?
OutLine
Servlet Introduction
Servlet Lifecycle
Servlet Architecture
Software Requirement to run Servlet
Tomcat Introduction
Tomcat Configuration in Eclipse
Steps to run servlets in Eclipse
Sample code
Session Management
Steps to run servlet in Eclipse
Create a Dynamic web project
create a servlet
add servlet-api.jar file
Run the servlet
Steps to run servlet in Eclipse
Create a Dynamic web project
create a servlet
add servlet-api.jar file
Run the servlet
Create the dynamic webproject
Start Eclipse and In Menu : File -> New -> Dynamic Web Project
Create the dynamic webproject
Create the dynamic webproject
Create the dynamic webproject
Create the dynamic webproject
Structure of Dynamic Web Project
Steps to run servlet in Eclipse
Create a Dynamic web project
create a servlet
add servlet-api.jar file
Run the servlet
Create aservlet
Right click on Src -> New -> Sevlet
Create aservlet
Give name of class
Create aservlet
Create aservlet
Either select doGet ordoPost
Create aservlet
Servlet is created, you can write the code now.
Steps to run servlet in Eclipse
Create a Dynamic web project
create a servlet
add servlet-api.jar file
Run the servlet
Add servlet-api.jar
file
Add servlet-api.jarfile
Add servlet-api.jarfile
In Tomcat folder goto Lib folder and select servlet-api.jarfile
Add servlet-api.jarfile
Steps to run servlet in Eclipse
Create a Dynamic web project
create a servlet
add servlet-api.jar file
Run the servlet
Run theservlet
Right click on project name -> click Run As -> Run on Server
Run theservlet
Run theservlet
OutLine
Servlet Introduction
Servlet Lifecycle
Servlet Architecture
Software Requirement to run Servlet
Tomcat Introduction
Tomcat Configuration in Eclipse
Steps to run servlets in Eclipse
Sample code
Session Management
Example1-
ToPrint Hello Worlddirectly
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
public void init() throws ServletException { }
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1> Hello World </h1>");
}
public void destroy() { }
}
Example 2-
ToPrintHelloWorld using initmethod
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
private String message;
public void init() throws ServletException
{ message = "Hello World"; }
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>"); }
public void destroy() { }
}
Reading Form Data usingServlet
• getParameter() − You call request.getParameter() method to get
the value of a form parameter.
• getParameterValues() − Call this method if the parameter
appears more than once and returns multiple values, for
example checkbox.
• getParameterNames() − Call this method if you want a
complete list of all parameters in the current request.
Example3-
ToreaddatafromHTMLfileandprintthat.
• It requires 2 files:
• 1. HTML (s1.html)File
• 2. Servlet (s2.java) File
• First Run HTML file and after clicking on submit button it will
run servel(.java) file.
Example3-
ToreaddatafromHTMLfileandprintthat.
• S1.html (html code)
<html>
<form method=“post” action=“s2”>
Enter Your Name
<input type=text name=“t1”>
<br>
<input type=“submit” value=“submit”>
</form>
</body>
</html>
Example3-
ToreaddatafromHTMLfileandprintthat.
• S2.java (Servlet Code)
import java.io.*;
import javax.servlet.*;
public class s2 extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
response.setContentType("text/html");
String a= request.getParameter("t1");
PrintWriter out= response.getWriter();
out.print("<br>Your Name is: "+a);
}
}
Example 4–(HTML code)
ToreaddatafromHTMLcheckboxvaluesprintthat
• <!DOCTYPE html>
• <html>
• <body>
• <form method="post" action=s1>
• Hobbies
• <input type="checkbox" name="t1" value=“Cricket"> Cricket
• <input type="checkbox" name="t1" value="Music">Music
• <input type="checkbox" name="t1" value=“Dance">Dance
• <input type="submit" value="submit">
• </form>
• </body>
• </html>
Name of Servlet File
Example 4–(servlet code)
ToreaddatafromHTMLcheckboxvaluesprintthat
• protected void doPost(HttpServletRequest request,
HttpServletResponse response)
• throws ServletException, IOException {
• response.setContentType("text/html");
• PrintWriter out=response.getWriter();
• String[] values=request.getParameterValues("t1");
•
• for(int i=0;i<values.length;i++)
• {
• out.println("<li>"+values[i]+"</li>");
• }
• }
• }
Example 5–(HTML code)
Toprintcompletelistofallparameters
• <!DOCTYPE html>
• <html>
• <body>
• <form method="post" action=s1>
• Hobbies
• Enter Name <input type=“text" name="t1" > <br>
• Enter Address <input type=“text" name="t2" > <br>
• Enter Class <input type=“text" name="t3" > <br>
• <input type="submit" value="submit">
• </form>
• </body>
• </html>
Example 5 –(Servletcode)
Toprintcompletelistofallparameters
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Enumeration e = request.getParameterNames();
while(e.hasMoreElements())
{
Object obj = e.nextElement();
out.println((String) obj+ "<br>");
}
}
OutLine
Servlet Introduction
Servlet Lifecycle
Servlet Architecture
Software Requirement to run Servlet
Tomcat Introduction
Tomcat Configuration in Eclipse
Steps to run servlets in Eclipse
Sample code
Session Management
Session Tracking(Management)
• Session Tracking is a way to maintain state (data) of an user. It is also
known as session management in servlet.
• Http protocol is a stateless so we need to maintain state using session
tracking techniques.
• Each time user requests to the server, server treats the request as
the new request.
• So we need to maintain the state of an user to recognize to particular
user.
• Why use Session Tracking?
• To recognize the user It is used to recognize the particular user.
Session TrackingTechniques
Cookies
Hidden Form Field
URL Rewriting
HttpSession
Session Tracking-UsingCookies
• A cookie is a small piece of information that is persisted
between the multiple client requests.
• A cookie has a name, a single value, and optional attributes such as a
comment, path and domain qualifiers, a maximum age, and a version
number.
• How Cookie works
• In cookies technique, we add cookie with response from the servlet. So
cookie is stored in the cache of the browser. After that if request is sent by
the user, cookie is added with request by default. Thus, we recognize the
user as the old user.
Session Tracking-UsingCookies
• Types of Cookie
• Non-persistent cookie
• Persistent cookie
• Non-persistent cookie
• It is valid for single session only. It is removed each time when
user closes the browser.
• Persistent cookie
• It is valid for multiple session . It is not removed each time when
user closes the browser. It is removed only if user logout or
signout.
Session Tracking-UsingCookies
• Advantage of Cookies
• Simplest technique of maintaining the state.
• Cookies are maintained at client side.
• Disadvantage of Cookies
• It will not work if cookie is disabled from the browser.
• Only textual information can be set in Cookie object.
Session Tracking-UsingCookies
Method Description
public void setMaxAge(int expiry)
Sets the maximum age of the cookie in
seconds.
public String getName()
Returns the name of the cookie. The
name cannot be changed after
creation.
public String getValue() Returns the value of the cookie.
public void setName(String name) changes the name of the cookie.
public void setValue(String value) changes the value of the cookie.
Useful Methods of Cookie class
Session Tracking-UsingCookies
• How to create Cookie?
• Cookie ck=new Cookie("user","sonu");//creating cookie object
• response.addCookie(ck);//adding cookie in the response
• How to delete Cookie?
• Cookie ck=new Cookie("user","");//deleting value of cookie
• ck.setMaxAge(0);//changing the maximum age to 0 seconds
• response.addCookie(ck);//adding cookie in the response
• How to get Cookies?
• Cookie ck[]=request.getCookies();
• for(int i=0;i<ck.length;i++){
• out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing na
me and value of cookie
• }
Session Tracking-UsingCookies
SimpleexampleofServletCookies
Session Tracking-UsingCookies
SimpleexampleofServletCookies
• index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
Session Tracking-UsingCookies
SimpleexampleofServletCookies
Servlet1.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
Cookie ck=new Cookie("uname",n);//creating cookie object
response.addCookie(ck);//adding cookie in the response
//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);}
}
}
Session Tracking-UsingCookies
SimpleexampleofServletCookies
Servlet2.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse 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);}
}
}
Session TrackingTechniques
Cookies
Hidden Form Field
URL Rewriting
HttpSession
SessionTracking-Hidden Form Fields
• In case of Hidden Form Field a hidden (invisible) textfield is
used for maintaining the state of an user.
• In such case, we store the information in the hidden field and
get it from another servlet.
• Synax
• <input type="hidden" name="uname" value=“Bhavana">
• Here, uname is the hidden field name and Bhavana is the
hidden field value.
SessionTracking-Hidden Form Fields
• Advantage of Hidden Form Field
• It will always work whether cookie is disabled or not.
• Disadvantage of Hidden Form Field:
• It is maintained at server side.
• Extra form submission is required on each pages.
• Only textual information can be used.
SessionTracking-Hidden Form Fields
Example of passingusername
SessionTracking-Hidden Form Fields
Example of passingusername
• index.html
<form method="post" action=“First">
Name:<input type="text" name="user" /><br/>
Password:<input type="text" name="pass" ><br/>
<input type="submit" value="submit">
</form>
SessionTracking-Hidden Form Fields
Example of passingusername
• First.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class First extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String user = request.getParameter("user");
//creating a new hidden form field
out.println("<form action='Second'>");
out.println("<input type='hidden' name='user' value='"+user+"'>");
out.println("<input type='submit' value='submit' >");
out.println("</form>");
}
}
SessionTracking-Hidden Form Fields
Example of passingusername
• Second.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Second extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
//getting parameter from the hidden field
String user = request.getParameter("user");
out.println("Welcome "+user);
}
}
Session TrackingTechniques
Cookies
Hidden Form Field
URL Rewriting
HttpSession
Session Tracking-URLRewriting
• If the client has disabled cookies in the browser then session
management using cookie wont work.
• In that case URL Rewriting can be used as a backup. URL
rewriting will always work.
• In URL rewriting, a token(parameter) is added at the end of the
URL.
• The token consist of name/value pair separated by an equal(=)
sign.
• For Example:
Session Tracking-URLRewriting
• When the User clicks on the URL having parameters, the
request goes to the Web Container with extra bit of
information at the end of URL.
• The Web Container will fetch the extra part of the requested
URL and use it for session management.
• The getParameter() method is used to get the parameter
value at the server side.
• Advantage of URL Rewriting
• It will always work whether cookie is disabled or not (browser
independent).
• Extra form submission is not required on each pages.
• Disadvantage of URL Rewriting
• It will work only with links.
• It can send only textual information.
Session Tracking-URLRewriting
Example
• index.html
• <form method="post" action="validate">
• Name:<input type="text" name="user" /><br/>
• Password:<input type="text" name="pass" ><br/>
• <input type="submit" value="submit">
• </form>
Session Tracking-URLRewriting
Example
• Validate.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String name = request.getParameter("user");
String pass = request.getParameter("pass");
if(pass.equals("1234")) {
response.sendRedirect("First?user_name="+name+"");
}
}
}
Session Tracking-URLRewriting
Example
• First.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class First extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String user = request.getParameter("user_name");
out.println("Welcome "+user);
}
}
Session TrackingTechniques
Cookies
Hidden Form Field
URL Rewriting
HttpSession
Session Tracking- HttpSession
• The servlet container uses this interface to create a session
between an HTTP client and an HTTP server.
• The session persists for a specified time period, across more
than one connection or page request from the user.
• You would get HttpSession object by calling the public method
getSession() of HttpServletRequest, as below −
HttpSession session = request.getSession();
SessionTracking- HttpSession
• How to get the HttpSession object ?
• public HttpSession getSession():Returns the current session
associated with this request, or if the request does not have a
session, creates one.
• Commonly used methods of HttpSession interface
• public String getId():Returns unique identifiervalue.
• public long getCreationTime():Returns the time when this
session was created.
• public long getLastAccessedTime():Returns the last time the
client sent a request associated with thissession.
• public void invalidate():Invalidates this session then unbinds
any objects bound to it.
Session Tracking-HttpSession
Example HitCount
• HTML File
<h3>Hit Count Example with HttpSession</h3>
<form method="get" action=“HitCount">
Click for Hit Count
<input type="submit" value="GET HITS">
</form>
</body>
Session Tracking-HttpSession
Example HitCount
public class HitCount extends HttpServlet
{ public void service(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException {
res.setContentType("text/html") ;
PrintWriter out = res.getWriter( );
HttpSession session = req.getSession();
Integer hitNumber = (Integer) session.getAttribute("rama");
if (hitNumber == null) { hitNumber = new Integer(1); }
else { hitNumber = new Integer(hitNumber.intValue()+1) ; }
session.setAttribute("rama", hitNumber); // storing the value with session object
out.println("Your Session ID: " + session.getId()); // never changes in the whole session
out.println("<br>Session Creation Time: " + new Date(session.getCreationTime()));
out.println("<br>Time of Last Access: " + new Date(session.getLastAccessedTime()));
out.println("<br>Latest Hit Count: " + hitNumber); // increments by 1 for every hit
Session Tracking-HttpSession
ExampleHitCountoutput
JSP
Outline
Introduction to JSP
Advantages of JSP over Servlet
JSP Life cycle
JSP Creation in Eclipse
Elements of JSP page: directives, comments, scripting elements, actions
and templates
JDBC Connectivity with JSP.
Outline
Introduction to JSP
Advantages of JSP over Servlet
JSP Life cycle
JSP Creation in Eclipse
Elements of JSP page: directives, comments, scripting elements, actions
and templates
JDBC Connectivity with JSP.
Introduction toJSP
• JSP technology is used to create web application just like Servlet
technology.
• It can be thought of as an extension to servlet because it provides
more functionality than servlet such as expression language, jstl etc.
• A JSP page consists of HTML tags and JSP tags.
• The jsp pages are easier to maintain than servlet because we can
separate designing and development.
• It provides some additional features such as Expression
Language, Custom Tag etc.
Advantages ofJSP
• vs. Active Server Pages (ASP)
• The advantages of JSP are twofold.
• First, the dynamic part is written in Java, not Visual Basic or other MS
specific language, so it is more powerful and easier to use.
• Second, it is portable to other operating systems and non-
Microsoft Web servers.
• vs. JavaScript
• JavaScript can generate HTML dynamically on the client but can hardly
interact with the web server to perform complex tasks like database
access and image processing etc.
Advantage of JSP overServlet• 1) Extension to Servlet
• JSP technology is the extension to servlet technology. We can use all the
features of servlet in JSP. In addition to, we can use implicit objects,
predefined tags, expression language and Custom tags in JSP, that makes JSP
development easy.
• 2) Easy to maintain
• JSP can be easily managed because we can easily separate our business logic
with presentation logic. In servlet technology, we mix our business logic with
the presentation logic.
• 3) Fast Development: No need to recompile and redeploy
• If JSP page is modified, we don't need to recompile and redeploy the project.
The servlet code needs to be updated and recompiled if we have to change the
look and feel of the application.
• 4) Less code than Servlet
• In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that
reduces the code. Moreover, we can use EL, implicit objects etc.
Outline
Introduction to JSP
Advantages of JSP over Servlet
JSP Life cycle
JSP Creation in Eclipse
Elements of JSP page: directives, comments, scripting elements, actions
and templates
JDBC Connectivity with JSP.
Life cycle of aJSP Page
• The JSP pages follows these phases:
• Translation of JSP Page
• Compilation of JSP Page
• Classloading (class file is loaded by the classloader)
• Instantiation (Object of the Generated Servlet is created).
• Initialization ( jspInit() method is invoked by the container).
• Reqeust processing ( _jspService() method is invoked by the
container).
• Destroy ( jspDestroy() method is invoked by the container).
Life cycle of aJSP Page
In the end a JSP becomes a Servlet
JSP pages are converted into Servlet by the Web Container.
The Container translates a JSP page into servlet class source(.java) file and
then compiles into a Java Servlet class.
JSPCompilation
• When a browser asks for a JSP, the JSP engine first checks to see
whether it needs to compile the page.
• If the page has never been compiled, or if the JSP has been modified
since it was last compiled, the JSP engine compiles the page.
• The compilation process involves three steps −
• Parsing the JSP.
• Turning the JSP into a servlet.
• Compiling the servlet.
JSPInitialization
• When a container loads a JSP it invokes the jspInit() method
before servicing any requests.
• If you need to perform JSP-specific initialization, override the
jspInit() method −
• public void jspInit(){
• // Initialization code...
• }
• Typically, initialization is performed only once and as with the
servlet init method, you generally initialize database connections,
open files, and create lookup tables in the jspInitmethod.
JSP Execution
• This phase of the JSP life cycle represents all interactions with requests
until the JSP is destroyed.
• Whenever a browser requests a JSP and the page has been loaded and
initialized, the JSP engine invokes the _jspService() method in the JSP.
• The _jspService() method as follows −
• void _jspService(HttpServletRequest request, HttpServletResponse
response)
• {
• // Service handling code...
• }
• The _jspService() method of a JSP is invoked on request basis.
• This is responsible for generating the response for that request and this
method is also responsible for generating responses to all seven of the
HTTP methods, i.e, GET, POST, DELETE, etc.
JSP Cleanup
• The destruction phase of the JSP life cycle represents when
a JSP is being removed from use by a container.
• The jspDestroy() method is the JSP equivalent of the
destroy method for servlets.
• The jspDestroy() method has the following form −
• public void jspDestroy() {
• // Your cleanup code goes here.
• }
Outline
Introduction to JSP
Advantages of JSP over Servlet
JSP Life cycle
JSP Creation in Eclipse
Elements of JSP page: directives, comments, scripting elements, actions
and templates
JDBC Connectivity with JSP.
Creating a JSPPage
• A JSP page looks similar to an HTML page, but a JSP page
also has Java code in it.
• We can put any regular Java Code in a JSP file using a
scriplet tag which
• start with <%
• and ends with %>.
• JSP pages are used to develop dynamic responses.
Creating a JSPPage
Open Eclipse, Click on New → Dynamic Web Project
Creating a JSPPage
Give a name to your project and click on OK
Creating a JSPPage
You will see a new project created in Project Explorer
Creating a JSPPage
Tocreate a new JSP file right click on Web Content directory, New → JSP file
Creating a JSPPage
Give a name to your JSP file and click Finish.
Creating a JSPPage
Write something in your JSP file. The complete HTML and the JSP code,
goes inside the <body> tag, just like HTML pages.
Creating a JSPPage
Torun your project, right click on Project, select Run As → Run on Server
Creating a JSPPage
Tostart the server, Choose existing server name and click on finish
Creating a JSPPage
See the Output in your browser.
Outline
Introduction to JSP
Advantages of JSP over Servlet
JSP Life cycle
JSP Creation in Eclipse
Elements of JSP page: directives, comments, scripting elements,
actions and templates
JDBC Connectivity with JSP.
Elements ofJSP
Scripting Element Example
Comment <%-- comment --%>
Directive <%@ directive %>
Declaration <%! declarations %>
Scriptlet <% scriplets %>
Expression <%= expression %>
JSPComments
• JSP comment marks text or statements that the JSP container
should ignore.
• Syntax of the JSP comments −
• <%-- This is JSP comment --%>
• Example shows the JSP Comments −
<html>
<body>
<h2>A Test of Comments</h2>
<%-- This comment will not be visible in the page source --%>
</body>
</html>
TheScriptlet
• A scriptlet can contain any number of JAVAlanguage statements,
variable or method declarations, or expressions that are valid in the
page scripting language.
• syntax of Scriptlet − <% code fragment %>
• first example for JSP −
<html>
<head><title>Hello World</title></head>
<body>
Hello World!<br/>
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
</body>
</html>
JSPDeclarations
• A declaration declares one or more variables or methods that
you can use in Java code later in the JSP file. You must declare
the variable or method before you use it in the JSP file.
• Syntax for JSP Declarations −
• <%! declaration; %>
• Example for JSP Declarations −
• <%! int i = 0; %>
• <%! int a, b, c; %>
• <%! Circle a = new Circle(2.0); %>
JSPExpression
• A JSP expression element contains a scripting language
expression that is evaluated, converted to a String, and
inserted where the expression appears in the JSP file.
• you cannot use a semicolon to end an expression.
• Syntax of JSP Expression −
• <%= expression %>
• Example shows a JSP Expression −
<html>
<body>
<%= "Welcome "+request.getParameter("uname") %>
</body>
</html>
JSP Directives
• A JSP directive affects the overall structure of the servlet class.
It usually has the following form −
• <%@ directive attribute="value" %>
• There are three types of directive tag −
JSP pagedirective
• The page directive defines attributes that apply to an entire JSP page.
• Syntax of JSP page directive
• <%@ page attribute="value" %>
• Attributes of JSP page directive
• import
• contentType
• extends
• info
• buffer
• language
• isELIgnored
• isThreadSafe
• autoFlush
• session
• pageEncoding
• errorPage
• isErrorPage
JSP pagedirective
• Example of import attribute
• <html>
• <body>
•
• <%@ page import="java.util.Date" %>
• Today is: <%= new Date() %>
•
• </body>
• </html>
JSPActions
• JSP actions use to control the behavior of the servlet engine.
• You can dynamically insert a file, reuse JavaBeans components,
forward the user to another page, or generate HTML for the Java
plugin.
• Syntax
<jsp:action_name attribute = "value" />
JSPActions
S.No. Syntax & Purpose
1 jsp:include - Includes a file at the time the page is requested.
2 jsp:useBean - Finds or instantiates a JavaBean.
3 jsp:setProperty - Sets the property of a JavaBean.
4 jsp:getProperty - Inserts the property of a JavaBean into the output.
5 jsp:forward - Forwards the requester to a new page.
6
jsp:plugin - Generates browser-specific code that makes an OBJECT or
EMBED tag for the Java plugin.
7 jsp:element - Defines XML elements dynamically.
8 jsp:attribute - Defines dynamically-defined XML element's attribute.
9 jsp:body - Defines dynamically-defined XML element's body.
10 jsp:text - Used to write template text in JSP pages and documents.
jsp:include
• Syntax of jsp:include action tag without parameter
• <jsp:include page="relativeURL | <%= expression %>" />
• Syntax of jsp:include action tag with parameter
• <jsp:include page="relativeURL | <%= expression %>">
• <jsp:param name="parametername" value="parametervalue |
<%=expression%>" />
• </jsp:include>
jsp:include- withoutparameter
• In this example, index.jsp file includes the content of the printdate.jsp
file.
• File: index.jsp
• <h2>this is index page</h2>
• <jsp:include page="printdate.jsp" />
• <h2>end section of index page</h2>
• File: printdate.jsp
• <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
jsp:include- withparameter
• <html>
• <body>
• This is index.jsp Page
• <jsp:include page="display.jsp">
• <jsp:param name=“UName"
value=“Akash" />
• <jsp:param name="age"
value="27" />
• </jsp:include>
• </body>
• </html>
<html>
<body>
This is a display.jsp Page
Name :
<%=request.getParameter(“UName")%>
<br>
Age:
<%=request.getParameter("age")%>
</body>
</html>
jsp:forward actiontag
• The jsp:forward action tag is used to forward the request to
another resource it may be jsp, html or another resource.
• Syntax of jsp:forward action tag without parameter
• <jsp:forward page="relativeURL | <%= expression %>" />
• Syntax of jsp:forward action tag with parameter
• <jsp:forward page="relativeURL | <%= expression %>">
• <jsp:param name="parametername" value="parametervalue |
<%=expression%>" />
• </jsp:forward>
jsp:forward- withoutparameter
In this example, we are simply forwarding the request to the
printdate.jsp file.
index.jsp
<h2>this is index page</h2>
<jsp:forward page="printdate.jsp" />
printdate.jsp
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
jsp:forward- withparameter
• In this example, we are forwarding the request to the printdate.jsp file
with parameter and printdate.jsp file prints the parameter value with
date and time.
• index.jsp
• <h2>this is index page</h2>
• <jsp:forward page="printdate.jsp" >
• <jsp:param name="name" value=“Bhavana" />
• </jsp:forward>
•
• printdate.jsp
• <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %
• <%= request.getParameter("name") %>
jsp:useBean (JavaBeans)
• According to Java white paper, it is a reusable software
component. A bean encapsulates many objects into one
object, so we can access this object from multiple places.
Moreover, it provides the easy maintenance.
jsp:useBean
Simple example of java bean class
//Employee.java
public class Employee implements java.io.Serializable{
private int id;
public Employee(){}
public void setName(String name){this.name=name;}
public String getName(){return name;}
}
jsp:useBean
• How to access the java bean class?
• Toaccess the java bean class, we should use getter and setter
methods.
• public class Test{
• public static void main(String args[]){
• Employee e=new Employee();//object is created
• e.setName("Arjun");//setting value to the object
• System.out.println(e.getName());
• }}
JSPTemplates
• If a Website has multiple pages with identical formats, which
is common, even simple layout changes require modifications
to all of the pages.
• To minimize the impact of layout changes, we need a
mechanism for including layout in addition to content; that
way, both layout and content can vary without modifying files
that use them.
• That mechanism is JSP templates. (Same like CSS in HTML)
JSPTemplates
• Templates are JSP files that include parameterized content. The
templates have a set of custom tags:
• template:get,
• template:put,
• template:insert.
• Example
• <template:get name='header'/>
• <template:get name='content'/>
• <template:get name='footer'/>
• <template:insert template='/articleTemplate.jsp'>
• <template:put name='header' content='/header.html' />
• <template:put name='sidebar' content='/sidebar.jsp' />
• <template:put name='content' content='/introduction.html'/>
• <template:put name='footer' content='/footer.html' />
• </template:insert>
Outline
Introduction to JSP
Advantages of JSP over Servlet
JSP Life cycle
JSP Creation in Eclipse
Elements of JSP page: directives, comments, scripting elements, actions
and templates
JDBC Connectivity with JSP.
JDBC
• Java JDBC is a java API to connect and execute query with the
database. JDBC API uses jdbc drivers to connect with the database.
• Before JDBC, ODBC API was the database API to connect and execute
query with the database.
• But, ODBC API uses ODBC driver which is written in C
language (i.e. platform dependent and unsecured).
• That is why Java has defined its own API (JDBC API) that uses JDBC
drivers (written in Java language).
JDBCDriver
• JDBC Driver is a software component that enables java
application to interact with the database.
• There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)
JDBC Connectivity withJSP
• Software Requirement
• 1 MySQL
• 2 MySQL Connector (Jar file)
• 3 Apache Tomcat Server
• 4 Eclipse
• Important Note:
• Copy MySQL Connector (Jar file) into Tomcat’s Bin and Lib folder
• Before running program right click on project name -> Build path ->
Configure build path -> Libraries -> Add External Jar file -> Mysql
.jar file -> ok
JDBC Connectivity withJSP-
Createtableandaddrowsindatabase(mysql)
• Create the Employee table in the db1 database as follows −−
• mysql> Create database db1;
• mysql> use db1;
• mysql> create table emp
• (
• id int,
• name varchar (255)
• );
• Query OK, 0 rows affected (0.08 sec)
JDBC Connectivity withJSP-
Createtableandaddrowsindatabase(mysql)
• Insert Data
• mysql> INSERT INTO emp VALUES (100, 'Zara'');
• mysql> INSERT INTO Employees VALUES (101, 'Mamta');
JSP Code inEclipse
• File->New->Web->Dynamic Web Project->Give Project Name
• Right click on Project name->new->package->Give package
name For Writing JSP Code
• project-> Right click->new->JSP file-> Give file name with .jsp
• Extension
• In Body tag write java code in script let tag <% %>
• Right click on .jsp file -> Run -> Run as Server
JDBC Connectivity withJSP-
Example 1- JSPCodefortoselectdatafromemptable
<%@ page import ="java.sql.*" %>
<%@ page import ="javax.sql.*" %>
<%
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/db1","root","root");
Statement st= con.createStatement();
ResultSet rs=st.executeQuery("select * from emp");
out.print("<h2 align=center>Employee Database</h2>");
out.print("<table border=1 align=center>");
out.print("<tr><th> ENo</th> <th>Ename</th></tr>");
JDBC Connectivity withJSP-
Example1-JSPCodefortoselectdatafromemptable
while(rs.next())
{
out.print("<tr align=center>");
out.print("<td>");
out.print(rs.getInt(1));
out.print("</td>");
out.print("<td>");
out.print(rs.getString(2));
out.print("</td>");
out.print("</tr>");
}
%>
JDBC Connectivity withJSP-
Example2-JSPCodeforinsertdatainemptableanddisplaythe inserted
datafromtable
• It requires 2 files
• 1. S1.html (Html file to take values fromuser)
• 2. s2.jsp (jsp file to insert data in database and to displaythe
inserted data)
JDBC Connectivity withJSP-
Example2-JSPCodeforinsertdatainemptableanddisplaythe
inserteddatafromtable
• S1.html
<html>
<body>
<form method="post" action=“s2.jsp">
Enter Employee No<input type="text" name="t1"><br>
Enter Empoyee Name <input type="text" name="t2"><br>
<input type="submit" value="submit">
</form>
</body>
</html>
JDBC Connectivity withJSP-
Example2-JSPCodeforinsertdatainemptableanddisplaythe
inserteddatafromtable
S2.jsp
<%@ page import ="java.sql.*" %>
<%@ page import ="javax.sql.*" %>
<%
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3307/db1","root","root");
Statement st= con.createStatement();
int id= Integer.parseInt(request.getParameter("t1"));
String name=request.getParameter("t2");
st.executeUpdate("insert into emp values("+id+",'"+name+"')");
JDBC Connectivity withJSP-
Example2-JSPCodeforinsertdatainemptableanddisplaythe
inserteddatafromtable
ResultSet rs=st.executeQuery("select * from emp");
out.print("<h2 align=center>Employee Database</h2>");
out.print("<table border=1 align=center>");
out.print("<tr><th> ENo</th><th>Ename</th></tr>");
while(rs.next())
{
out.print("<tr align=center>");
out.print("<td>");
out.print(rs.getInt(1));
out.print("</td>");
out.print("<td>");
out.print(rs.getString(2));
out.print("</td>");
out.print("</tr>");
}
%>
References
• https://www.javatpoint.com/cookies-in-servlet
• https://www.javatpoint.com/hidden-form-field-in-session-
tracking
• https://www.studytonight.com/servlet/hidden-form-field.php
• https://www.studytonight.com/servlet/url-rewriting-for-
session-management.php
• https://www.tutorialspoint.com/jsp/jsp_overview.htm
• https://www.javatpoint.com/jsp-tutorial
• https://www.studytonight.com/jsp/introduction-to-jsp.php
• https://www.studytonight.com/jsp/creating-a-jsp-page.php
• https://www.studytonight.com/jsp/jsp-scripting-element.php
• https://www.javatpoint.com/java-jdbc
• https://www.javatpoint.com/jsp-include-action
Thank You
170
gharu.anand@gmail.com
Blog : anandgharu.wordpress.com
Prof. Gharu Anand N. 170

More Related Content

What's hot

Java Servlets
Java ServletsJava Servlets
Java ServletsNitin Pai
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1vikram singh
 
Java EE 01-Servlets and Containers
Java EE 01-Servlets and ContainersJava EE 01-Servlets and Containers
Java EE 01-Servlets and ContainersFernando Gil
 
1 java servlets and jsp
1   java servlets and jsp1   java servlets and jsp
1 java servlets and jspAnkit Minocha
 
Introduction to Servlets
Introduction to ServletsIntroduction to Servlets
Introduction to ServletsFulvio Corno
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.pptVMahesh5
 
Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012
Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012
Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012Sam Brannen
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packagesvamsi krishna
 
java servlet and servlet programming
java servlet and servlet programmingjava servlet and servlet programming
java servlet and servlet programmingKumar
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSPGary Yeh
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycleDhruvin Nakrani
 

What's hot (20)

Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
 
Java EE 01-Servlets and Containers
Java EE 01-Servlets and ContainersJava EE 01-Servlets and Containers
Java EE 01-Servlets and Containers
 
Servlets
ServletsServlets
Servlets
 
Jsp servlets
Jsp servletsJsp servlets
Jsp servlets
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
Java Servlet
Java Servlet Java Servlet
Java Servlet
 
1 java servlets and jsp
1   java servlets and jsp1   java servlets and jsp
1 java servlets and jsp
 
Servlets
ServletsServlets
Servlets
 
Introduction to Servlets
Introduction to ServletsIntroduction to Servlets
Introduction to Servlets
 
Java EE 8
Java EE 8Java EE 8
Java EE 8
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012
Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012
Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
 
Servlet
Servlet Servlet
Servlet
 
Advance Java
Advance JavaAdvance Java
Advance Java
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
java servlet and servlet programming
java servlet and servlet programmingjava servlet and servlet programming
java servlet and servlet programming
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSP
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycle
 

Similar to Wt unit 3 server side technology

Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdfArumugam90
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)slire
 
Ppt for Online music store
Ppt for Online music storePpt for Online music store
Ppt for Online music storeADEEBANADEEM
 
IP UNIT III PPT.pptx
 IP UNIT III PPT.pptx IP UNIT III PPT.pptx
IP UNIT III PPT.pptxssuser92282c
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servletssbd6985
 
Advance java session 2
Advance java session 2Advance java session 2
Advance java session 2Smita B Kumar
 
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database ConnectivityIT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivitypkaviya
 
WEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxWEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxkarthiksmart21
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technologyTanmoy Barman
 
Session 26 - Servlets Part 2
Session 26 - Servlets Part 2Session 26 - Servlets Part 2
Session 26 - Servlets Part 2PawanMM
 
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
 
Java Servlet
Java ServletJava Servlet
Java ServletYoga Raja
 
JavaScript, often abbreviated as JS, is a programming language and core techn...
JavaScript, often abbreviated as JS, is a programming language and core techn...JavaScript, often abbreviated as JS, is a programming language and core techn...
JavaScript, often abbreviated as JS, is a programming language and core techn...MathivananP4
 

Similar to Wt unit 3 server side technology (20)

Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdf
 
Servlet.pptx
Servlet.pptxServlet.pptx
Servlet.pptx
 
Servlet.pptx
Servlet.pptxServlet.pptx
Servlet.pptx
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
 
AJppt.pptx
AJppt.pptxAJppt.pptx
AJppt.pptx
 
Ppt for Online music store
Ppt for Online music storePpt for Online music store
Ppt for Online music store
 
IP UNIT III PPT.pptx
 IP UNIT III PPT.pptx IP UNIT III PPT.pptx
IP UNIT III PPT.pptx
 
Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
Advance java1.1
Advance java1.1Advance java1.1
Advance java1.1
 
Advance java session 2
Advance java session 2Advance java session 2
Advance java session 2
 
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database ConnectivityIT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
 
WEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxWEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptx
 
CS8651 IP Unit 3.pptx
CS8651 IP Unit 3.pptxCS8651 IP Unit 3.pptx
CS8651 IP Unit 3.pptx
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
Session 26 - Servlets Part 2
Session 26 - Servlets Part 2Session 26 - Servlets Part 2
Session 26 - Servlets Part 2
 
Servlets
ServletsServlets
Servlets
 
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)
 
Java Servlet
Java ServletJava Servlet
Java Servlet
 
JavaScript, often abbreviated as JS, is a programming language and core techn...
JavaScript, often abbreviated as JS, is a programming language and core techn...JavaScript, often abbreviated as JS, is a programming language and core techn...
JavaScript, often abbreviated as JS, is a programming language and core techn...
 

More from PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK

More from PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK (20)

BASICS OF COMPUTER
BASICS OF COMPUTERBASICS OF COMPUTER
BASICS OF COMPUTER
 
Wt unit 6 ppts web services
Wt unit 6 ppts web servicesWt unit 6 ppts web services
Wt unit 6 ppts web services
 
Wt unit 5 client &amp; server side framework
Wt unit 5 client &amp; server side frameworkWt unit 5 client &amp; server side framework
Wt unit 5 client &amp; server side framework
 
Wt unit 4 server side technology-2
Wt unit 4 server side technology-2Wt unit 4 server side technology-2
Wt unit 4 server side technology-2
 
Wt unit 3 server side technology
Wt unit 3 server side technologyWt unit 3 server side technology
Wt unit 3 server side technology
 
Wt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technologyWt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technology
 
web development process WT
web development process WTweb development process WT
web development process WT
 
Unit 6 dsa SEARCHING AND SORTING
Unit 6 dsa SEARCHING AND SORTINGUnit 6 dsa SEARCHING AND SORTING
Unit 6 dsa SEARCHING AND SORTING
 
Unit 5 dsa QUEUE
Unit 5 dsa QUEUEUnit 5 dsa QUEUE
Unit 5 dsa QUEUE
 
Unit 3 dsa LINKED LIST
Unit 3 dsa LINKED LISTUnit 3 dsa LINKED LIST
Unit 3 dsa LINKED LIST
 
Unit 2 dsa LINEAR DATA STRUCTURE
Unit 2 dsa LINEAR DATA STRUCTUREUnit 2 dsa LINEAR DATA STRUCTURE
Unit 2 dsa LINEAR DATA STRUCTURE
 
Unit 1 dsa
Unit 1 dsaUnit 1 dsa
Unit 1 dsa
 
Wt unit 2 ppts client side technology
Wt unit 2 ppts client side technologyWt unit 2 ppts client side technology
Wt unit 2 ppts client side technology
 
Wt unit 1 ppts web development process
Wt unit 1 ppts web development processWt unit 1 ppts web development process
Wt unit 1 ppts web development process
 
LANGUAGE TRANSLATOR
LANGUAGE TRANSLATORLANGUAGE TRANSLATOR
LANGUAGE TRANSLATOR
 
OPERATING SYSTEM
OPERATING SYSTEMOPERATING SYSTEM
OPERATING SYSTEM
 
LEX & YACC TOOL
LEX & YACC TOOLLEX & YACC TOOL
LEX & YACC TOOL
 
PL-3 LAB MANUAL
PL-3 LAB MANUALPL-3 LAB MANUAL
PL-3 LAB MANUAL
 
COMPUTER LABORATORY-4 LAB MANUAL BE COMPUTER ENGINEERING
COMPUTER LABORATORY-4 LAB MANUAL BE COMPUTER ENGINEERINGCOMPUTER LABORATORY-4 LAB MANUAL BE COMPUTER ENGINEERING
COMPUTER LABORATORY-4 LAB MANUAL BE COMPUTER ENGINEERING
 
Deld model answer nov 2017
Deld model answer nov 2017Deld model answer nov 2017
Deld model answer nov 2017
 

Recently uploaded

CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacingjaychoudhary37
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZTE
 

Recently uploaded (20)

CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacing
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
 

Wt unit 3 server side technology

  • 1. Pune Vidyarthi Griha’s COLLEGE OF ENGINEERING, NASHIK “SERVER SIDE TECHNOLOGYIES” By Prof. Anand N. Gharu (Assistant Professor) PVGCOE Computer Dept. 18 Jan 2020Note: Thematerial to preparethis presentation hasbeentaken from internet andare generatedonly for students referenceandnot for commercialuse.
  • 2. Outline Introduction to Server Side technology and TOMCAT, Servlet: Introduction to Servlet, need and advantages, Servlet Lifecycle, Creating and testing of sample Servlet, session management. JSP: Introduction to JSP, advantages of JSP over Servlet , elements of JSP page: directives, comments, scripting elements, actions and templates, JDBC Connectivity with JSP.
  • 4. OutLine Servlet Introduction Servlet Lifecycle Servlet Architecture Software Requirement to run Servlet Tomcat Introduction Tomcat Configuration in Eclipse Steps to run servlets in Eclipse Sample code Session Management
  • 5. What areServlets? • Servlet is server side java application which is used to create dynamic web pages. • Java Servlets are programs that run on a Web or Application server and act as a middle layer between a requests coming from a Web browser or other HTTP client and databases or applications on the HTTP server. • Using Servlets, you can collect input from users through web page forms, present records from a database or another source, and create web pages dynamically.
  • 6. Client vs Server side Scripting
  • 7. Client vs Server side technology Servlet vs CGI
  • 8. Advantages of Servlet overCGI • Portability • Powerful • Efficiency • Safety • Integration • Extensibility • Inexpensive • Secure • performance
  • 9. Advantages of Servlet overCGI • Performance is significantly better. • Servlets execute within the address space of a Web server. It is not necessary to create a separate process to handle each client request. • Servlets are platform-independent because they are written in Java. • servlets are trusted. • The full functionality of the Java class libraries is available to a servlet. • Invocation or calling of servlet is highly efficient than CGI • Servlet can handle number of complex task which were difficult for CGI.
  • 13. ServletsPackages • Java Servlets are Java classes run by a web server that has an interpreter that supports the Java Servlet specification. • Servlets can be created using the packages • javax.servlet • javax.servlet.http
  • 14. OutLine Servlet Introduction Servlet Lifecycle Servlet Architecture Software Requirement to run Servlet Tomcat Introduction Tomcat Configuration in Eclipse Steps to run servlets in Eclipse Sample code
  • 15. Servlet LifeCycle • Load Servlet • Create servlet instance • Call init ( ) once • Call service ( ) • Call destroy ( ) once
  • 16. Servlet LifeCycle • The servlet is initialized by calling the init() method. • The servlet calls service() method to process a client's request. • The servlet is terminated by calling the destroy() method. • Finally, servlet is garbage collected by the garbage collector of the JVM.
  • 17. The init( )Method • The init method is called only once. It is called only when the servlet is created, and not called for any user requests afterwards. • So, it is used for one-time initializations. • When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread that is handed off to doGet or doPost as appropriate. • The init() method simply creates or loads some data that will be used throughout the life of the servlet. • The init method definition looks like this − public void init() throws ServletException { // Initialization code... }
  • 18. The service( )Method • The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client. • When server receives a request for a servlet, the service() method checks the HTTP request type (GET, POST) and calls doGet, doPost, methods as appropriate. • Here is the signature of this method − • public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { }
  • 19. The doGet()Method • A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it should be handled by doGet() method. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Servlet code }
  • 20. The doPost()Method • A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled by doPost() method. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Servlet code }
  • 21. The destroy()Method • The destroy() method is called only once at the end of the life cycle of a servlet.SS • This method gives your servlet a chance to close database connections, halt background threads, and perform other such cleanup activities. • After the destroy() method is called, the servlet object is marked for garbage collection. • The destroy method definition looks like this − public void destroy() { // Finalization code...}
  • 24. OutLine Servlet Introduction Servlet Lifecycle Servlet Architecture Software Requirement to run Servlet Tomcat Introduction Tomcat Configuration in Eclipse Steps to run servlets in Eclipse Sample code Session Management
  • 25. ArchitectureDiagram • First the HTTP requests coming to the server are delegated to the servlet container. • The servlet container loads the servlet before invoking the service()S method. • Then the servlet container handles multiple requests by spawning multiple threads, each thread executing the service() method of a single instance of the servlet.
  • 26. OutLine Servlet Introduction Servlet Lifecycle Servlet Architecture Software Requirement to run Servlet Tomcat Introduction Tomcat Configuration in Eclipse Steps to run servlets in Eclipse Sample code Session Management
  • 27. Requirements Before running Servlet your machine requires following tools • 1> Eclipse (IDE-integrated development environment) • 2> Tomcat (Web Server)
  • 28. OutLine Servlet Introduction Servlet Lifecycle Servlet Architecture Software Requirement to run Servlet Tomcat Introduction Tomcat Configuration in Eclipse Steps to run servlets in Eclipse Sample code Session Management
  • 29. Apache-Tomcat • Apache Tomcat, often referred to as Tomcat Server, is an open-source Java Servlet Container developed by the Apache Software Foundation (ASF). • Tomcat implements several Java EE specifications including Java Servlet, JavaServer Pages (JSP), Java EL, and WebSocket, and provides a "pure Java" HTTP web server environment in which Java code can run.
  • 31. Tomcat-Components Catalina • Catalina is Tomcat's servlet container. • Catalina implements Sun Microsystems's specifications for servlet and JavaServer Pages (JSP). • In Tomcat, a Realm element represents a "database" of usernames, passwords, and roles assigned to those users. • Catalina to be integrated into environments where such authentication information is already being created and maintained, and then use that information to implement Container Managed Security as described in the Servlet Specification.
  • 32. Tomcat-Components Coyote • Coyote is a Connector component for Tomcat that supports the HTTP 1.1 protocol as a web server. • This allows Catalina, nominally a Java Servlet or JSP container, to also act as a plain web server that serves local files as HTTP documents. • Coyote listens for incoming connections to the server on a specific TCP port and forwards the request to the Tomcat Engine to process the request and send back a response to the requesting client.
  • 33. Tomcat-Components Jasper • Jasper is Tomcat's JSP Engine. • Jasper parses JSP files to compile them into Java code as servlets (that can be handled by Catalina). At runtime, Jasper detects changes to JSP files and recompiles them. • From Jasper to Jasper 2, important features were added: • JSP Tag library pooling - Each tag markup in JSP file is handled by a tag handler class. • Background JSP compilation - While recompiling modified JSP Java code, the older version is still available for server requests. • Recompile JSP when included page changes - Pages can be inserted and included into a JSP at runtime • JDT Java compiler - Jasper 2 can use the Eclipse JDT Java compiler
  • 34. Tomcat-Components • These components are added from Tomcat 7.0 version • Cluster • This component has been added to manage large applications. • High availability • A high-availability feature has been added to facilitate the scheduling of system upgrades (e.g. new releases, change requests) without affecting the live environment. • Web application • It has also added user- as well as system-based web applications enhancement to add support for deployment across the variety of environments.
  • 35. OutLine Servlet Introduction Servlet Lifecycle Servlet Architecture Software Requirement to run Servlet Tomcat Introduction Tomcat Configuration in Eclipse Steps to run servlets in Eclipse Sample code Session Management
  • 36. Howtoconfiguretomcatserverin Eclipse ?(One time Requirement) • If you are using Eclipse IDE first time, you need to configure the tomcat server First. S • For configuring the tomcat server in eclipse IDE, • click on servers tab at the bottom side of the IDE -> right click on blank area -> New -> Servers -> choose tomcat then its version -> next -> click on Browse button -> select the apache tomcat root folder previous to bin -> next -> addAll -> Finish.
  • 45. OutLine Servlet Introduction Servlet Lifecycle Servlet Architecture Software Requirement to run Servlet Tomcat Introduction Tomcat Configuration in Eclipse Steps to run servlets in Eclipse Sample code Session Management
  • 46. Steps to run servlet in Eclipse Create a Dynamic web project create a servlet add servlet-api.jar file Run the servlet
  • 47. Steps to run servlet in Eclipse Create a Dynamic web project create a servlet add servlet-api.jar file Run the servlet
  • 48. Create the dynamic webproject Start Eclipse and In Menu : File -> New -> Dynamic Web Project
  • 49. Create the dynamic webproject
  • 50. Create the dynamic webproject
  • 51. Create the dynamic webproject
  • 52. Create the dynamic webproject Structure of Dynamic Web Project
  • 53. Steps to run servlet in Eclipse Create a Dynamic web project create a servlet add servlet-api.jar file Run the servlet
  • 54. Create aservlet Right click on Src -> New -> Sevlet
  • 58. Create aservlet Servlet is created, you can write the code now.
  • 59. Steps to run servlet in Eclipse Create a Dynamic web project create a servlet add servlet-api.jar file Run the servlet
  • 62. Add servlet-api.jarfile In Tomcat folder goto Lib folder and select servlet-api.jarfile
  • 64. Steps to run servlet in Eclipse Create a Dynamic web project create a servlet add servlet-api.jar file Run the servlet
  • 65. Run theservlet Right click on project name -> click Run As -> Run on Server
  • 68. OutLine Servlet Introduction Servlet Lifecycle Servlet Architecture Software Requirement to run Servlet Tomcat Introduction Tomcat Configuration in Eclipse Steps to run servlets in Eclipse Sample code Session Management
  • 69. Example1- ToPrint Hello Worlddirectly import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void init() throws ServletException { } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<h1> Hello World </h1>"); } public void destroy() { } }
  • 70. Example 2- ToPrintHelloWorld using initmethod import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { private String message; public void init() throws ServletException { message = "Hello World"; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<h1>" + message + "</h1>"); } public void destroy() { } }
  • 71. Reading Form Data usingServlet • getParameter() − You call request.getParameter() method to get the value of a form parameter. • getParameterValues() − Call this method if the parameter appears more than once and returns multiple values, for example checkbox. • getParameterNames() − Call this method if you want a complete list of all parameters in the current request.
  • 72. Example3- ToreaddatafromHTMLfileandprintthat. • It requires 2 files: • 1. HTML (s1.html)File • 2. Servlet (s2.java) File • First Run HTML file and after clicking on submit button it will run servel(.java) file.
  • 73. Example3- ToreaddatafromHTMLfileandprintthat. • S1.html (html code) <html> <form method=“post” action=“s2”> Enter Your Name <input type=text name=“t1”> <br> <input type=“submit” value=“submit”> </form> </body> </html>
  • 74. Example3- ToreaddatafromHTMLfileandprintthat. • S2.java (Servlet Code) import java.io.*; import javax.servlet.*; public class s2 extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String a= request.getParameter("t1"); PrintWriter out= response.getWriter(); out.print("<br>Your Name is: "+a); } }
  • 75. Example 4–(HTML code) ToreaddatafromHTMLcheckboxvaluesprintthat • <!DOCTYPE html> • <html> • <body> • <form method="post" action=s1> • Hobbies • <input type="checkbox" name="t1" value=“Cricket"> Cricket • <input type="checkbox" name="t1" value="Music">Music • <input type="checkbox" name="t1" value=“Dance">Dance • <input type="submit" value="submit"> • </form> • </body> • </html> Name of Servlet File
  • 76. Example 4–(servlet code) ToreaddatafromHTMLcheckboxvaluesprintthat • protected void doPost(HttpServletRequest request, HttpServletResponse response) • throws ServletException, IOException { • response.setContentType("text/html"); • PrintWriter out=response.getWriter(); • String[] values=request.getParameterValues("t1"); • • for(int i=0;i<values.length;i++) • { • out.println("<li>"+values[i]+"</li>"); • } • } • }
  • 77. Example 5–(HTML code) Toprintcompletelistofallparameters • <!DOCTYPE html> • <html> • <body> • <form method="post" action=s1> • Hobbies • Enter Name <input type=“text" name="t1" > <br> • Enter Address <input type=“text" name="t2" > <br> • Enter Class <input type=“text" name="t3" > <br> • <input type="submit" value="submit"> • </form> • </body> • </html>
  • 78. Example 5 –(Servletcode) Toprintcompletelistofallparameters protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); Enumeration e = request.getParameterNames(); while(e.hasMoreElements()) { Object obj = e.nextElement(); out.println((String) obj+ "<br>"); } }
  • 79. OutLine Servlet Introduction Servlet Lifecycle Servlet Architecture Software Requirement to run Servlet Tomcat Introduction Tomcat Configuration in Eclipse Steps to run servlets in Eclipse Sample code Session Management
  • 80. Session Tracking(Management) • Session Tracking is a way to maintain state (data) of an user. It is also known as session management in servlet. • Http protocol is a stateless so we need to maintain state using session tracking techniques. • Each time user requests to the server, server treats the request as the new request. • So we need to maintain the state of an user to recognize to particular user. • Why use Session Tracking? • To recognize the user It is used to recognize the particular user.
  • 81. Session TrackingTechniques Cookies Hidden Form Field URL Rewriting HttpSession
  • 82. Session Tracking-UsingCookies • A cookie is a small piece of information that is persisted between the multiple client requests. • A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. • How Cookie works • In cookies technique, we add cookie with response from the servlet. So cookie is stored in the cache of the browser. After that if request is sent by the user, cookie is added with request by default. Thus, we recognize the user as the old user.
  • 83. Session Tracking-UsingCookies • Types of Cookie • Non-persistent cookie • Persistent cookie • Non-persistent cookie • It is valid for single session only. It is removed each time when user closes the browser. • Persistent cookie • It is valid for multiple session . It is not removed each time when user closes the browser. It is removed only if user logout or signout.
  • 84. Session Tracking-UsingCookies • Advantage of Cookies • Simplest technique of maintaining the state. • Cookies are maintained at client side. • Disadvantage of Cookies • It will not work if cookie is disabled from the browser. • Only textual information can be set in Cookie object.
  • 85. Session Tracking-UsingCookies Method Description public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds. public String getName() Returns the name of the cookie. The name cannot be changed after creation. public String getValue() Returns the value of the cookie. public void setName(String name) changes the name of the cookie. public void setValue(String value) changes the value of the cookie. Useful Methods of Cookie class
  • 86. Session Tracking-UsingCookies • How to create Cookie? • Cookie ck=new Cookie("user","sonu");//creating cookie object • response.addCookie(ck);//adding cookie in the response • How to delete Cookie? • Cookie ck=new Cookie("user","");//deleting value of cookie • ck.setMaxAge(0);//changing the maximum age to 0 seconds • response.addCookie(ck);//adding cookie in the response • How to get Cookies? • Cookie ck[]=request.getCookies(); • for(int i=0;i<ck.length;i++){ • out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing na me and value of cookie • }
  • 88. Session Tracking-UsingCookies SimpleexampleofServletCookies • index.html <form action="servlet1" method="post"> Name:<input type="text" name="userName"/><br/> <input type="submit" value="go"/> </form>
  • 89. Session Tracking-UsingCookies SimpleexampleofServletCookies Servlet1.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class FirstServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); out.print("Welcome "+n); Cookie ck=new Cookie("uname",n);//creating cookie object response.addCookie(ck);//adding cookie in the response //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);} } }
  • 90. Session Tracking-UsingCookies SimpleexampleofServletCookies Servlet2.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SecondServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse 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);} } }
  • 91. Session TrackingTechniques Cookies Hidden Form Field URL Rewriting HttpSession
  • 92. SessionTracking-Hidden Form Fields • In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining the state of an user. • In such case, we store the information in the hidden field and get it from another servlet. • Synax • <input type="hidden" name="uname" value=“Bhavana"> • Here, uname is the hidden field name and Bhavana is the hidden field value.
  • 93. SessionTracking-Hidden Form Fields • Advantage of Hidden Form Field • It will always work whether cookie is disabled or not. • Disadvantage of Hidden Form Field: • It is maintained at server side. • Extra form submission is required on each pages. • Only textual information can be used.
  • 95. SessionTracking-Hidden Form Fields Example of passingusername • index.html <form method="post" action=“First"> Name:<input type="text" name="user" /><br/> Password:<input type="text" name="pass" ><br/> <input type="submit" value="submit"> </form>
  • 96. SessionTracking-Hidden Form Fields Example of passingusername • First.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class First extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String user = request.getParameter("user"); //creating a new hidden form field out.println("<form action='Second'>"); out.println("<input type='hidden' name='user' value='"+user+"'>"); out.println("<input type='submit' value='submit' >"); out.println("</form>"); } }
  • 97. SessionTracking-Hidden Form Fields Example of passingusername • Second.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Second extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); //getting parameter from the hidden field String user = request.getParameter("user"); out.println("Welcome "+user); } }
  • 98. Session TrackingTechniques Cookies Hidden Form Field URL Rewriting HttpSession
  • 99. Session Tracking-URLRewriting • If the client has disabled cookies in the browser then session management using cookie wont work. • In that case URL Rewriting can be used as a backup. URL rewriting will always work. • In URL rewriting, a token(parameter) is added at the end of the URL. • The token consist of name/value pair separated by an equal(=) sign. • For Example:
  • 100. Session Tracking-URLRewriting • When the User clicks on the URL having parameters, the request goes to the Web Container with extra bit of information at the end of URL. • The Web Container will fetch the extra part of the requested URL and use it for session management. • The getParameter() method is used to get the parameter value at the server side. • Advantage of URL Rewriting • It will always work whether cookie is disabled or not (browser independent). • Extra form submission is not required on each pages. • Disadvantage of URL Rewriting • It will work only with links. • It can send only textual information.
  • 101. Session Tracking-URLRewriting Example • index.html • <form method="post" action="validate"> • Name:<input type="text" name="user" /><br/> • Password:<input type="text" name="pass" ><br/> • <input type="submit" value="submit"> • </form>
  • 102. Session Tracking-URLRewriting Example • Validate.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class MyServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String name = request.getParameter("user"); String pass = request.getParameter("pass"); if(pass.equals("1234")) { response.sendRedirect("First?user_name="+name+""); } } }
  • 103. Session Tracking-URLRewriting Example • First.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class First extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String user = request.getParameter("user_name"); out.println("Welcome "+user); } }
  • 104. Session TrackingTechniques Cookies Hidden Form Field URL Rewriting HttpSession
  • 105. Session Tracking- HttpSession • The servlet container uses this interface to create a session between an HTTP client and an HTTP server. • The session persists for a specified time period, across more than one connection or page request from the user. • You would get HttpSession object by calling the public method getSession() of HttpServletRequest, as below − HttpSession session = request.getSession();
  • 106. SessionTracking- HttpSession • How to get the HttpSession object ? • public HttpSession getSession():Returns the current session associated with this request, or if the request does not have a session, creates one. • Commonly used methods of HttpSession interface • public String getId():Returns unique identifiervalue. • public long getCreationTime():Returns the time when this session was created. • public long getLastAccessedTime():Returns the last time the client sent a request associated with thissession. • public void invalidate():Invalidates this session then unbinds any objects bound to it.
  • 107. Session Tracking-HttpSession Example HitCount • HTML File <h3>Hit Count Example with HttpSession</h3> <form method="get" action=“HitCount"> Click for Hit Count <input type="submit" value="GET HITS"> </form> </body>
  • 108. Session Tracking-HttpSession Example HitCount public class HitCount extends HttpServlet { public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html") ; PrintWriter out = res.getWriter( ); HttpSession session = req.getSession(); Integer hitNumber = (Integer) session.getAttribute("rama"); if (hitNumber == null) { hitNumber = new Integer(1); } else { hitNumber = new Integer(hitNumber.intValue()+1) ; } session.setAttribute("rama", hitNumber); // storing the value with session object out.println("Your Session ID: " + session.getId()); // never changes in the whole session out.println("<br>Session Creation Time: " + new Date(session.getCreationTime())); out.println("<br>Time of Last Access: " + new Date(session.getLastAccessedTime())); out.println("<br>Latest Hit Count: " + hitNumber); // increments by 1 for every hit
  • 110. JSP
  • 111. Outline Introduction to JSP Advantages of JSP over Servlet JSP Life cycle JSP Creation in Eclipse Elements of JSP page: directives, comments, scripting elements, actions and templates JDBC Connectivity with JSP.
  • 112. Outline Introduction to JSP Advantages of JSP over Servlet JSP Life cycle JSP Creation in Eclipse Elements of JSP page: directives, comments, scripting elements, actions and templates JDBC Connectivity with JSP.
  • 113. Introduction toJSP • JSP technology is used to create web application just like Servlet technology. • It can be thought of as an extension to servlet because it provides more functionality than servlet such as expression language, jstl etc. • A JSP page consists of HTML tags and JSP tags. • The jsp pages are easier to maintain than servlet because we can separate designing and development. • It provides some additional features such as Expression Language, Custom Tag etc.
  • 114. Advantages ofJSP • vs. Active Server Pages (ASP) • The advantages of JSP are twofold. • First, the dynamic part is written in Java, not Visual Basic or other MS specific language, so it is more powerful and easier to use. • Second, it is portable to other operating systems and non- Microsoft Web servers. • vs. JavaScript • JavaScript can generate HTML dynamically on the client but can hardly interact with the web server to perform complex tasks like database access and image processing etc.
  • 115. Advantage of JSP overServlet• 1) Extension to Servlet • JSP technology is the extension to servlet technology. We can use all the features of servlet in JSP. In addition to, we can use implicit objects, predefined tags, expression language and Custom tags in JSP, that makes JSP development easy. • 2) Easy to maintain • JSP can be easily managed because we can easily separate our business logic with presentation logic. In servlet technology, we mix our business logic with the presentation logic. • 3) Fast Development: No need to recompile and redeploy • If JSP page is modified, we don't need to recompile and redeploy the project. The servlet code needs to be updated and recompiled if we have to change the look and feel of the application. • 4) Less code than Servlet • In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that reduces the code. Moreover, we can use EL, implicit objects etc.
  • 116. Outline Introduction to JSP Advantages of JSP over Servlet JSP Life cycle JSP Creation in Eclipse Elements of JSP page: directives, comments, scripting elements, actions and templates JDBC Connectivity with JSP.
  • 117. Life cycle of aJSP Page • The JSP pages follows these phases: • Translation of JSP Page • Compilation of JSP Page • Classloading (class file is loaded by the classloader) • Instantiation (Object of the Generated Servlet is created). • Initialization ( jspInit() method is invoked by the container). • Reqeust processing ( _jspService() method is invoked by the container). • Destroy ( jspDestroy() method is invoked by the container).
  • 118. Life cycle of aJSP Page In the end a JSP becomes a Servlet JSP pages are converted into Servlet by the Web Container. The Container translates a JSP page into servlet class source(.java) file and then compiles into a Java Servlet class.
  • 119. JSPCompilation • When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. • If the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page. • The compilation process involves three steps − • Parsing the JSP. • Turning the JSP into a servlet. • Compiling the servlet.
  • 120. JSPInitialization • When a container loads a JSP it invokes the jspInit() method before servicing any requests. • If you need to perform JSP-specific initialization, override the jspInit() method − • public void jspInit(){ • // Initialization code... • } • Typically, initialization is performed only once and as with the servlet init method, you generally initialize database connections, open files, and create lookup tables in the jspInitmethod.
  • 121. JSP Execution • This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed. • Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspService() method in the JSP. • The _jspService() method as follows − • void _jspService(HttpServletRequest request, HttpServletResponse response) • { • // Service handling code... • } • The _jspService() method of a JSP is invoked on request basis. • This is responsible for generating the response for that request and this method is also responsible for generating responses to all seven of the HTTP methods, i.e, GET, POST, DELETE, etc.
  • 122. JSP Cleanup • The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container. • The jspDestroy() method is the JSP equivalent of the destroy method for servlets. • The jspDestroy() method has the following form − • public void jspDestroy() { • // Your cleanup code goes here. • }
  • 123. Outline Introduction to JSP Advantages of JSP over Servlet JSP Life cycle JSP Creation in Eclipse Elements of JSP page: directives, comments, scripting elements, actions and templates JDBC Connectivity with JSP.
  • 124. Creating a JSPPage • A JSP page looks similar to an HTML page, but a JSP page also has Java code in it. • We can put any regular Java Code in a JSP file using a scriplet tag which • start with <% • and ends with %>. • JSP pages are used to develop dynamic responses.
  • 125. Creating a JSPPage Open Eclipse, Click on New → Dynamic Web Project
  • 126. Creating a JSPPage Give a name to your project and click on OK
  • 127. Creating a JSPPage You will see a new project created in Project Explorer
  • 128. Creating a JSPPage Tocreate a new JSP file right click on Web Content directory, New → JSP file
  • 129. Creating a JSPPage Give a name to your JSP file and click Finish.
  • 130. Creating a JSPPage Write something in your JSP file. The complete HTML and the JSP code, goes inside the <body> tag, just like HTML pages.
  • 131. Creating a JSPPage Torun your project, right click on Project, select Run As → Run on Server
  • 132. Creating a JSPPage Tostart the server, Choose existing server name and click on finish
  • 133. Creating a JSPPage See the Output in your browser.
  • 134. Outline Introduction to JSP Advantages of JSP over Servlet JSP Life cycle JSP Creation in Eclipse Elements of JSP page: directives, comments, scripting elements, actions and templates JDBC Connectivity with JSP.
  • 135. Elements ofJSP Scripting Element Example Comment <%-- comment --%> Directive <%@ directive %> Declaration <%! declarations %> Scriptlet <% scriplets %> Expression <%= expression %>
  • 136. JSPComments • JSP comment marks text or statements that the JSP container should ignore. • Syntax of the JSP comments − • <%-- This is JSP comment --%> • Example shows the JSP Comments − <html> <body> <h2>A Test of Comments</h2> <%-- This comment will not be visible in the page source --%> </body> </html>
  • 137. TheScriptlet • A scriptlet can contain any number of JAVAlanguage statements, variable or method declarations, or expressions that are valid in the page scripting language. • syntax of Scriptlet − <% code fragment %> • first example for JSP − <html> <head><title>Hello World</title></head> <body> Hello World!<br/> <% out.println("Your IP address is " + request.getRemoteAddr()); %> </body> </html>
  • 138. JSPDeclarations • A declaration declares one or more variables or methods that you can use in Java code later in the JSP file. You must declare the variable or method before you use it in the JSP file. • Syntax for JSP Declarations − • <%! declaration; %> • Example for JSP Declarations − • <%! int i = 0; %> • <%! int a, b, c; %> • <%! Circle a = new Circle(2.0); %>
  • 139. JSPExpression • A JSP expression element contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. • you cannot use a semicolon to end an expression. • Syntax of JSP Expression − • <%= expression %> • Example shows a JSP Expression − <html> <body> <%= "Welcome "+request.getParameter("uname") %> </body> </html>
  • 140. JSP Directives • A JSP directive affects the overall structure of the servlet class. It usually has the following form − • <%@ directive attribute="value" %> • There are three types of directive tag −
  • 141. JSP pagedirective • The page directive defines attributes that apply to an entire JSP page. • Syntax of JSP page directive • <%@ page attribute="value" %> • Attributes of JSP page directive • import • contentType • extends • info • buffer • language • isELIgnored • isThreadSafe • autoFlush • session • pageEncoding • errorPage • isErrorPage
  • 142. JSP pagedirective • Example of import attribute • <html> • <body> • • <%@ page import="java.util.Date" %> • Today is: <%= new Date() %> • • </body> • </html>
  • 143. JSPActions • JSP actions use to control the behavior of the servlet engine. • You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin. • Syntax <jsp:action_name attribute = "value" />
  • 144. JSPActions S.No. Syntax & Purpose 1 jsp:include - Includes a file at the time the page is requested. 2 jsp:useBean - Finds or instantiates a JavaBean. 3 jsp:setProperty - Sets the property of a JavaBean. 4 jsp:getProperty - Inserts the property of a JavaBean into the output. 5 jsp:forward - Forwards the requester to a new page. 6 jsp:plugin - Generates browser-specific code that makes an OBJECT or EMBED tag for the Java plugin. 7 jsp:element - Defines XML elements dynamically. 8 jsp:attribute - Defines dynamically-defined XML element's attribute. 9 jsp:body - Defines dynamically-defined XML element's body. 10 jsp:text - Used to write template text in JSP pages and documents.
  • 145. jsp:include • Syntax of jsp:include action tag without parameter • <jsp:include page="relativeURL | <%= expression %>" /> • Syntax of jsp:include action tag with parameter • <jsp:include page="relativeURL | <%= expression %>"> • <jsp:param name="parametername" value="parametervalue | <%=expression%>" /> • </jsp:include>
  • 146. jsp:include- withoutparameter • In this example, index.jsp file includes the content of the printdate.jsp file. • File: index.jsp • <h2>this is index page</h2> • <jsp:include page="printdate.jsp" /> • <h2>end section of index page</h2> • File: printdate.jsp • <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
  • 147. jsp:include- withparameter • <html> • <body> • This is index.jsp Page • <jsp:include page="display.jsp"> • <jsp:param name=“UName" value=“Akash" /> • <jsp:param name="age" value="27" /> • </jsp:include> • </body> • </html> <html> <body> This is a display.jsp Page Name : <%=request.getParameter(“UName")%> <br> Age: <%=request.getParameter("age")%> </body> </html>
  • 148. jsp:forward actiontag • The jsp:forward action tag is used to forward the request to another resource it may be jsp, html or another resource. • Syntax of jsp:forward action tag without parameter • <jsp:forward page="relativeURL | <%= expression %>" /> • Syntax of jsp:forward action tag with parameter • <jsp:forward page="relativeURL | <%= expression %>"> • <jsp:param name="parametername" value="parametervalue | <%=expression%>" /> • </jsp:forward>
  • 149. jsp:forward- withoutparameter In this example, we are simply forwarding the request to the printdate.jsp file. index.jsp <h2>this is index page</h2> <jsp:forward page="printdate.jsp" /> printdate.jsp <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
  • 150. jsp:forward- withparameter • In this example, we are forwarding the request to the printdate.jsp file with parameter and printdate.jsp file prints the parameter value with date and time. • index.jsp • <h2>this is index page</h2> • <jsp:forward page="printdate.jsp" > • <jsp:param name="name" value=“Bhavana" /> • </jsp:forward> • • printdate.jsp • <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); % • <%= request.getParameter("name") %>
  • 151. jsp:useBean (JavaBeans) • According to Java white paper, it is a reusable software component. A bean encapsulates many objects into one object, so we can access this object from multiple places. Moreover, it provides the easy maintenance.
  • 152. jsp:useBean Simple example of java bean class //Employee.java public class Employee implements java.io.Serializable{ private int id; public Employee(){} public void setName(String name){this.name=name;} public String getName(){return name;} }
  • 153. jsp:useBean • How to access the java bean class? • Toaccess the java bean class, we should use getter and setter methods. • public class Test{ • public static void main(String args[]){ • Employee e=new Employee();//object is created • e.setName("Arjun");//setting value to the object • System.out.println(e.getName()); • }}
  • 154. JSPTemplates • If a Website has multiple pages with identical formats, which is common, even simple layout changes require modifications to all of the pages. • To minimize the impact of layout changes, we need a mechanism for including layout in addition to content; that way, both layout and content can vary without modifying files that use them. • That mechanism is JSP templates. (Same like CSS in HTML)
  • 155. JSPTemplates • Templates are JSP files that include parameterized content. The templates have a set of custom tags: • template:get, • template:put, • template:insert. • Example • <template:get name='header'/> • <template:get name='content'/> • <template:get name='footer'/> • <template:insert template='/articleTemplate.jsp'> • <template:put name='header' content='/header.html' /> • <template:put name='sidebar' content='/sidebar.jsp' /> • <template:put name='content' content='/introduction.html'/> • <template:put name='footer' content='/footer.html' /> • </template:insert>
  • 156. Outline Introduction to JSP Advantages of JSP over Servlet JSP Life cycle JSP Creation in Eclipse Elements of JSP page: directives, comments, scripting elements, actions and templates JDBC Connectivity with JSP.
  • 157. JDBC • Java JDBC is a java API to connect and execute query with the database. JDBC API uses jdbc drivers to connect with the database. • Before JDBC, ODBC API was the database API to connect and execute query with the database. • But, ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and unsecured). • That is why Java has defined its own API (JDBC API) that uses JDBC drivers (written in Java language).
  • 158. JDBCDriver • JDBC Driver is a software component that enables java application to interact with the database. • There are 4 types of JDBC drivers: 1. JDBC-ODBC bridge driver 2. Native-API driver (partially java driver) 3. Network Protocol driver (fully java driver) 4. Thin driver (fully java driver)
  • 159. JDBC Connectivity withJSP • Software Requirement • 1 MySQL • 2 MySQL Connector (Jar file) • 3 Apache Tomcat Server • 4 Eclipse • Important Note: • Copy MySQL Connector (Jar file) into Tomcat’s Bin and Lib folder • Before running program right click on project name -> Build path -> Configure build path -> Libraries -> Add External Jar file -> Mysql .jar file -> ok
  • 160. JDBC Connectivity withJSP- Createtableandaddrowsindatabase(mysql) • Create the Employee table in the db1 database as follows −− • mysql> Create database db1; • mysql> use db1; • mysql> create table emp • ( • id int, • name varchar (255) • ); • Query OK, 0 rows affected (0.08 sec)
  • 161. JDBC Connectivity withJSP- Createtableandaddrowsindatabase(mysql) • Insert Data • mysql> INSERT INTO emp VALUES (100, 'Zara''); • mysql> INSERT INTO Employees VALUES (101, 'Mamta');
  • 162. JSP Code inEclipse • File->New->Web->Dynamic Web Project->Give Project Name • Right click on Project name->new->package->Give package name For Writing JSP Code • project-> Right click->new->JSP file-> Give file name with .jsp • Extension • In Body tag write java code in script let tag <% %> • Right click on .jsp file -> Run -> Run as Server
  • 163. JDBC Connectivity withJSP- Example 1- JSPCodefortoselectdatafromemptable <%@ page import ="java.sql.*" %> <%@ page import ="javax.sql.*" %> <% Class.forName("com.mysql.jdbc.Driver"); java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1","root","root"); Statement st= con.createStatement(); ResultSet rs=st.executeQuery("select * from emp"); out.print("<h2 align=center>Employee Database</h2>"); out.print("<table border=1 align=center>"); out.print("<tr><th> ENo</th> <th>Ename</th></tr>");
  • 164. JDBC Connectivity withJSP- Example1-JSPCodefortoselectdatafromemptable while(rs.next()) { out.print("<tr align=center>"); out.print("<td>"); out.print(rs.getInt(1)); out.print("</td>"); out.print("<td>"); out.print(rs.getString(2)); out.print("</td>"); out.print("</tr>"); } %>
  • 165. JDBC Connectivity withJSP- Example2-JSPCodeforinsertdatainemptableanddisplaythe inserted datafromtable • It requires 2 files • 1. S1.html (Html file to take values fromuser) • 2. s2.jsp (jsp file to insert data in database and to displaythe inserted data)
  • 166. JDBC Connectivity withJSP- Example2-JSPCodeforinsertdatainemptableanddisplaythe inserteddatafromtable • S1.html <html> <body> <form method="post" action=“s2.jsp"> Enter Employee No<input type="text" name="t1"><br> Enter Empoyee Name <input type="text" name="t2"><br> <input type="submit" value="submit"> </form> </body> </html>
  • 167. JDBC Connectivity withJSP- Example2-JSPCodeforinsertdatainemptableanddisplaythe inserteddatafromtable S2.jsp <%@ page import ="java.sql.*" %> <%@ page import ="javax.sql.*" %> <% Class.forName("com.mysql.jdbc.Driver"); java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3307/db1","root","root"); Statement st= con.createStatement(); int id= Integer.parseInt(request.getParameter("t1")); String name=request.getParameter("t2"); st.executeUpdate("insert into emp values("+id+",'"+name+"')");
  • 168. JDBC Connectivity withJSP- Example2-JSPCodeforinsertdatainemptableanddisplaythe inserteddatafromtable ResultSet rs=st.executeQuery("select * from emp"); out.print("<h2 align=center>Employee Database</h2>"); out.print("<table border=1 align=center>"); out.print("<tr><th> ENo</th><th>Ename</th></tr>"); while(rs.next()) { out.print("<tr align=center>"); out.print("<td>"); out.print(rs.getInt(1)); out.print("</td>"); out.print("<td>"); out.print(rs.getString(2)); out.print("</td>"); out.print("</tr>"); } %>
  • 169. References • https://www.javatpoint.com/cookies-in-servlet • https://www.javatpoint.com/hidden-form-field-in-session- tracking • https://www.studytonight.com/servlet/hidden-form-field.php • https://www.studytonight.com/servlet/url-rewriting-for- session-management.php • https://www.tutorialspoint.com/jsp/jsp_overview.htm • https://www.javatpoint.com/jsp-tutorial • https://www.studytonight.com/jsp/introduction-to-jsp.php • https://www.studytonight.com/jsp/creating-a-jsp-page.php • https://www.studytonight.com/jsp/jsp-scripting-element.php • https://www.javatpoint.com/java-jdbc • https://www.javatpoint.com/jsp-include-action
  • 170. Thank You 170 gharu.anand@gmail.com Blog : anandgharu.wordpress.com Prof. Gharu Anand N. 170