What Is Java Server Pages Java Server Pages

  • Slides: 56
Download presentation
What Is Java. Server Pages? • Java. Server Pages is a technology for developing

What Is Java. Server Pages? • Java. Server Pages is a technology for developing web pages that include dynamic content. • HTML page contains static content that always remains the same • A JSP page can change its content based on any number of variable items, including the identity of the user, the user's browser type, information provided by the user, and selections made by the user. • JSP can be used to create web applications like shopping carts and employee directories. • A JSP page contains standard markup language elements, such as HTML tags, just like a regular web page. • JSP page also contains special JSP elements that allow the server to insert dynamic content in the page

 • JSP elements can be used for a wide variety of purposes, such

• JSP elements can be used for a wide variety of purposes, such as retrieving information from a database or registering user preferences. • When a user asks for a JSP page, the server executes the JSP elements, merges the results with the static parts of the page, and sends the dynamically composed page back to the browser • JSP defines a number of standard elements useful for any web application, such as accessing Java. Beans components, passing control between pages, and sharing information between requests, pages, and users.

 • Programmers can also extend the JSP syntax by implementing application-specific elements that

• Programmers can also extend the JSP syntax by implementing application-specific elements that perform tasks such as accessing databases and Enterprise Java. Beans, sending email, and generating HTML to present application-specific data. • The combination of standard elements and custom elements allows for the creation of powerful web applications.

Dynamic Content With JSP

Dynamic Content With JSP

What is JSP Good For? • Servlets allow us to easily: – read data

What is JSP Good For? • Servlets allow us to easily: – read data from user – read HTTP request – create cookies – etc. • It is not convenient to write long static HTML using Servlets – out. println("<h 1>Bla Bla</h 1>" + "bla bla bla " + " lots more here. . . ") 5

JSP Idea • Use HTML for most of the page • Write Java code

JSP Idea • Use HTML for most of the page • Write Java code directly in the HTML page (similar to Javascript) • Automatically translate JSP to Servlet that actually runs 6

Benefits of JSP over Servlets • It is easier to write and maintain HTML.

Benefits of JSP over Servlets • It is easier to write and maintain HTML. • We can use standard website development tools. • JSP’s are translated into servlets. • Separation of Business Logic from Page Presentation

Relationships • In servlets: HTML code is printed from java code • In JSP

Relationships • In servlets: HTML code is printed from java code • In JSP pages: Java code is embedded in HTML code Java HTML 8 HTML Java

JSP Life Cycle .

JSP Life Cycle .

2021 -05 -20 10

2021 -05 -20 10

Embedding Elements in HTML Pages <html> <body bgcolor="white"> <% java. util. Date clock =

Embedding Elements in HTML Pages <html> <body bgcolor="white"> <% java. util. Date clock = new java. util. Date( ); %> <% if (clock. get. Hours( ) < 12) { %> <h 1>Good morning!</h 1> <% } else if (clock. get. Hours( ) < 18) { %> <h 1>Good day!</h 1> <% } else { %> <h 1>Good evening!</h 1> <% } %> Welcome to our site, open 24 hours a day. </body> </html> For example, if the current time is 8: 53 P. M. , the resulting page sent from the server to the browser looks like this: <html> <body bgcolor="white"> <h 1>Good evening!</h 1> Welcome to our site, open 24 hours a day. </body> </html>

Integration with Enterprise Java APIs Java. Server Pages is built on top of the

Integration with Enterprise Java APIs Java. Server Pages is built on top of the Java Servlets API, JSP has access to all of the powerful Enterprise Java APIs, including: • JDBC • Remote Method Invocation (RMI) and OMG CORBA support • JNDI ( Java Naming and Directory Interface) • Enterprise Java. Beans (EJB) • JMS ( Java Message Service) • JTA ( Java Transaction API) • This means that you can easily integrate Java. Server Pages with your existing Java Enterprise solutions

The JSP Advantage • JSP supports both scripting and element-based dynamic content, and allows

The JSP Advantage • JSP supports both scripting and element-based dynamic content, and allows programmers to develop custom tag libraries to satisfy application-specific needs. • JSP pages are precompiled for efficient server processing. • JSP pages can be used in combination with servlets that handle the business logic, the model supported by Java servlet template engines.

JSP Page contents: Everything in JSP page can be broken into 2 categories: ->

