SlideShare una empresa de Scribd logo
1 de 19
Java Servlets
Java Server Pages
(JSP)
Overview of History
CGI
(in C)
Template
(ASP, PHP)
Servlet
CGI
(java, C++)
JSP
Speed, Security
complexity
HelloWorld
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<head>");
out.println("<title>Hello CS764!</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello CS764!</h1>");
out.println("</body>");
out.println("</html>");
out.close();
}
}
<html><head></head>
<body>
<a href="../servlet/HelloWorld">
<h1>Execute HelloWorld Servlet</h1>
</a>
</body>
</html>
<html>
<head>
<title>Hello CS764!</title></head>
<body>
<h1>Hello CS764!</h1>
</body>
</html>
Client - Server - DB
Client
(browser)
Web server
(Apache, JWS)
Database
server (DB2)
Through
internet
Return html file
(Response)
Trigger Servlet, JSP
(Request)
JDBC,
intranet
Request
data
Return
data
Life Cycle of Servlet
init(ServletConfig);
service(ServletRequest,
ServletResponse);
destroy();
servlet
GenericServlet HttpServlet
doGet(HttpServletRequest,
HttpServletResponse);
doPost(HttpServletRequest,
HttpServletResponse);
…….
Interaction with Client
• HttpServletRequest
– String getParameter(String)
– Enumeration getParameters(String[])
• HttpServletResponse
– Writer getWriter()
– ServletOutputStream getOutputStream()
• Handling GET and POST Requests
Assignment 2:
Get Stock Price
<html><head></head>
<body>
<form action="../servlet/Ass2Servlet"
method=POST>
<h2>Stock Symbol name:
<input type=text name="stockSymbol"></h2><br>
<input type="submit" value = "get price">
</form>
</body></html>
Client Side
Ass2.html
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Ass2Servlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse res)
throws IOException, ServletException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String stockSymb = request.getParameter("stockSymbol");
StockGrabber sg = new StockGrabber();
sg.setStockSymbol(stockSymb); // Set the stock symbol as “input”
String stockPrice = sg.getPrice();// Get the price of stock
System.out.println("After StockGrabber.getPrice --"+stockPrice);// Debug
out.println("<html><head></head><body><br><br>");
out.println(stockSymb + " -- " + stockPrice);
out.println("<hr>");
out.println("<form action="../servlet/Ass2Servlet" method=POST>");
out.println("<h3>Stock Symbol name: <input type=text name="stockSymbol"></h3>");
out.println("<input type=submit value="get price">");
out.println("</form>");
out.println("</body></html>");
}
}
Ass2Servlet
Java Server Pages (JSP)
Client’s
Computer
Server
1.Browser requests HTML
7. Server sends HTML
back to browser
servlet
servlet
class 5.The servlet
runs and
generates
HTML
Java Engine
6. Java Engine sends HTML to server
2. Server sends requests to Java Engine
3. If needed, the Java Engine
reads the .jsp file
4. The JSP is turned into a
servlet, compiled, and loaded
Bean
A First JSP
<html>
<head></head>
<body>
<p>Enter two numbers and click the
‘calculate’ button.</p>
<form action=“calculator.jsp” method=“get”>
<input type=text name=value1><br>
<input type=text name=value2 ><br>
<input type=submit name=calculate value=calculate>
</form>
</body>
</html>
Calculator.html
<html>
<head><title>A simple calculator: results</title></head>
<body>
<%-- A simpler example 1+1=2 --%>
1+1 = <%= 1+1 %>
<%-- A simple calculator --%>
<h2>The sum of your two numbers is:</h2>
<%= Integer.parseInt(request.getParameter("value1")) +
Integer.parseInt(request.getParameter("value2")) %>
</body>
</html>
Calculator.jsp
JSP Tags
• Comments <%-- …...text…... --%>
• Declaration <%! int i; %>
<%! int numOfStudents(arg1,..) {} %>
• Expression <%= 1+1 %>
• Scriptlets <% … java code … %>
• include file <%@ include file=“*.jsp” %>
• …...
Using Java Bean
1. <jsp:useBean id=“bean1” class=“Bean1”/>
2. <jsp:useBean id=“bean1” class=“Bean1” name=“serBean” type=“SerBean1”/>
Declaration
Getting property
1. <jsp:getProperty name=“bean1” property=“color”/>
2. <%=bean1.getColor() %>
Setting property
1. <jsp:setProperty name=“bean1” property=“color” value=“red”/>
2. <jsp:setProperty name=“bean1” property=“color”/>
3. <jsp:setProperty name=“bean1” property=“color” param=“bgColor”/>
4. <jsp:setProperty name=“bean1” property=“*”/>
Assg2
example
<html>
<head></head>
<body>
<center>
<table border = 0>
<form action=ass2.jsp method = POST>
<tr><td><font color=blue>choose a stock market:</font></td>
<td><select name="stockMarket">
<option value="Waterhouse">Waterhouse</option>
<option value="Yahoo">Yahoo</option>
<option value="ChicagoStockex">Chicago Stockex</option>
<option value="Reuters">Reuters</option>
</select></td>
</tr>
<tr><td><font color = blue>input a stock symbol:</font></td>
<td><input type="edit" name="stockSymbol" size=15></td>
</tr>
<tr><td></td><td><input type="submit" value = "get price"></td></tr>
</table>
</form></center>
</body></html>
Client side
Ass2.html
Server side
ass2.jsp
<html><head>
<jsp:useBean id="ass2" scope="session" class="ass2.StockGrabber" />
<jsp:setProperty name="ass2" property="*" />
</head>
<body><h2><%
ass2.processInput();
ass2.getPrice();
%>
<center><table border=5>
<tr><td># of data</td> <td>Stock Market</td> <td>Stock Symbol</td> <td>Stock Price </td>
</tr><%
String[] stockMarkets = ass2.getStockMarkets();
String[] symbols = ass2.getSymbols();
String[] prices = ass2.getPrices();
for(int i=0; i<prices.length; i++){
%>
<tr><td> <%= i+1 %> </td>
<td> <%= stockMarkets[i] %> </td>
<td> <%= symbols[i] %> </td>
<td><font color=red><%= prices[i] %></font></td>
</tr><%
}
%>
</table>
</center>
</h2>
<hr><%@include file="ass2.html" %></html>
<jsp:setProperty name=“ass2” property=“stockSymbol”/>
<jsp:setProperty name=“ass2” property=“stockMarket”/>
Without using JDBC
Public class StockGrabber {
...
public void processInput(){
if(stockMarket.compareTo("Waterhouse")==0){
setPrePriceString("<!--Last-->");
setPostPriceString("</FONT>");
setUrlPrefix("http://research.tdwaterhouse.com/
waterhouse/quote.asp?ticker=");
}
else if(stockMarket.compareTo("Yahoo")==0){
setPrePriceString("<td nowrap><b>");
setPostPriceString("</b></td>");
setUrlPrefix("http://finance.yahoo.com/q?s=");
}
...
else if(...){}
...
else{...}
}
...
}
Using JDBC --> Database
import java.sql.*;
Public class StockGrabber {
...
public void processInput(){
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String sourceURL="jdbc:odbc:stockInfo";
Connection databaseConnection=DriverManager.getConnection(sourceURL);
Statement statement=databaseConnection.createStatement();
ResultSet info =statement.executeQuery(
"select tPrePriceStr, tPostPriceStr, tUrlPrefix
from stockMarketData
where tStockMarket = stockMarket”);
while(inf.next())
{
prePriceString = info.getString(”tPrePriceStr");
postPriceString = info.getString(“tPostPriceStr”);
urlPrefix = info.getString(“tUrlPrefix”);
}
}
catch(SQLException e){ ... }
...
}
}

Más contenido relacionado

La actualidad más candente

Scala ActiveRecord
Scala ActiveRecordScala ActiveRecord
Scala ActiveRecord
scalaconfjp
 
Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)
Jacob Kaplan-Moss
 
