0% found this document useful (0 votes)
3 views

Chapter 7 JSP

Chapter 6 discusses Java Server Pages (JSP), a server-side technology for creating dynamic web applications using Java. It highlights the advantages of JSP over CGI and servlets, including better performance, ease of maintenance, and access to Java APIs. The chapter also covers JSP architecture, lifecycle, scripting elements, implicit objects, and action tags, providing a comprehensive overview for developers looking to utilize JSP in their applications.

Uploaded by

temsgentesfaye1
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Chapter 7 JSP

Chapter 6 discusses Java Server Pages (JSP), a server-side technology for creating dynamic web applications using Java. It highlights the advantages of JSP over CGI and servlets, including better performance, ease of maintenance, and access to Java APIs. The chapter also covers JSP architecture, lifecycle, scripting elements, implicit objects, and action tags, providing a comprehensive overview for developers looking to utilize JSP in their applications.

Uploaded by

temsgentesfaye1
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 62

Chapter 6

Java Servlet Pages (JSP)

Chapter 6
Introduction
• Java Server Pages (JSP) is a server-side programming technology.
• It enables the creation of dynamic, platform-independent method for building
Web-based applications.
• JSP have access to the entire family of Java APIs, including the JDBC API to access
enterprise databases
Why to Learn JSP?

• JavaServer Pages often serve the same purpose as programs implemented


using the Common Gateway Interface (CGI).
• But JSP offers several advantages in comparison with the CGI.
• Performance is significantly better because JSP allows embedding Dynamic
Elements in HTML Pages itself instead of having separate CGI files.
• JSP are always compiled before they are processed by the server unlike
CGI/Perl which requires the server to load an interpreter and the target
script each time the page is requested.
• JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP
also has access to all the powerful Enterprise Java APIs, including JDBC, JNDI,
EJB, JAXP, etc.
Cont’d
• JSP pages can be used in combination with servlets that handle the
business logic, the model supported by Java servlet template engines
• Finally, JSP is an integral part of Java EE, a complete platform for
enterprise class applications.
• This means that JSP can play a part in the simplest applications to the
most complex and demanding.
Applications of JSP

• JSP 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.
• JSP vs. Pure Servlets
• It is more convenient to write (and to modify!) regular HTML than to
have plenty of println statements that generate the HTML
JSP vs. Server-Side Includes (SSI)

• SSI is really only intended for simple inclusions, not for "real"
programs that use form data, make database connections, and the
like.
• JSP 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.
• JSP vs. Static HTML
• Regular HTML, of course, cannot contain dynamic information.
JSP - Environment Setup
• A development environment is where you would develop your JSP programs,
test them and finally run them.
• Setting up Java Development Kit
• This step involves downloading an implementation of the Java Software
Development Kit (SDK) and setting up the PATH environment variable
appropriately.
• Setting up Web Server: Tomcat
• A number of Web Servers that support JavaServer Pages and Servlets
development are available in the market.
• Apache Tomcat is an open source software implementation of the JavaServer
Pages and Servlet technologies and
JSP - Architecture

• The web server needs a JSP engine, i.e, a container to process JSP
pages.
• The JSP container is responsible for intercepting requests for JSP
pages.
• A JSP container works with the Web server to provide the runtime
environment and other services a JSP needs.
• It knows how to understand the special elements that are part of
JSPs.
Architecture of
JSP
JSP Processing

• As with a normal page, your browser sends an HTTP request to the web
server.
• The web server recognizes that the HTTP request is for a JSP page and
forwards it to a JSP engine.
• This is done by using the URL or JSP page which ends with .jsp instead
of .html.
• The JSP engine loads the JSP page from disk and converts it into a
servlet content.
• This conversion is very simple in which all template text is converted to
println( ) statements and all JSP elements are converted to Java code.
Cont’d
• he JSP engine compiles the servlet into an executable class and forwards the
original request to a servlet engine.
• A part of the web server called the servlet engine loads the Servlet class and
executes it.
• During execution, the servlet produces an output in HTML format.
• The output is furthur passed on to the web server by the servlet engine
inside an HTTP response.
• The web server forwards the HTTP response to your browser in terms of
static HTML content.
• Finally, the web browser handles the dynamically-generated HTML page
inside the HTTP response exactly as if it were a static page.
JSP Processing
Java Servlet Life Cycle
• It is defined as the process from its creation till the destruction.
• This is similar to a servlet life cycle with an additional step which is
required to compile a java Servlet into servlet.
• The following are the paths followed by a JS−
• Compilation
• Initialization
• Execution
• Cleanup
Servlets - Life Cycle

