Java Server Pages
Java Server Pages
Contents
• Pre-Requisites
• Introduction
• Servlets vs. JSP
• How to Setup the Server
• Servlets
-- Basics
-- Form Data
• JavaServer Pages(JSP)
-- Overview
-- Scripting
• MVC Architecture
• Choice of Developing:
-- Online Stores
-- Web Applications
-- Dynamic Web Sites and Web Pages
• What is CGI?
-- Stands for Common Gateway Interface
-- Is a Simple & Portable Interface for running Ext.
Programs on a Web Server
<html>
<head><title>Cluster Analysis</title></head>
<body>
<form action="/cgi-bin/clusteranalysis.pl" method="GET“>
How many clusters?
<input type=text name="clusters" size=3>
<input type=submit value=" OK ">
</form>
</body>
</html>
• Efficient
• Convenient
• Powerful
• Portable
• It is regular Java code: There are new APIs, but no new syntax.
response.setContentType("text/html");
PrintWriter out = response.getWriter();
<BODY BGCOLOR="#FDF5E6“>
<H1>Welcome to Our Store</H1>
<SMALL>Welcome, <!-- User name is "New User" for first-time visitors -->
<%= coreservlets.Utils.getUserNameFromCookie(request) %>
To access your account settings, click
<A HREF="Account-Settings.html">here.</A>
</SMALL>
<P>Regular HTML for rest of online store’s Web page</P>
</BODY>
</HTML>
• Consider the Codes that we’ve seen: Both look COMPLETELY Different.
• The Servlet looks like a Normal Java Code and the JSP, like a
Normal HTML Page
• But, they are the SAME
• JSP pages get translated into Servlets, the Servlets get compiled, and it is
the Servlets that run at request time.
Contents:
• Installing Java onto the System
• Setting up & Configuring a Server
• Difference between Development
and
Deployment
• Running Test Codes
• Developing Web Applications
• First of all, you MUST have the Proper Software and KNOW
HOW, to Use it
• You must know first, whether you have the correct Version of
JDK to support the Codes that will be given for Compilation
• Then, comes Installing and Configuring the Server
• Setting up the Development Environment would Come down
as the Next Step
• Running Codes to test the Working of the Server and the
other Softwares involved.
• Then proceed to Configuring the “web.xml” file and then
Proceed to Developing a Web Application.
• If J2EE features like Enterprise JavaBeans (EJB) or Java Messaging Service (JMS) are
NOT REQUIRED, the Standard Edition is recommend
• The Installed server will supply the classes needed to add servlet and JSP support to
Java 2 Standard Edition.
• Step 1 comprised of Having the Correct JDK Installed into the System
• Step2: Download a server (often called a “servlet container” or “servlet
engine”)
that implements the Servlet 2.3 Specification (JSP 1.2) or the Servlet
2.4
Specification (JSP 2.0) for use on your desktop
The Server that is Downloaded and Loaded onto the System is called as a
Development Server/Test Server….
If you can run the same server on your desktop that you use for
deployment, all
the better
• To confirm whether the Server has been Properly Configured, or not, before
We run Our Servlets and JSPs
-- Open DOS Command Prompt or Unix Shell and type in the command
prompt:
1. java –version 2. javac –help
A Result must be seen BOTH times
NOT an Error Message about an Unknown Command
• If either of these tests fails, review the installation instructions that came
with the SDK.
• Once the Server’s Working and the JDK is showing NO Problems, then
the Above three Files are Supposed to Work without any problems.
<body>
<H2>Hello! This is a Test Going On.. ;-)</H2>
</body>
</html>
Deployment Implies Placing the Class Files of the Respective Java Files,
in the Server’s Respective Directory. Four Methods for that:
<servlet>
<servlet-name>Testing1</servlet-name>
<servlet-class>Package1.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Testing1</servlet-name>
<url-pattern>/Testing1</url-pattern>
</servlet-mapping>
</web-app>
Contents:
• Life Cycle of a Servlet
• Form Data
• Have already seen How Servlets are Written, Compiled & Executed
• Here, We shall look at the LIFE-CYCLE of a Servlet
• After this, each user request results in a thread that calls the service
method of the previously created instance.
// Continued Part 2…
Wednesday, December 08,
2021
Complete Program:
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Your Lottery Numbers";
String docType ="<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
+"Transitional//EN\">\n";
out.println(docType +
"<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>" + title + "</H1>\n" +
"<B>Based upon extensive research of " +
"astro-illogical trends, psychic farces, " +
"and detailed statistical claptrap, " +
"we have chosen the " + numbers.length +
" best lottery numbers for you.</B>" +
"<OL>");
out.println("</OL>"+"</BODY></HTML>");
<servlet>
<servlet-name>Testing3</servlet-name>
<servlet-class>Package1.LotteryNumbers</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Testing3</servlet-name>
<url-pattern>/Testing3</url-pattern>
</servlet-mapping>
</web-app>
• 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., as
appropriate.
• A POST request results from an HTML form that specifically lists POST
as the METHOD.
// Servlet code
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
• Although this approach takes a couple of extra lines of code, it has several advantages
over directly overriding service.
• Second, you can add support for modification dates by adding a getLastModified method.
• There are many Reasons where a Server may be Removed or HAVE to be removed.
• Example: The server may decide to remove a previously loaded servlet instance,
perhaps because it is explicitly asked to do so by the server administrator or perhaps
because the servlet is idle for a long time.
• 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.
Using Form tag(<FORM>….</FORM>), we shall see how to Achieve the Above Result:
Ever typed: “Java/J2EE Certification” in Google and seen What appears in the URL?
Form data can be attached to the end of the URL after a question mark (as above) for GET
requests;
Form data can also be sent to the server on a separate line for POST requests.
Some of the Following, are the functions that are used for Retrieving Form
Data:
HttpServletRequest
- getParameter
- getParameterValues
- getParameterNames*
- getParameterMap
<CENTER><INPUT TYPE="SUBMIT"></CENTER>
</FORM>
</BODY>
</HTML>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/*@author 258854*/
public class ThreeParams extends HttpServlet{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading Three Request Parameters“;
package Package1;
import java.io.*;
import java.util.*; //For import java.util.Enumeration
import javax.servlet.*; // For import javax.servlet.ServletException;
Import javax.servlet.http.*; // For Http Servlet, ServletRequest and ServletResponse
/* @author 258854*/
public class ShowAllParameters extends HttpServlet{
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<TR><TD>" + paramName + "\n<TD>");
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0)
out.println("<I>No Value</I>");
else
out.println(paramValue);
}
else{
out.println("<UL>");
for(int i=0; i<paramValues.length; i++) {
out.println("<LI>" + paramValues[i]);
}
out.println("</UL>");
}
}
out.println("</TABLE>\n</BODY></HTML>");
}
Contents:
• Overview and Basics
• Scripting/Elements
• Java Beans
• Basics
• Installing JSP Pages
• JSP Syntax
• A Combination of Static and Dynamic Text; Static being the HTML Part and
Dynamic being the Java Content.
• The HTML Part is written like a Normal HTML. The Dynamic Java Code, is
“Embedded” between: “<%” and “%>” respectively
<HTML>
<HEAD>
<TITLE>Order Confirmation</TITLE>
<LINK REL=STYLESHEET HREF="JSP-Styles.css” TYPE="text/css“>
</HEAD>
<BODY>
<H2>Order Confirmation</H2>
Thanks for ordering
<I><%= request.getParameter("title") %></I>!
</BODY>
</HTML>
• Use beans.
Are of 3 Forms:
Comments in JSP are put in the Following Format: <%-- JSP Code --%>
Note: Its always to have as Less Java Code in JSP Pages as Possible
<%--@page import="Package1.RanUtilities;"--%>
<html>
<head>
<title>RandomNums</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="GENERATOR" content="Rational Application Developer">
</head>
<body>
<H1>Random Numbers</H1>
<UL>
<LI><%= Package1.RanUtilities.randomInt(10) %>
<LI><%= Package1.RanUtilities.randomInt(10) %>
<LI><%= Package1.RanUtilities.randomInt(10) %>
<LI><%= Package1.RanUtilities.randomInt(10) %>
<LI><%= Package1.RanUtilities.randomInt(10) %>
</UL>
</body>
</html>
<%--@page import="Package1.RanUtilities"--%>
<html>
<head>
<title>SemiRandomNumber</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="GENERATOR" content="Rational Application Developer">
</head>
<body>
<%!private int randomNum = Package1.RanUtilities.randomInt(10);%>
<H1>Semi-Random Number:<BR><%= randomNum %></H1>
</body>
</html>
Controller - Servlet
View - JSP
Model - EJBs
• Storing data that the JSP page will use only in this request
Next, the servlet would forward the request to a JSP page that uses the
following to retrieve the data.
Next, the servlet would forward to a JSP page that uses the following to
retrieve the data in the following fashion:
Next, the servlet would forward to a JSP page that uses the following to
retrieve the data:
String address;
if (operation.equals("order")) { address = "/WEB-INF/Order.jsp”; }
else if (operation.equals("cancel")) { address = "/WEB-INF/Cancel.jsp”; }
else { address = "/WEB-INF/UnknownOperation.jsp”; }
• asdasdas
• Once the request arrives at the JSP page, the JSP page uses jsp:useBean and
jsp:getProperty to extract the data.
package BankingEg;
import java.util.HashMap;
//Getters
public String getId(){
return(id);
}
public String getFirstName(){
return(firstName);
}
public String getLastName(){
return(lastName);
}
public double getBalance() {
return(balance);
}
public double getBalanceNoSign(){
return(Math.abs(balance));
}
//One Setter...
public void setBalance(double balance){
this.balance = balance;
}
// Continued Part3….
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/* @author 258854 */
public class ShowBalance extends HttpServlet{
if (customer == null) {
address = "/Web-Docs/Banking Folder/UnknownCustomer.jsp“;
}
else if (customer.getBalance() < 0) {
address = "/Web-Docs/Banking Folder/NegativeBalance.jsp“;
request.setAttribute("badCustomer", customer);
}
else if (customer.getBalance() < 10000) {
address = "/Web-Docs/Banking Folder/NormalBalance.jsp“;
request.setAttribute("regularCustomer", customer);
}
<html>
<head>
<title>UnknownCustomer</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="GENERATOR" content="Rational Application Developer">
</head>
<body>
<TABLE BORDER=5 ALIGN="CENTER">
<TR><TH CLASS="TITLE">
Unknown Customer
</TABLE>
<P>Unrecognized customer ID.</P>
</body>
</html>
<P>
<jsp:useBean id="badCustomer" type="BankingEg.BankCustomer" scope="request" />
Watch out,<jsp:getProperty name="badCustomer" property="firstName" />,
we know where you live.
</P>
<P>
Pay us the
$<jsp:getProperty name="badCustomer" property="balanceNoSign" />
you owe us before it is too late!
</P>
</body>
</html>
ID = “id000”
ID = “id001”
ID = “id003”