Deploying
DeployingDeploying
Deploying
soon
 
深入淺出 MVC
深入淺出 MVC深入淺出 MVC
深入淺出 MVC
Jace Ju
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Paulo Ragonha
 
The Best (and Worst) of Django
The Best (and Worst) of DjangoThe Best (and Worst) of Django
The Best (and Worst) of Django
Jacob Kaplan-Moss
 
Head First Zend Framework - Part 1 Project & Application
Head First Zend Framework - Part 1 Project & ApplicationHead First Zend Framework - Part 1 Project & Application
Head First Zend Framework - Part 1 Project & Application
Jace Ju
 

La actualidad más candente (20)

Rails Security
Rails SecurityRails Security
Rails Security
 
Django REST Framework
Django REST FrameworkDjango REST Framework
Django REST Framework
 
Deploy and Manage the Infrastructure Using Azure Resource Manager
Deploy and Manage the Infrastructure Using Azure Resource ManagerDeploy and Manage the Infrastructure Using Azure Resource Manager
Deploy and Manage the Infrastructure Using Azure Resource Manager
 
Introduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress DevelopersIntroduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress Developers
 
Scala ActiveRecord
Scala ActiveRecordScala ActiveRecord
Scala ActiveRecord
 
CodeIgniter 3.0
CodeIgniter 3.0CodeIgniter 3.0
CodeIgniter 3.0
 