JSP Page contents: Everything in JSP page can be broken into 2 categories: -> Elements or tags that are processed on the server. -> Everything other than elements that the JSP engine ignores(Template data).

2021 -05 -20 15

2021 -05 -20 15

 • JSP is a Java based language and can utilize the potential of

• JSP is a Java based language and can utilize the potential of Java language • JSP Uses Tags to render pages into HTML code • JSP Tags can be classified into 5 groups – – – Directives Declarations Expressions Scriptlets Standard Actions • JSP Tags start with <% and end with %> • JSP Comments start with <%-- and end with --%>

Directives • JSP directives serve as messages to the JSP container from JSP. •

Directives • JSP directives serve as messages to the JSP container from JSP. • They are used to set global values. General Syntax is: <% @ directive name attribute =“value” %>

Contd… Three types of directives: • Page directive • Include directive • Tag lib

Contd… Three types of directives: • Page directive • Include directive • Tag lib directive

Contd… • Page directive: It defines a number of important attributes that effect the

Contd… • Page directive: It defines a number of important attributes that effect the whole page. Syntax: <% @ page attribute %> Attributes: 1. Import <% @ page import = “java. sql. *” %> <%@ page import=“java. util. Collection”%> 2. 3. Content type (content. Type=“text/html; charset=ISO-8859 -1) Session <% @ page Session = “”true” %>

Directives Cont. . • These are parsed and translated by the compiler before the

Directives Cont. . • These are parsed and translated by the compiler before the compilation Syntax: <%@directive attribute=“value”. . . %> Directive can be: page: use to provide information about it by way of attributes language=“java” the only supported language as of now session=“true” session will be created (default=“true”) error. Page=“errorpage. jsp” Any exception is redirected to it content. Type=“text/html; charset=ISO-8859 -1” is. Error. Page=“false” true only for error page Example: <%@page language="java" import="java. sql. *, mypackage. myclass" session=”false”%>

JSP Syntax Page Directive • Defines attributes that apply to an entire page <%@

JSP Syntax Page Directive • Defines attributes that apply to an entire page <%@ page [ language=“java” ] [ extends=“package. class” ] [ import=“package. class” ] [ session=“true | false” ] [ buffer=“none | 8 kb | sizekb” ] [ auto. Flush=“true | false” ] [ is. Thread. Safe=“true | false” ] [ info=“text” ] [ error. Page=“relative. URL” ] [ content. Type=“mime. Type” ] [ is. Error. Page=“true | false” ] %> 2021 -05 -20 21

Directives Cont. . import attribute: A comma seperated list of classes/packages to import <%@

Directives Cont. . import attribute: A comma seperated list of classes/packages to import <%@ page import="java. util. *, java. io. *" %> <%@ page import="java. util. *, coreservlets. *" %> content. Type attribute: Sets the MIME-Type of the resulting document (default is text/html) <%@ page content. Type="text/plain" %> <%@ page content. Type="MIME-Type; charset=Character-Set" %> Note that instead of using the content. Type attribute, you can write <% response. set. Content. Type("text/plain"); %> include: used to include other html/jsp pages here <%@ include file=“abc. jsp” %> <%@ include file="relative url" %> taglib: Used to define new tags and prefixes <%@ taglib uri=“tlds/taglib. tld” prefix=“mytag” %>

URI for the JSTL Libraries JSTL consists of five different type of tag libraries

URI for the JSTL Libraries JSTL consists of five different type of tag libraries , which minimizes the name collisions among the actions in different categories --------------------------------------------------Library URI Prefix Core http: //java. sun. com. jsp/jstl/core c XML processing http: //java. sun. com. jsp/jstl/XML x 118 Nformating http: //java. sun. com. jsp/jstl/fmt Database accesses http: //java. sun. com. jsp/jstl/sql Functions http: //java. sun. com. jsp/jstl/functions fun

JSP Scripting Elements • Scripting elements let you insert code into the servlet that

JSP Scripting Elements • Scripting elements let you insert code into the servlet that will be generated from the JSP • Three forms: – Expressions of the form <%= expression %> that are evaluated and inserted into the output, – Scriptlets of the form <% code %> that are inserted into the servlet's _jsp. Service method, and – Declarations of the form <%! code %> that are inserted into the servlet class, outside of any methods

