JSP Presented by : Fayez Salma Supervised by : Dr. Zouhir Dahrouj.

Post on 03-Jan-2016

219 views 1 download

Transcript of JSP Presented by : Fayez Salma Supervised by : Dr. Zouhir Dahrouj.

JSPPresented by : Fayez Salma

Supervised by : Dr. Zouhir Dahrouj

OUTLINES

Web Applications CGI JSP Servlet JSP structure Java Beans JSP vs. PHP Conclusion

WEB APPLICATION

Application that is accessed via web browser over a network such as Internet or an Intranet.

It is also a computer software application that is coded in a language (such as HTML, Jsvascript, JSP, PHP…)

Common web applications include webmail, online retail sales, online auctions, and many other functions.

STATIC PAGES

DYNAMIC PAGES

WHY WEB APPLICATIONS?

Desktop Applications desktop application means any software that

can be installed on a single computer (laptop or a desktop) and used to perform specific tasks. Some desktop applications can also be used by multiple users in a networked environment.

Maintenanceweb based applications need to be installed only once where as desktop applications are to be installed separately on each computer. Also updating the applications is cumbersome with desktop applications as it needs to be done on every single computer which is not the case with web applications.

Ease of use desktop applications are confined to a physical location and hence have usability constraint. Web applications development on the other hand makes it convenient for the users to access the application from any location using the Internet.

Security web applications are exposed to more security risks than desktop applications. You can have a total control over the standalone applications and protect it from various vulnerabilities. This may not be the case with web applications as they are open to a large number of users in the Internet community thus widening the threat.

Connectivity web application development relies significantly on Internet connectivity and speed. Absence of Internet or its poor connectivity can cause performance issues with web applications. Desktop applications are standalone in nature and hence do not face any hindrances resulting from Internet connectivity. Connectivity also significantly affects the speed at which desktop and web applications operate.

Cost factorweb application development and its maintenance involve higher costs and mostly recurring in nature. Desktop applications are purchased one time and there are not continually occurring charges. However, in certain cases, maintenance fees may be charged.

WHAT IS THE BEST?

Having considered the basics of desktop and web application development, the selection of a suitable type will depend on the business needs and factors discussed in the comparison given above.

UNDERSTANDING HTTP The Basics of HTTP HTTP is a generic, lightweight protocol that

is used for the delivery of HTML and XML. HTTP is the primary protocol used to deliver information across the World Wide Web.

HTTP is also a stateless protocol that keeps

no association between requests. This means that when the client makes a request to a server, the server sends a response, and the transaction is closed. A second request from the same client is a whole new transaction, unrelated to the first request.

THE HTTP REQUEST