Django - 次の一歩 gumiStudy#3
Django - 次の一歩 gumiStudy#3Django - 次の一歩 gumiStudy#3
Django - 次の一歩 gumiStudy#3
 
Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)
 
Deploying
DeployingDeploying
Deploying
 
深入淺出 MVC
深入淺出 MVC深入淺出 MVC
深入淺出 MVC
 
JSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTLJSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTL
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
 
Basic JSTL
Basic JSTLBasic JSTL
Basic JSTL
 
The Best (and Worst) of Django
The Best (and Worst) of DjangoThe Best (and Worst) of Django
The Best (and Worst) of Django
 
Caldera Learn - LoopConf WP API + Angular FTW Workshop
Caldera Learn - LoopConf WP API + Angular FTW WorkshopCaldera Learn - LoopConf WP API + Angular FTW Workshop
Caldera Learn - LoopConf WP API + Angular FTW Workshop
 
Single Page Web Apps As WordPress Admin Interfaces Using AngularJS & The Word...
Single Page Web Apps As WordPress Admin Interfaces Using AngularJS & The Word...Single Page Web Apps As WordPress Admin Interfaces Using AngularJS & The Word...
Single Page Web Apps As WordPress Admin Interfaces Using AngularJS & The Word...
 
Introducing Assetic: Asset Management for PHP 5.3
Introducing Assetic: Asset Management for PHP 5.3Introducing Assetic: Asset Management for PHP 5.3
Introducing Assetic: Asset Management for PHP 5.3
 
What happens in laravel 4 bootstraping
What happens in laravel 4 bootstrapingWhat happens in laravel 4 bootstraping
What happens in laravel 4 bootstraping
 
Assetic (Symfony Live Paris)
Assetic (Symfony Live Paris)Assetic (Symfony Live Paris)
Assetic (Symfony Live Paris)
 
Head First Zend Framework - Part 1 Project & Application
Head First Zend Framework - Part 1 Project & ApplicationHead First Zend Framework - Part 1 Project & Application
Head First Zend Framework - Part 1 Project & Application
 

Similar a Presentation

Primefaces Nextgen Lju
Primefaces Nextgen LjuPrimefaces Nextgen Lju
Primefaces Nextgen Lju
Skills Matter
 
E2 appspresso hands on lab
E2 appspresso hands on labE2 appspresso hands on lab
E2 appspresso hands on lab
NAVER D2
 
E3 appspresso hands on lab
E3 appspresso hands on labE3 appspresso hands on lab
E3 appspresso hands on lab
NAVER D2
 
ASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin LauASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin Lau
Spiffy
 

Similar a Presentation (20)

Html5 For Jjugccc2009fall
Html5 For Jjugccc2009fallHtml5 For Jjugccc2009fall
Html5 For Jjugccc2009fall
 
JavaServer Pages
JavaServer PagesJavaServer Pages
JavaServer Pages
 
JSP
JSPJSP
JSP
 
Wt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technologyWt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technology
 
Wt unit 2 ppts client side technology
Wt unit 2 ppts client side technologyWt unit 2 ppts client side technology
Wt unit 2 ppts client side technology
 
Jsp sasidhar
Jsp sasidharJsp sasidhar
Jsp sasidhar
 
Java script
Java scriptJava script
Java script
 
Rich Portlet Development in uPortal
Rich Portlet Development in uPortalRich Portlet Development in uPortal
Rich Portlet Development in uPortal
 
Primefaces Nextgen Lju
Primefaces Nextgen LjuPrimefaces Nextgen Lju
Primefaces Nextgen Lju
 
Primefaces Nextgen Lju
Primefaces Nextgen LjuPrimefaces Nextgen Lju
Primefaces Nextgen Lju
 
Jsp Notes
Jsp NotesJsp Notes
Jsp Notes
 
前端概述
前端概述前端概述
前端概述
 
Advance java
Advance javaAdvance java
Advance java
 
JavaServer Pages
JavaServer Pages JavaServer Pages
JavaServer Pages
 
Jsp intro
Jsp introJsp intro
Jsp intro
 
Velocity EU 2014 — Offline-first web apps
Velocity EU 2014 — Offline-first web appsVelocity EU 2014 — Offline-first web apps
Velocity EU 2014 — Offline-first web apps
 