Declarations • Declarations are used to declare variables, methods etc. , which will be

Declarations • Declarations are used to declare variables, methods etc. , which will be used later in the page. • JSP Declaratives begins with <%! and ends with %> • Any amount of Java code can be embed in the JSP Declaratives. • Variables and functions defined in the declaratives are class level and can be used anywhere in the JSP page. • Syntax of JSP is as follows: <%! %> • Examples: //java codes – <%! int count = 0; %> – <%! double sqr(double x) { return x * x; } %> – <%! private int counter ; %>

Declarations Example: <%@page content. Type="text/html" language=“java”%> <html> <body> <%! int cnt=0; private int get.

Declarations Example: <%@page content. Type="text/html" language=“java”%> <html> <body> <%! int cnt=0; private int get. Cnt() { cnt++; return cnt; } %> Values of Cnt are: <%= get. Cnt()%> </body> </html>

Expressions • • Expressions in JSP are single instructions. Expressions begin with <%= and

Expressions • • Expressions in JSP are single instructions. Expressions begin with <%= and end with %> There is no semicolon after the expression Examples of expressions are as follows: <%= i++ %> <%= my. Method() %>

Expression Translation <H 1>A Random Number</H 1> <%= Math. random() %> public void _jsp.

Expression Translation <H 1>A Random Number</H 1> <%= Math. random() %> public void _jsp. Service(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { request. set. Content. Type("text/html"); Http. Session session = request. get. Session(true); Jsp. Writer out = response. get. Writer(); out. println("<H 1>A Random Number</H 1>"); out. println(Math. random()); . . . } 28

Predefined or implicit Variables are used in Expressions • The following predefined variables can

Predefined or implicit Variables are used in Expressions • The following predefined variables can be used: – request, the Http. Servlet. Request – Represents the client’s request as an object and is a subclass of Http. Servlet. Request. It is used to get client’s form data – response, the Http. Servlet. Response – Response is a subclass of Http. Servlet. Response and is used to send out the information from server to client (browser) 29

Cont. . – session, the Http. Session associated with the request – Represents a

Cont. . – session, the Http. Session associated with the request – Represents a storage space common to all pages of the client. Anything stored here is available as long as the session is alive – out, the Print. Writer (a buffered version of type Jsp. Writer) used to send output to the client Represents the write stream of the client and anything written here will be sent to the browser 30

Other Implicit variable • Page. Context – Page attributes are available throughout the object

Other Implicit variable • Page. Context – Page attributes are available throughout the object • exception – Exception details can be obtained through this object • application – Variables in this object are available throughout the application, which means all clients can access the same variable • config – Uses to get servlet configuration parameters • page – Represents this object 31

Request Object methods: • Some of the request object methods are as follows: –

Request Object methods: • Some of the request object methods are as follows: – <%=request. get. Method()%> – <%=request. get. Request. URI()%> – <%=request. get. Protocol()%> – <%=request. get. Path. Info()%> – <%=request. get. Path. Translated()%> – <%=request. get. Content. Length()%> – <%=request. get. Query. String()%> – <%=request. get. Content. Type()%> – <%=request. get. Server. Name()%> – <%=request. get. Server. Port()%> – <%=request. get. Remote. User()%> – <%=request. get. Remote. Addr()%> – <%=request. get. Remote. Host()%> – <%=request. get. Auth. Type()%>

<HTML> <HEAD> <TITLE>JSP Expressions</TITLE></HEAD> <BODY> <H 2>JSP Expressions</H 2> <UL> <LI>Current time: <%= new

<HTML> <HEAD> <TITLE>JSP Expressions</TITLE></HEAD> <BODY> <H 2>JSP Expressions</H 2> <UL> <LI>Current time: <%= new java. util. Date() %> <LI>Your hostname: <%= request. get. Remote. Host() %> <LI>Your session ID: <%= session. get. Id() %> <LI>The <CODE>test. Param</CODE> form parameter: <%= request. get. Parameter("test. Param") %> </UL> </BODY> </HTML> 33

Encoded Unencoded 34

Encoded Unencoded 34

Scriptlets • Scriptlets are small pieces of Java code that runs immediately. • Scriptlets

Scriptlets • Scriptlets are small pieces of Java code that runs immediately. • Scriptlets start with <% and end with %> • These are sections of Java code embedded in the page Unlike expressions, they do not return a value • But may write directly to the page • JSP scriptlets let you insert arbitrary code into the servlet method that will be built to generate the page ( _jsp. Service ) • The syntax of a scriptlet is as shown below: <% // Any amount of Java code here %>

Scriptlets • Java code, which is inserted into the servlet Example: <% //java codes

Scriptlets • Java code, which is inserted into the servlet Example: <% //java codes String user. Name=null; user. Name=request. get. Parameter("user. Name"); out. println( user. Name ) %> • Example: <% for( int i=0; i<poll. get. Answer. Count(); i++ ) %>

Scriptlet Translation <%= foo() %> <% bar(); %> public void _jsp. Service(Http. Servlet. Request

Scriptlet Translation <%= foo() %> <% bar(); %> public void _jsp. Service(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { request. set. Content. Type("text/html"); Http. Session session = request. get. Session(true); Jsp. Writer out = response. get. Writer(); out. println(foo()); bar(); . . . } 37

HTML Code in Scriptlets • Scriptlets don't have to be entire Java Staments: <%

HTML Code in Scriptlets • Scriptlets don't have to be entire Java Staments: <% if (Math. random() < 0. 5) { %> You <B>won</B> the game! <% } else { %> You <B>lost</B> the game! <% } %> if (Math. random() < 0. 5) { out. println("You <B>won</B> the game!"); } else { out. println("You <B>lost</B> the game!"); } 38

Example <%! int n = 0; %> Page accessed: <%= ++n %> times <%

Example <%! int n = 0; %> Page accessed: <%= ++n %> times <% if ( (n % 10) == 0 ) { n = 0; } %>

RESULT

RESULT

JSP Standard actions • Standard actions: JSP tags JSP action elements result in some

JSP Standard actions • Standard actions: JSP tags JSP action elements result in some sort of action occurring while the JSP page is being executed, such as instantiating a Java object and making it available to the page. general tag syntax for JSP standard actions: <jsp: tag attr 1="value 1" attr 2="value 2". . . attr. N="value. N">. . . body. . . </jsp: tag>

Standard Actions • JSP Standard actions are predefined into the JSP engine. • JSP

Standard Actions • JSP Standard actions are predefined into the JSP engine. • JSP Standard actions start with <jsp: action. Name and end with </jsp: action. Name> • Some of the extensively used actions are: (jsp: use. Bean, jsp: set. Property, jsp: get. Property – manipulate a Java. Bean) – <jsp: use. Bean> -- Creates an object of given type – <jsp: set. Property> -- Sets variable to a value from HTML – <jsp: get. Property> -- Gets a variable value into HTML – <jsp: include> -- Includes another page – <jsp: forward> -- Redirects the Page 42

Example : Predefined bean <%@ page language="java" content. Type="text/html" %> <html> <body bgcolor="white"> <jsp:

Example : Predefined bean <%@ page language="java" content. Type="text/html" %> <html> <body bgcolor="white"> <jsp: use. Bean id="clock" class="java. util. Date" /> The current time at the server is: <ul> <li>Date: <jsp: get. Property name="clock" property="date" /> <li>Month: <jsp: get. Property name="clock" property="month" /> <li>Year: <jsp: get. Property name="clock" property="year" /> <li>Hours: <jsp: get. Property name="clock" property="hours" /> <li>Minutes: <jsp: get. Property name="clock" property="minutes" /> </ul> </body> </html> 43

Using User Defined Classes Creating an object of type Abc <jsp: use. Bean id=“varname”

Using User Defined Classes Creating an object of type Abc <jsp: use. Bean id=“varname” class = “my. package. Abc” /> Getting value of the bean variables into HTML <b>The value of count in object is </b> <i> <jsp: get. Property name=“varname” property=“count” /> Setting Values of Bean: <jsp: set. Property name=“varname" property="*" /> <jsp: set. Property name=“varname" property=“count" param=“html_count" /> <jsp: set. Property name=“varname" property=“count" value=“ 100" /> 44

Standard Actions The jsp: include Action • This action lets you insert files into

Standard Actions The jsp: include Action • This action lets you insert files into the page being generated • The file inserted when page is requested • The syntax looks like this: <jsp: include page="relative URL" flush="true" /> <jsp: include page=“abc. jsp” /> 45

The jsp: forward Action • Forwards request to another page <jsp: forward page="relative URL"/>

The jsp: forward Action • Forwards request to another page <jsp: forward page="relative URL"/> <jsp: forward page=“abc. jsp"/> • Page could be a static value, or could be computed at request time • Examples: <jsp: forward page="/utils/error. Reporter. jsp" /> <jsp: forward page="<%= some. Java. Expression %>" /> 46

Create a web application using JSP to show welcome message to the user <html>

Create a web application using JSP to show welcome message to the user <html> <body bgcolor="wheat"> <form action=“wel. jsp"> <center> Name<input type="text" name="t 1"> <input type="submit" value="send"> </center> </form> </body> </html>

Wel. jsp <html> <body bgcolor="yellow"> <h 1>Hello <%=request. get. Parameter("t 1")%> Welcome to our

Wel. jsp <html> <body bgcolor="yellow"> <h 1>Hello <%=request. get. Parameter("t 1")%> Welcome to our website!</h 1> </body> </html>

Create a web application using JSP to show current date and time. Index. jsp

Create a web application using JSP to show current date and time. Index. jsp <%@page content. Type="text/html" page. Encoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W 3 C//DTD HTML 4. 01 Transitional//EN" "http: //www. w 3. org/TR/html 4/loose. dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> hello! the time is now <%=new java. util. Date()%> </body> </html> OUTPUT hello! the time is now Thu Apr 05 09: 11: 58 CEST 2012

JSP Example.

JSP Example.

Result

Result

Write a JSP which does the following job: Insert the details of the 3

Write a JSP which does the following job: Insert the details of the 3 or 4 users who register with the web site (week 9) by using registration form. Authenticate the user when he submits the login form using the user name and password from the database CREATING TABLE : register QUERY: create table register(name varchar 2(20), password varchar 2(20)); : insert into register values(‘user’, ’pass 1’); : insert into register values(‘user 2’, ’pass 2’); : select * from register;

VAL. Html <html> <head> <title>Login</title> </head> <body> <center> <form name="a" action="http: //localhost: 9090/week 10/val.

VAL. Html <html> <head> <title>Login</title> </head> <body> <center> <form name="a" action="http: //localhost: 9090/week 10/val. jsp"> <table> <tr> <td>User. Name: </td><input type="text" name="uname"/></td></tr><tr> <td>Password: </td><input type="password" name="pass"/></td></tr><tr> <td><input type="submit" value="Login"></td> </tr> </table> </center> </form> </body> </html>

ERROR. HTM: <html> <head><title>Login</title></head> <body><form name="a" action="http: //localhost: 9090/week 10/val. jsp"> <center><p style="color: red">Enter

ERROR. HTM: <html> <head><title>Login</title></head> <body><form name="a" action="http: //localhost: 9090/week 10/val. jsp"> <center><p style="color: red">Enter password or username are incorrect</p> <table> <tr> <td>User. Name: </td><input type="text" name="uname"/></td></tr><tr> <td>Password: </td><input type="password" name="pass"/></td></tr><tr> <td><input type="submit" value="Login"></td></tr> <table> </center> </form> </body> </html>

Val. jsp <%@page import="java. sql. *, java. io. *"%> <%! Connection con; Statement st;

Val. jsp <%@page import="java. sql. *, java. io. *"%> <%! Connection con; Statement st; Result. Setrs; boolean flag=false; %> <% Driver. Manager. register. Driver(new oracle. jdbc. driver. Oracle. Driver()); try { con=Driver. Manager. get. Connection("jdbc: oracle: thin: @localhost: 1521: db", "scott", "tiger”); System. out. println(con); st=con. create. Statement(); rs=st. execute. Query("select * from register"); String name=request. get. Parameter("uname"); String pass=request. get. Parameter("pass"); System. out. println("outside"); while(rs. next()) { System. out. println(1); if(name. equals(rs. get. String(1))) { if(pass. equals(rs. get. String(2))) { flag=true; break; } } }

if(flag) { %> } else {%> } <%=name+“Welcome to J. N. T. University "%>

if(flag) { %> } else {%> } <%=name+“Welcome to J. N. T. University "%> <% flag=false; <%="Enter Username or password are invalid please try again"%> <% response. send. Redirect("error. html"); } catch(Exception e) { } %>