• A servlet life cycle can be defined as the entire process from its creation till the
destruction.
• The following are the paths followed by a servlet.
• 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, just as with the init method of
applets.
• The servlet is normally created when a user first invokes a URL
corresponding to the servlet, but you can also specify that the servlet be
loaded when the server is first started.
• 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.
Init() method
• 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.
• Each time the server receives a request for a servlet, the server spawns a
new thread and calls service.
• The service() method checks the HTTP request type (GET, POST, PUT,
DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as
appropriate.
Service() 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.
• Java Code
• 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. This method gives your servlet a chance to close database
connections, halt background threads, write cookie lists or hit counts to
disk, 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...
•}
Java web ..used for JavaServelet
Java Servlet in Netbeans
Writing HTML in WEB.INF/Webpages
Writing Java code in Source
packages
JSP
• 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 Tags, etc.
• Advantages of JSP over Servlet
• There are many advantages of JSP over the Servlet. They are as follows:
• 1) Extension to Servlet
• JSP technology is the extension to Servlet technology. We can use all the features of the 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 many tags such as action tags, JSTL, custom tags, etc. that reduces the code. Moreover,
we can use EL, implicit objects, etc.
The Lifecycle of a JSP Page
• The JSP pages follow these phases:
• Translation of JSP Page
• Compilation of JSP Page
• Classloading (the classloader loads class file)
• Instantiation (Object of the Generated Servlet is created).
• Initialization ( the container invokes jspInit() method).
• Request processing ( the container invokes _jspService() method).
• Destroy ( the container invokes jspDestroy() method).
Cont’d…
Creating a simple JSP Page
• To create the first JSP page, write some HTML code as given below, and save
it by .jsp extension. We have saved this file as index.jsp.
• Put it in a folder and paste the folder in the web-apps directory in apache
tomcat to run the JSP page.
• index.jsp
• Let's see the simple example of JSP where we are using the scriptlet tag to
put Java code in the JSP page.
1.<html>
2.<body>
3.<% out.print(2*5); %>
4.</body>
5.</html>
The Directory structure of JSP
Cont’d…
• The JSP API consists of two packages:
• javax.servlet.jsp
• javax.servlet.jsp.tagext
• javax.servlet.jsp package
• The javax.servlet.jsp package has two interfaces and classes.The two interfaces are as follows:
• JspPage
• HttpJspPage
• The classes are as follows:
• JspWriter
• PageContext
• JspFactory
• JspEngineInfo
• JspException
• JspError
The JspPage interface
• According to the JSP specification, all the generated servlet classes
must implement the JspPage interface.
• It extends the Servlet interface. It provides two life cycle methods.
SP Scriptlet tag (Scripting elements)
• In JSP, java code can be written inside the jsp page using the scriptlet
tag. Let's see what are the scripting elements first.
• JSP Scripting elements
• The scripting elements provides the ability to insert java code inside
the jsp. There are three types of scripting elements:
• scriptlet tag
• expression tag
• declaration tag
Cont’d…
• Example of JSP scriptlet tag
• In this example, we are displaying a welcome message.
• <html>
• <body>
• <% out.print("welcome to jsp"); %>
• </body>
• </html>
Example of JSP scriptlet tag that
prints the user name
• In this example, we have created two files index.html and
welcome.jsp.
• The index.html file gets the username from the user and the
welcome.jsp file prints the username with the welcome message.
Index.html
• <html>
• <body>
• <form action="welcome.jsp">
• <input type="text" name="uname">
• <input type="submit" value="go"><br/>
• </form>
• </body>
• </html>
Welcome.jsp
• <html>
• <body>
• <%
• String name=request.getParameter("uname");
• out.print("welcome "+name);
• %>
• </form>
• </body>
• </html>
JSP expression tag
• The code placed within JSP expression tag is written to the output
stream of the response. So you need not write out.print() to write
data.
• It is mainly used to print the values of variable or method.
• Syntax of JSP expression tag
• <%= statement %>
Cont’d…
• In this example of jsp expression tag, we are simply displaying a
welcome message.
• <html>
• <body>
• <%= "welcome to jsp" %>
• </body>
• </html>
Cont’d…
• To display the current time, we have used the getTime() method of
Calendar class.
• The getTime() is an instance method of Calendar class, so we have called
it after getting the instance of Calendar class by the getInstance()
method.
• <html>
• <body>
• Current Time: <%= java.util.Calendar.getInstance().getTime() %>
• </body>
• </html>
JSP declaration tag
• The JSP declaration tag is used to declare fields and methods.
• The code written inside the jsp declaration tag is placed outside the
service() method of auto generated servlet.
• So it doesn't get memory at each request.
• The syntax of the declaration tag is as follows:
• <%! field or method declaration %>
Example
• index.jsp
• <html>
• <body>
• <%! int data=50; %>
• <%= "Value of the variable is:"+data %>
• </body>
• </html>
Declaring methods
• <html>
• <body>
• <%!
• int cube(int n){
• return n*n*n*;
• }
• %>
• <%= "Cube of 3 is:"+cube(3) %>
• </body>
• </html>
JSP Implicit Objects
• There are 9 jsp implicit objects. These objects are created by the web
container that are available to all the jsp pages.
• The available implicit objects are out, request, config, session,
application etc.
Cont’d…
Object Type
out JspWriter
request HttpServletRequest
response HttpServletResponse
config ServletConfig
application ServletContext
session HttpSession
pageContext PageContext
page Object
exception Throwable
Cont’d…
• Example of JSP request implicit object
• index.html
• <form action="welcome.jsp">
• <input type="text" name="uname">
• <input type="submit" value="go"><br/>
• </form>
• welcome.jsp
• <%
• String name=request.getParameter("uname");
• out.print("welcome "+name);
• %>
response implicit object
• Example of response implicit object
• index.html
• <form action="welcome.jsp">
• <input type="text" name="uname">
• <input type="submit" value="go"><br/>
• </form>
• welcome.jsp
• <%
• response.sendRedirect("http://www.google.com");
• %>
JSP Action Tags
JSP Action Tags Description