servlets
servletsservlets
servlets
 
E2 appspresso hands on lab
E2 appspresso hands on labE2 appspresso hands on lab
E2 appspresso hands on lab
 
E3 appspresso hands on lab
E3 appspresso hands on labE3 appspresso hands on lab
E3 appspresso hands on lab
 
ASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin LauASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin Lau
 

Más de Manav Prasad (20)

Experience with mulesoft
Experience with mulesoftExperience with mulesoft
Experience with mulesoft
 
Mulesoftconnectors
MulesoftconnectorsMulesoftconnectors
Mulesoftconnectors
 
Mule and web services
Mule and web servicesMule and web services
Mule and web services
 
Mulesoft cloudhub
Mulesoft cloudhubMulesoft cloudhub
Mulesoft cloudhub
 
Perl tutorial
Perl tutorialPerl tutorial
Perl tutorial
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
Jpa
JpaJpa
Jpa
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
 
Json
Json Json
Json
 
The spring framework
The spring frameworkThe spring framework
The spring framework
 
Rest introduction
Rest introductionRest introduction
Rest introduction
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
 
Junit
JunitJunit
Junit
 
Xml parsers
Xml parsersXml parsers
Xml parsers
 
Xpath
XpathXpath
Xpath
 
Xslt
XsltXslt
Xslt
 
Xhtml
XhtmlXhtml
Xhtml
 
Css
CssCss
Css
 
Introduction to html5
Introduction to html5Introduction to html5
Introduction to html5
 
Ajax
AjaxAjax
Ajax
 

Último

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 

