You are on page 1of 36

Java Server

Pages (JSP)
U. K. R.
Dept. of IT, JU
u_roy@it.jusl.ac.in
Web Development
 Static html
 – text file containing html tags created
manually
 – may include some client-side scripts (e.g.
JavaScript)
 Active html
 html contains a program that runs at the client
 Java Applets
 Dynamic html
 – html file produced at time of request

 – cgi, php, asp, jsp, Servlets


Static HTML
Active HTML
History of Dynamic Web Content
 The Common Gateway Interface (CGI)
 Used scripts, and a process was dispatched for
each web page generated.
 Problems
 Datasets became large
 Increased traffic on sites
 Trouble maintaining state and session
information
 Performance bottlenecks
 Can involve proprietary APIs
History of Dynamic Web Content
 Numerous second generation alternatives
were invented:
 FastCGI, mod_perl, NSAPI, ISAPI, Java
Servlets
 These embedded HTML in programming code.
Hence costly in programmer time.
Scripting—the Third Generation
Approach
 Idea: embed simple code in HTML pages!
 The HTML pages use the code to choose
what elements and data to display.
 Classes and/or subroutines may be called
to compute information for inclusion in the
web page. Existing APIs can be invoked.
 This is known as ‘scripting’.
Some Approaches to Scripting
 JavaServer Pages –(uses Java)
 Active Server Pages
 (uses VBScript, Jscript, COM or ActiveX
components, ODBC). ASP.NET is quite similar to
JSP, using C#. Has not been very popular.
 PHP
 (C-like syntax, many functions available, insecure)
 ColdFusion (proprietary)
 Others…
Java Web Application Architecture

Browser
HTTP / HTML

Application Server

Servlet JSP

Java Classes DB / ERP /


/ EJB Legacy
Java Servlets
 Currently, Java is the predominant language for
SSP. This is due to the Java Servlet API.
 Advantages over other SSP technologies:
 Persistent between invocations, avoiding process
instantiations.
 Portable across operating systems and servers.
 Good security.
 Can use the Java APIs, particularly JDBC.
 Is integrated closely with the J2EE environment.
Introduction to Servlet
 Java’s answer to SSP
 is a simple, consistent mechanism for extending
the functionality of a web server
 Are precompiled Java programs that are
executed on the server side.
 Require a Servlet container to run in

 When would you use servlets?


 Page is based on user-submitted data e.g search
engines
 Data changes frequently e.g. weather-reports
 Page uses information from a databases e.g. on-
line stores
Architecture
Servlet Lifecycle
 A client makes a request involving a servlet
running on the server.
 The servlet is responsible for loading and
executing the Java classes that generate the
HTML content.
 To the client, this looks like standard HTML
processing, except faster.
 The servlet then need not shut down. Instead, it
can handle subsequent requests without
restarting.
Basic Servlet Structure
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SomeServlet extends HttpServlet {
// Handle get request
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException {
// request – access incoming HTTP headers and HTML
form data
// response - specify the HTTP response line and
headers
// (e.g. specifying the content type, setting cookies).

PrintWriter out = response.getWriter(); //out - send


content to browser
}
}
A Simple Servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet {


public void doGet(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException {

PrintWriter out = response.getWriter();


out.println("Hello World");
}
}
Generating HTML
public class HelloWWW extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>\n" +

"<HEAD><TITLE>HelloWWW</TITLE></HEAD
>\n" +
"<BODY>\n" + "<H1>Hello
WWW</H1>\n" +
"</BODY></HTML>");
}
}
Java Server Pages
 JSPs are equivalent to Servlets
 A simplified, fast way to create dynamic web
content
 HTML or XML pages with embedded Java Code
or Java Beans
 Can be a mix of template data in HTML/XML with
some dynamic content
 A JSP is a complied to a Java Servlet
automatically by the Servlet container, it is then
cached
Predefined objects
 You can declare your own variables, as
usual
 JSP provides several predefined variables
 request : The HttpServletRequest parameter
 response : The HttpServletResponse parameter
 session : The HttpSession associated with the
request, or null if there is none
 out : A JspWriter (like a PrintWriter) used to
send output to the client
 Example:
 Your hostname: <%= request.getRemoteHost() %>
JSP Tags
 Four types of tags
 Directives
 Used to import packages, define error handling
pages or the session information of the JSP page
 Declaration
 used for defining the functions and variables to be
used in the JSP
 Scriplets
 Used to insert any amount of valid java code
 Expression
 Used to output any data on the generated page