GET /simpleDate.jsp HTTP/1.1accept: image/gif, image/jpeg, image/png, */*accept-charset: iso-8859-1,*,utf-8host: www.javadesktop.comaccept-language: enuser-agent: Mozilla/5.0

THE HTTP RESPONSEHTTP/1.1 200 OKDate: Sun, 08 Dec 1999 18:16:31 GMTServer: Apache/1.3.9 (Unix) ApacheJServ/1.0Last-Modified: Tue, 22 Jun 1999 05:12:38 GMTETag: "d828b-371-376f1b46"Accept-Ranges: bytesConnection: closeContent-Type: text/html<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Final//EN">

<HTML><HEAD>

<TITLE>A simple date example</TITLE>

</HEAD><BODY COLOR="#ffffff">

The time on the server isWed Dec 08 16:17:57 PST 1999

</BODY></HTML>

CGI COMMON GATEWAY INTERFACE

CGI allows requests to be sent to an external program. These external programs could be written in just about any programming language—most commonly C, C++, Perl, and Python.

For each request sent to a CGI program, the Web server loads, runs, and unloads the entire CGI

CGI

CGI PROBLEMS

Efficiency each request to a CGI resource creates a new

process on the server and passes information to the process

Security Popularity Ease of Use

SERVLET

Servlets are modules of Java code that run in a server application to answer client requests

They are most commonly used with HTTP. They follow Java Standards and provide a

meansto create sophisticated server extensions in aserver and operating system independent way.

Packages: javax.servlet (the basic Servlet framework)

javax.servlet.http (extensions of the Servlet framework for Servlets that answer HTTP requests).

SERVLETS MAIN USE

Processing and/or storing data submitted by an HTML form.

Providing dynamic content, e.g. returning the results of a database query to the client.

Managing state information on top of the stateless HTTP, e.g. for an online shopping cart system which manages shopping carts for many concurrent customers and maps every request to the right customer.

SERVLETS Example: public class OrderServlet extends HttpServlet {

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

IOException {response.setContentType("text/html");PrintWriter out = response.getWriter( );if (isOrderInfoValid(request)) {

saveOrderInfo(request);out.println("<html>");out.println(" <head>");out.println(" <title>Order

Confirmation</title>");out.println(" </head>");out.println(" <body>");out.println(" <h1>Order Confirmation</h1>");renderOrderInfo(request);out.println(" </body>");out.println("</html>");

}

THE PROBLEM WITH SERVLETS Detailed Java programming knowledge is

needed to develop and maintain all aspects of the application, since the processing code and the HTML elements are lumped together.

Changing the look and feel of the application requires the servlet code to be updated an recompiled.

It's hard to take advantage of web page development tools when designing the application interface. If such tools are used to develop the web page layout, the generated HTML must then be manually embedded into the servlet code, a process that is time-consuming, error-prone, and extremely boring.

WHAT IS JSP?

Mostly HTML page, with extension .jsp Include JSP tags to enable dynamic content

creation Translation: JSP → Servlet class Compiled at Request time

(first request, a little slow) Execution: Request → JSP Servlet's service

method

TYPE OF SCRIPTING ELEMENTS

A text file with snippets of Java code: Expressions <%= %> Statements <% %> Declarations <%! %>

JSP EXPRESSIONS

Java expression whose output is spliced into HTML <%= userInfo.getUserName() %>

<%= 1 + 1 %><%= new java.util.Date() %>

Translated to out.println(userInfo.getUserName()) ...

%<CODE>%

Scriptlet: Add a whole block of code to JSP... passed through to JSP's service method

<% String queryData=query.getQueryString();out.println(“Attached GET data :”+queryData);%>

!%<DECL>

<%! private int tempvar=5; %> <%! private void calSum(…){…} %>

IMPLICITLY DECLARED VARIABLES:

• HttpServletRequest request;• HttpServletResponse response;• HttpSession session;• ServletContext application;• JspWriter out;

IMPLICITLY DECLARED VARIABLES:

The out ObjectThe major function of JSP is to describe data

being sent to an output stream in response to a client request. This is output stream is exposed to the JSP author through the implicit out object.

<% out.println(“Hello World”); %>

IMPLICITLY DECLARED VARIABLES:

The request Object Through the request object the JSP page is

able to react to input received from the client. Request parameters are stored in special name/value pairs that can be retrieved using the request.getParameter(name) method.

<% request.getParameter(“username”); %>

IMPLICITLY DECLARED VARIABLES:

The response ObjectThe response object deals with the stream of

data back to the client. The out object is very closely is related to the response object.

IMPLICITLY DECLARED VARIABLES:

The session object

The session object is used to track information about a particular client while using stateless connection protocols, such as HTTP. Sessions can be used to store arbitrary information between client requests.

A HttpSession object keeps state during a session HttpSession provides a rich API

public void setAttribute( String name, Object value ) public Object getAttribute( String name ) public Object removeAttribute( String name ) public String getId() public long getCreationTime() ...

Session Examples In JSP<%@ page session="true" %> <% ... String user = "Kai"; session.setAttribute( "user", user );%>

In Servlet

...HttpSession session = request.getSession( true );String user = (String) session.getAttribute("user");

JSP DIRECTIVES

Format:<%@ directivename attribute=”value”

attribute=”value” %>

There are three main directives that can be used in JSP:• The page directive• The include directive• The taglib directive

THE PAGE DIRECTIVE

Attributes : Import, errorPage, isErrorPage, isThreadSafe, language, session, buffer, info …

<%@ page import=”java.util.*” %>

THE INCLUDE DIRECTIVE

<@% include file=”filename” %>

THE TAGLIB DIRECTIVE

<@% taglib uri=”taglibURI” prefix=”tagprefix” %>

JAVA BEANS

What Are Beans?Classes that follows certain conventions: Must have zero argument Should have no public instance variables Persistent values should be accessed through

methods called getXxx and setXxx Boolean properties use isXxx instead of

getXxx If class has method getTitle that return a

String, class is said to have a string property named title.

JAVA BEANS

Format - <jsp:useBean id=“name”

class=“Package.Class” />

Example:<jsp:useBean id=“book1”

class=“cwp.Book” />Can be thought of as equivalent to the

scriptlet<% cwp.Book book1=new cwp.Book(); %>

ACCESSING BEAN PROPERTIES

Format - <jsp:getProperty name=“name”

property=“property” />

Example:<jsp:getProperty name=“book1”

property=“title” />It equivalent to the following JSP expression<%= book1.getTitle() %>

SETTING BEANS PROPERTIES

Format - <jsp:serProperty name=“name”

property=“property” value=“value” />

Example <jsp:setProperty name=“book1” property

=“tilte” value=“Core Servlets and JSP”

SHARING DATA

within page - <jsp:useBean ….. scope=“page” />

Objects placed in the default scope, the page scope, are available only within that page

SHARING DATA

request scope <jsp:useBean … scope=“request” />

The request scope is for objects that need to be available to all pages processing the same request.

SHARING DATA

session scope <jsp:useBean … scope=“session” />

Objects in the session scope are available to all requests made from the same session

SHARING DATA

application scope <jsp:useBean … scope=“application” />

Objects in the application scope are shared by all users of the application

PHP

Open-source technology Providing server-side scripting very similar to

ASP/JSP Source code and distribution freely available Large community of developers Implementations for– All major UNIX, Linux and Windows operatingsystems– Accessing different databases especially MySQL

JSP VS. PHP

PHP has C-like syntax with some feature borrowed from Perl, C++ and Java

JSP: Java

Platform PHP: Unix (Linux), Windows, MacOS. JSP: UNIX, Microsoft Windows, Mac OS, Linux

JSP VS. PHP

File Extension

PHP

FILENAME.php

JSP

FILENAME.jsp

JSP VS. PHP

Database

PHP: MySQL, mSQL, Oracle, Informix, Sybase, etc.

JSP: any ODBC- and JDBC-compliant database

JSP VS. PHP

PHP:

<?php ?> <? ?>

JSP:

<%= %> <% %> <%! %>

JSP VS. PHP

Variables Definition

PHP:

No type $varaible_name vlaue;

JSP:

Like JAVAType Varname initial value ;

JSP VS. PHP

Include File

PHP:

include(“file_name”)include_once (“file_name”)require (“file_name”)reuire_once (“file_name”)

JSP

<@% include file=”filename” %>

JSP VS. PHP

Get/Post Variable

PHP

$_POST[“varaible_name”]$_REQUEST[“variable_name”]

JSP

The request Object

JSP VS. PHP

Sessions

PHP

start_session() $_SESSION[“variable_name”]

JSP

The Session Object

JSP VS. PHP Connect to Database

PHP:function connect(){

if(!$dbconnect=mysql_connect('localhost',USER_NAME,PASSWORD))

{

echo "Connection faild to the host";

exit;

}

else

{

if (!mysql_select_db(DATABASE NAME))

{

echo "Cannot Connect ot DataBase";

}

else

{

return $dbconnect;

}

}

}

JSP VS. PHP Connect to Database

JSP public long connect() {

try { String driver = "sun.jdbc.odbc.JdbcOdbcDriver"; Class.forName(driver); String conStr = "jdbc:odbc:new"; con = DriverManager.getConnection(conStr,

sDBUserName, sDBPass); con.setAutoCommit(false); } catch (Exception e) {} return 1; //Errors.SUCCESS; }

JSP VS. PHP

Object Oriented language

PHP

Yes. Contains classes, function, inheritance, Interfaces, Visibility features, ….

JSP

JAVA

PHPJSP

Language In PagePHPJAVA

OS PlatformUnix (Linux), Windows, MacOS, OS/2

UNIX, Microsoft Windows, Mac OS, Linux

Supported Database

MySQL, mSQL, ODBC, Oracle, Informix, Sybase, etc.

any ODBC- and JDBC-compliant database

ScalabilityFairGood

Learning curveHigh (C, Perl)High (Java)

PortabilityDB portabilityGood

Programming Approach

Scripting with object oriented support

Completely object oriented

String and data manipulation

Rich functionality. Functional and easy coding

Rich library, too much descriptive and object oriented code

Web Oriented featuresIncludes Mails File Uploads Form Handling Sessions

Inbuilt functionality. Easy to use functions, written for the specific tasks

Almost everything is built in or supported by libraries. Complicated and too much of code.

XML/XSL/XPATHSAX and DOM parsers available are easy to use and to the point. Another library, Simple XML provides very easy OO approach to handling XML data. XSL and XPATH functionality is also built in.

Use standard SAX/DOM parsers. Too much boiler plate code involved. Well defined APIs and stable implementations are available for XSL and XPATH

CONCLUSION

?

Thanks