This document provides an overview of server-side technologies, specifically focusing on servlets and Tomcat. It begins with an introduction to servlets, covering their lifecycle, advantages over CGI, and architecture. It then discusses Tomcat, the requirements to run servlets, and how to configure Tomcat in Eclipse. The document outlines the steps to create and run a sample servlet program in Eclipse. It provides examples of servlet code to print "Hello World", read form data, and manage sessions. Overall, the document serves as a tutorial on servlets and Tomcat for educational purposes.
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.
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
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
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.
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.
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
• }
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);
}
}
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.
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
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.
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)
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