Directives
 Directives affect the servlet class itself
 A directive has the form:
<%@ directive attribute="value" %>
or
<%@ directive attribute1="value1"
attribute2="value2"
...
attributeN="valueN" %>
 The most useful directive is page, which lets
you import packages
 Example: <%@ page import="java.util.*" %>
page Directives
 Example
 <%@page language="java" %>
 <%@page import="java.sql.* %>
 <%@page extends="mypackage.myclass" %>
 <%@page session="true" %>
 <%@page errorPage="error.jsp" %>
 <%@page contentType="text/html;charset=ISO-
8859-1" %>
The include directive
 The include directive inserts another file
into the file being parsed
 The included file is treated as just more JSP,
hence it can include static HTML, scripting
elements, actions, and directives
 Syntax: <%@ include file="URL " %>
 The URL is treated as relative to the JSP page
 If the URL begins with a slash, it is treated as
relative to the home directory of the Web server
 The include directive is especially useful
for inserting things like navigation bars
Directives
 Syntax
<%@directive attribute="value" %>
<%@ directive attribute1="value1"
attribute2="value2"
...
attributeN="valueN" %>
 Directive may be
 page:
 Used to provide the information about it

 include:
 Used to include a file in the JSP page

 taglib:
 used to use the custom tags in the JSP pages
Directives
 include
 <%@ include file="/header.jsp" %>
 taglib
 <%@ taglib uri="tlds/taglib.tld" prefix="mytag" %>
Actions
 Actions are XML-syntax tags used to
control the servlet engine
 <jsp:include page="URL " flush="true" />
 Inserts the indicated relative URL at execution
time (not at compile time, like the include
directive does)
 This is great for rapidly changing data

 <jsp:forward page="URL" />


<jsp:forward page="<%= JavaExpression
%>" />
 Jump to the (static) URL or the (dynamically
computed) JavaExpression resulting in a URL
Declaration
 Syntax <%@page contentType="text/html" %>
<%! <html>
<body>
//declarations <%!
%> int cnt=0;
private int getCount(){
 Example //increment cnt and return the value
cnt++;
return cnt;
}
%>
<p>Values of Cnt are:</p>
<p><%=getCount()%></p>
</body>
</html>
Scriplets
 Syntax
<%
//java code
%>
Example
<%
//java codes
String userName=null;
userName=request.getParameter("userName");
%>
Expression
 Syntax
<%=expression%>
Example
<%="Hello World!" %>

<HTML>
<BODY>
Hello!  The time is now <%= new java.util.Date() %>
</BODY>
</HTML>
Session Tracking
 Typical scenario – shopping cart in online store
 Necessary because HTTP is a "stateless"
protocol
 Common solutions: Cookies and URL-rewriting
 Session Tracking API allows you to
 look up session object associated with current
request
 create a new session object when necessary
 look up information associated with a session
 store information in a session
 discard completed or abandoned sessions
Session Tracking API
 Looking up a session object
 HttpSession session = request.getSession(true);
 Pass true to create a new session if one does
not exist
 Associating information with session
 session.setAttribute(“user”,request.getParamete
r(“name”))
 Session attributes can be of any type
 Looking up session information
 String name = (String)
session.getAttribute(“user”)
JSP and JavaBeans
 A JavaBean is a Java Class file that
creates an object
 Defines how to create an Object, retrieve
and set properties of the Object

Set Bean Value


JavaBeans JSP
Get Bean Value
JSP and JavaBeans (Cont’d)
 JavaBeans can store data
 JavaBeans can perform complex calculations
 JavaBeans can hold business logic
 JavaBeans can handle Database Connectivity
and store data retrieved from them
 JavaBeans facilitate
 Reuse of code
 Debugging process
 Separating code from content
Java Beans in Web Apps
 Normally used for all data transfers and
business components
 Similar to how Java Beans are used in Swing
and AWT
 But do not need the full implementation
 Must have no constructor or no-arg constructor
 Must have setter and getter methods for each
property value
 JSP constructs/tags use Java Beans
JSP Actions
 JSP actions are special tags that affect the
output stream and are normally used with
Java beans
 Most commonly used:
 <jsp:useBean>, <jsp:getProperty>,
<jsp:setProperty>
 The code below will display the lastName property of

the student bean on the output stream


<jsp:useBean id="student" scope="request"
class="com.lucek.dto.StudentValue" />
<jsp:getProperty name="student" property="lastName"
/>

You might also like