Presentation

  • 2. Overview of History CGI (in C) Template (ASP, PHP) Servlet CGI (java, C++) JSP Speed, Security complexity
  • 3. HelloWorld import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); out.println("<title>Hello CS764!</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Hello CS764!</h1>"); out.println("</body>"); out.println("</html>"); out.close(); } }
  • 4. <html><head></head> <body> <a href="../servlet/HelloWorld"> <h1>Execute HelloWorld Servlet</h1> </a> </body> </html> <html> <head> <title>Hello CS764!</title></head> <body> <h1>Hello CS764!</h1> </body> </html>
  • 5. Client - Server - DB Client (browser) Web server (Apache, JWS) Database server (DB2) Through internet Return html file (Response) Trigger Servlet, JSP (Request) JDBC, intranet Request data Return data
  • 6. Life Cycle of Servlet init(ServletConfig); service(ServletRequest, ServletResponse); destroy(); servlet GenericServlet HttpServlet doGet(HttpServletRequest, HttpServletResponse); doPost(HttpServletRequest, HttpServletResponse); …….
  • 7. Interaction with Client • HttpServletRequest – String getParameter(String) – Enumeration getParameters(String[]) • HttpServletResponse – Writer getWriter() – ServletOutputStream getOutputStream() • Handling GET and POST Requests
  • 8. Assignment 2: Get Stock Price <html><head></head> <body> <form action="../servlet/Ass2Servlet" method=POST> <h2>Stock Symbol name: <input type=text name="stockSymbol"></h2><br> <input type="submit" value = "get price"> </form> </body></html> Client Side Ass2.html
  • 9. import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class Ass2Servlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse res) throws IOException, ServletException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); String stockSymb = request.getParameter("stockSymbol"); StockGrabber sg = new StockGrabber(); sg.setStockSymbol(stockSymb); // Set the stock symbol as “input” String stockPrice = sg.getPrice();// Get the price of stock System.out.println("After StockGrabber.getPrice --"+stockPrice);// Debug out.println("<html><head></head><body><br><br>"); out.println(stockSymb + " -- " + stockPrice); out.println("<hr>"); out.println("<form action="../servlet/Ass2Servlet" method=POST>"); out.println("<h3>Stock Symbol name: <input type=text name="stockSymbol"></h3>"); out.println("<input type=submit value="get price">"); out.println("</form>"); out.println("</body></html>"); } } Ass2Servlet
  • 10. Java Server Pages (JSP) Client’s Computer Server 1.Browser requests HTML 7. Server sends HTML back to browser servlet servlet class 5.The servlet runs and generates HTML Java Engine 6. Java Engine sends HTML to server 2. Server sends requests to Java Engine 3. If needed, the Java Engine reads the .jsp file 4. The JSP is turned into a servlet, compiled, and loaded Bean
  • 11. A First JSP <html> <head></head> <body> <p>Enter two numbers and click the ‘calculate’ button.</p> <form action=“calculator.jsp” method=“get”> <input type=text name=value1><br> <input type=text name=value2 ><br> <input type=submit name=calculate value=calculate> </form> </body> </html> Calculator.html
  • 12. <html> <head><title>A simple calculator: results</title></head> <body> <%-- A simpler example 1+1=2 --%> 1+1 = <%= 1+1 %> <%-- A simple calculator --%> <h2>The sum of your two numbers is:</h2> <%= Integer.parseInt(request.getParameter("value1")) + Integer.parseInt(request.getParameter("value2")) %> </body> </html> Calculator.jsp
  • 13. JSP Tags • Comments <%-- …...text…... --%> • Declaration <%! int i; %> <%! int numOfStudents(arg1,..) {} %> • Expression <%= 1+1 %> • Scriptlets <% … java code … %> • include file <%@ include file=“*.jsp” %> • …...
  • 14. Using Java Bean 1. <jsp:useBean id=“bean1” class=“Bean1”/> 2. <jsp:useBean id=“bean1” class=“Bean1” name=“serBean” type=“SerBean1”/> Declaration Getting property 1. <jsp:getProperty name=“bean1” property=“color”/> 2. <%=bean1.getColor() %> Setting property 1. <jsp:setProperty name=“bean1” property=“color” value=“red”/> 2. <jsp:setProperty name=“bean1” property=“color”/> 3. <jsp:setProperty name=“bean1” property=“color” param=“bgColor”/> 4. <jsp:setProperty name=“bean1” property=“*”/>
  • 15. Assg2 example <html> <head></head> <body> <center> <table border = 0> <form action=ass2.jsp method = POST> <tr><td><font color=blue>choose a stock market:</font></td> <td><select name="stockMarket"> <option value="Waterhouse">Waterhouse</option> <option value="Yahoo">Yahoo</option> <option value="ChicagoStockex">Chicago Stockex</option> <option value="Reuters">Reuters</option> </select></td> </tr> <tr><td><font color = blue>input a stock symbol:</font></td> <td><input type="edit" name="stockSymbol" size=15></td> </tr> <tr><td></td><td><input type="submit" value = "get price"></td></tr> </table> </form></center> </body></html> Client side Ass2.html
  • 16. Server side ass2.jsp <html><head> <jsp:useBean id="ass2" scope="session" class="ass2.StockGrabber" /> <jsp:setProperty name="ass2" property="*" /> </head> <body><h2><% ass2.processInput(); ass2.getPrice(); %> <center><table border=5> <tr><td># of data</td> <td>Stock Market</td> <td>Stock Symbol</td> <td>Stock Price </td> </tr><% String[] stockMarkets = ass2.getStockMarkets(); String[] symbols = ass2.getSymbols(); String[] prices = ass2.getPrices(); for(int i=0; i<prices.length; i++){ %> <tr><td> <%= i+1 %> </td> <td> <%= stockMarkets[i] %> </td> <td> <%= symbols[i] %> </td> <td><font color=red><%= prices[i] %></font></td> </tr><% } %> </table> </center> </h2> <hr><%@include file="ass2.html" %></html> <jsp:setProperty name=“ass2” property=“stockSymbol”/> <jsp:setProperty name=“ass2” property=“stockMarket”/>
  • 17.
  • 18. Without using JDBC Public class StockGrabber { ... public void processInput(){ if(stockMarket.compareTo("Waterhouse")==0){ setPrePriceString("<!--Last-->"); setPostPriceString("</FONT>"); setUrlPrefix("http://research.tdwaterhouse.com/ waterhouse/quote.asp?ticker="); } else if(stockMarket.compareTo("Yahoo")==0){ setPrePriceString("<td nowrap><b>"); setPostPriceString("</b></td>"); setUrlPrefix("http://finance.yahoo.com/q?s="); } ... else if(...){} ... else{...} } ... }
  • 19. Using JDBC --> Database import java.sql.*; Public class StockGrabber { ... public void processInput(){ try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String sourceURL="jdbc:odbc:stockInfo"; Connection databaseConnection=DriverManager.getConnection(sourceURL); Statement statement=databaseConnection.createStatement(); ResultSet info =statement.executeQuery( "select tPrePriceStr, tPostPriceStr, tUrlPrefix from stockMarketData where tStockMarket = stockMarket”); while(inf.next()) { prePriceString = info.getString(”tPrePriceStr"); postPriceString = info.getString(“tPostPriceStr”); urlPrefix = info.getString(“tUrlPrefix”); } } catch(SQLException e){ ... } ... } }