jsp:forward forwards the request and response to


another resource.
jsp:include includes another resource.
jsp:useBean creates or locates bean object.
jsp:setProperty sets the value of property in bean object.

jsp:getProperty prints the value of property of the bean.

jsp:plugin embeds another components such as


applet.
jsp:param sets the parameter value. It is used in
forward and include mostly.

jsp:fallback can be used to print the message if plugin


is working. It is used in jsp:plugin.
Forward page
• index.jsp
• <html>
• <body>
• <h2>this is index page</h2>
• <jsp:forward page="printdate.jsp" />
• </body>
• </html>
• printdate.jsp
• <html>
• <body>
• <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
• </body>
• </html>
jsp:include page
• 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()); %>
Addition of two number
• <!DOCTYPE html>
• <html>
• <head>
• <title>Addition</title>
• </head>
• <body>
• <h2>Addition</h2>
• <form action="addition.jsp" method="post">
• <input type="text" name="num1" placeholder="Enter number 1" /><br>
• <input type="text" name="num2" placeholder="Enter number 2" /><br>
• <input type="submit" value="Add" />
• </form>
• </body>
• </html>
• <%
• // Retrieve the values entered by the user
• String num1Str = request.getParameter("num1");
• String num2Str = request.getParameter("num2");
• int num1 = Integer.parseInt(num1Str);
• int num2 = Integer.parseInt(num2Str);
• int sum = num1 + num2;
• %>
• <!DOCTYPE html>
• <html>
• <head>
• <title>Addition</title>
• </head>
• <body>
• <h2>Addition Result</h2>
• <p>Number 1: <%= num1 %></p>
• <p>Number 2: <%= num2 %></p>
• <p>Sum: <%= sum %></p>
• </body>
• </html>
JavaBean
• A JavaBean is a Java class that should follow the following
conventions:
• It should have a no-arg constructor.
• It should be Serializable.
• It should provide methods to set and get the values of the properties,
known as getter and setter methods.
• A bean encapsulates many objects into one object so that we can
access this object from multiple places. Moreover, it provides easy
maintenance.
Cont’d…
• The jsp:useBean action tag is used to locate or instantiate a bean
class.
• If bean object of the Bean class is already created, it doesn't create
the bean depending on the scope.
• But if object of bean is not created, it instantiates the bean
Cont’d…
• Syntax of jsp:useBean action tag
• <jsp:useBean id= "instanceName" scope= "page | request | session
| application"
• class= "packageName.className" type= "packageName.className"

• beanName="packageName.className | <%= expression >" >


• </jsp:useBean>
Cont’d…

• Attributes and Usage of jsp:useBean action tag


• id: is used to identify the bean in the specified scope.
• scope: represents the scope of the bean. It may be page, request,
session or application. The default scope is page.
• page: specifies that you can use this bean within the JSP page. The
default scope is page.
• request: specifies that you can use this bean from any JSP page that
processes the same request. It has wider scope than page.
• session: specifies that you can use this bean from any JSP page in the
same session whether processes the same request or not. It has
wider scope than request.
Cont’d…
• application: specifies that you can use this bean from any JSP page in
the same application. It has wider scope than session.
• class: instantiates the specified bean class (i.e. creates an object of
the bean class) but it must have no-arg or no constructor and must
not be abstract.
• type: provides the bean a data type if the bean already exists in the
scope. It is mainly used with class or beanName attribute. If you use it
without class or beanName, no bean is instantiated.
• beanName: instantiates the bean using the
java.beans.Beans.instantiate() method.
Calculator.java (a simple Bean class)

• package com.java;
• public class Calculator{
• public int cube(int n){return n*n*n;}
• }
• index.jsp file
• <jsp:useBean id="obj" class="com.java.Calculator"/>
• <%
• int m=obj.cube(5);
• out.print("cube of 5 is "+m);
• %>
Cont’d…
• index.html
• <form action="process.jsp" method="post">
• Name:<input type="text" name="name"><br>
• Password:<input type="password" name="password"><br>
• Email:<input type="text" name="email"><br>
• <input type="submit" value="register">
• </form>
Cont’d…
• process.jsp
• <jsp:useBean id="u" class="org.sssit.User"></jsp:useBean>
• <jsp:setProperty property="*" name="u"/>
• Record:<br>
• <jsp:getProperty property="name" name="u"/><br>
• <jsp:getProperty property="password" name="u"/><br>
• <jsp:getProperty property="email" name="u" /><br>
Cont’d…
• User.java
• package org.sssit;
• public class User {
• private String name,password,email;
• //setters and getters
•}
Thank you!!!

You might also like