Java Servlets Java Server Pages (JSP)

Post on 05-Jan-2016

98 views 5 download

description

Java Servlets Java Server Pages (JSP). Need for Servlets Servlets are required to: Reduce the overhead on the server and network To take care of processing data on the Web server Servlets are: Java programs that can be deployed on a Java enabled Web server - PowerPoint PPT Presentation

Transcript of Java Servlets Java Server Pages (JSP)

Java ServletsJava Server Pages

(JSP)

Need for Servlets

Servlets are required to:

Reduce the overhead on the server and network

To take care of processing data on the Web server

Servlets are:

Java programs that can be deployed on a Java enabled Web server

Used to extend the functionality of a Web server

Used to add dynamic content to Web pages

Characteristics of Servlets

Servlets are:

Efficient

Initialization code for a servlet is executed only once

Robust

Provide all powerful features of Java

Portable across Web servers

Persistent

Increase the performance of a system by preventing frequent disk access

Comparison between Servlets and Applets

Applets:

Are embedded in Web pages

Require the browser to be Java-enabled

Take a lot of time to be downloaded

Servlets:

Execute on the Web server, thus help overcome problems with download time

Do not require the browser to be Java-enabled

Comparison between Servlets and other Server-

Side Scripting Technologies

Common Gateway Interface (CGI) scripts, JSP, and ASP are alternatives to servlets

CGI Scripts:

Are programs written in C, C++, or Perl

Get executed in a server

Run in separate processes for each client access

Require the interpreter to be loaded on the server

A JSP file is automatically converted to a servlet before it is executed

Comparison between Servlets and other Server- Side Scripting Technologies (Contd.)

Active Server Pages (ASP):

Is a server-side scripting language developed by Microsoft

Enables a developer to combine HTML and a scripting language in the same Web page

Are not compatible with all Web servers

Overview of History

CGI(in C)

Template(ASP, PHP)

Servlet

CGI(java, C++)

JSP

Speed, Securitycomplexity

Working of Servlets

Client browser passes requests to a servlet using the

following methods:

GET

Uses a query string to send additional information to the server

Query string is displayed in the client browser

POST

Sends the data as packets to the server through a separate socket connection

Complete transaction is invisible to the client

Slower compared to the GET method

The javax.servlet Package• Hierarchy of classes that are used to create a

servletClass java.lang.Object

Class javax.servlet.GenericServlet

Class javax.servlet.HttpServlet

Interface javax.servlet.Servlet

Interface javax.servlet.ServletConfig

Interfacejavax.io.Serializable

The javax.servlet Package (Contd.)• A brief description of the classes and

interfaces are as follows:

Class/Interface Name Description

HTTPServlet class Provides a HTTP specific implementation of the Servlet interface.

HTTPServletRequest interface

Provides methods to process requests from the clients.

Class/Interface Name

Description

HTTPServlet Response interface

Response to the client is sent in the form of a HTML page through an object of the HTTPServletResponse class.

ServletConfig class

Used to store the servlets startup configuration values and the initialization parameters.

Life Cycle of a Servlet• Life cycle of a servlet is depicted below:

Client (Browser)

init()

service()

destroy()

Request

Response

Life Cycle of a Servlet (Contd.)• The following table describes few methods

that are used in creating a servlet:

Method name Functionality

Servlet.init (ServletConfig config) throws ServletException

Contains all initialization code for the servlet.

Servlet. service()

Receives all requests from clients, identifies the type of the request, and dispatches them to the doGet() or doPost() methods for processing.

Life Cycle of a Servlet (Contd.)

Method name Functionality

Servlet. destroy()

Executes only once when the servlet is removed from server.

HTTPServlet Response. getWriter()

Returns a reference to a PrintWriter object.

HTTPServlet Response. setContentType (String type)

Sets the type of content that is to be sent as response to the client browser.

Deploying a Servlet• A servlet can be deployed in:

– Java Web Server (JWS)– JRun– Apache– Java 2 Enterprise Edition (J2EE) server

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 : 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

Session Tracking

Session:

• Is a group of activities that are performed by a user while accessing a particular Web site

Session Tracking:

• Is the process of keeping track of settings across sessions

Techniques to Keep Track of Sessions in ServletsHttp:•Cannot be used to maintain data across two sessions• Is a stateless protocol

The following techniques can be used to track sessions data in servlets:• URL rewriting • Hidden form fields• Cookies• Using the HTTPSession interface

URL Rewriting • Is a technique by which the URL is

modified to include the session ID of a particular user and is sent back to the client – The session ID is used by the client for

subsequent transactions with the server

Hidden Form Fields• Is a technique that can be used to keep track

of users– The values that are trapped in the hidden fields

are sent to the server when the user submits the form

Using the HttpSession Interface HttpSession Interface:• Is a part of the Servlet API that is used to

keep track of sessions– A user who logs on to a Web site is

automatically associated with a session object– The session object can be used to store any type

of data for keeping track of sessions

Cookies• Are small text files that are used by a Web server to keep track of

users• Has values in the form of key-value pairs• Are created by the server and sent to the client with the HTTP

response headers• Are saved in the client’s local hard disks and sent along with the

HTTP requests headers to the server• Are supported by the Servlet API through javax.servlet.http.Cookie class

Need for JSP

Caters to the need for server-side scripting

Facilitates segregation of work profiles of a Web designer and a Web developer

The Web designer designs the layout for the Web page by using HTML

The Web developer writes the code for business logic by using Java and other JSP-specific tags

Generates a servlet on compilation, hence incorporates all servlet functionalities

Differences between servlets and JSP

Servlets:

Consist of an HTML file for static content and a Java file for dynamic content

Require recompilation if changes are made to any of the files

Involve extensive code writing

JSP:

Contains Java code embedded directly into an HTML page by using special tags

Automatically incorporates changes made to any files

Facilitates independent working of Web developers and Web designers

Java Server Pages (JSP)

Client’s Computer

Server

1.Browser requests HTML

7. Server sends HTML back to browser

servletservlet

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

The JSP request-response cycle

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 property1. <jsp:getProperty name=“bean1” property=“color”/>2. <%=bean1.getColor() %>

Setting property1. <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 sideAss2.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 JDBCPublic 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 --> Databaseimport 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){ ... }...

}}

A JSP page consists of HTML and JSP tags. The JSP tags include comments, directives, declarations, scriplets, expressions, and actions

JSP directives are used to specify general information about a particular page

JSP declarations are used to define variables and methods in a page

JSP scriplets consist of valid code snippets placed within the <% and the %> tags

JSP expressions are used to directly insert values into the output

JSP actions such as useBean, getProperty, setProperty, and forward are used to perform tasks such as insertion of files, reusing beans, forwarding a user to another page, and instantiating objects

JSP implicit objects such as request, response, out, and session are pre-defined variables that can be added to expressions and scriplets You use the java utility to execute a Java program