Chapter 7 JSP
Chapter 7 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?
• 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 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
• 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!!!