Jsp

  • Uploaded by: Adarsh
  • 0
  • 0
  • May 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Jsp as PDF for free.

More details

  • Words: 4,380
  • Pages: 25
1

JSP [JAVA SERVER PAGES] Introduction • • • The are a number of ways to get data from one computer to another the first was called UNIX-to-UNIX copy • • The next development was the File Transfer Protocol • • Then came HTTP which abstracts content away from files on a disk to arbitrary URLs that can be any type of resource • • After HTTP it came HTML that can specify how data should look through a wide variety of tags, images, links and tables • • The client server technology which is based on request response mechanism made a big change in file transfer technologies • • Today a web server can do a lot things besides sending a file in response to a request like running a program and sending the output of that program to the user • • The world wide web came up with static pages similar to pages in a file which had no interaction with the user • • Then came up dynamic pages which has dynamic content that immediately reacts to the user’s need • • The server generates dynamic content with the help of programs that resides inside the server called common gateway interface (CGI) A sample CGI program in C #include <stdio.h> #include int main(int argc, char **argv) { time_t now;

2 printf(“\n”); printf(“\n”); time(&now); printf(“The time is now: %s”, ctime(&now)); printf(“\n”); printf(“\n”); exit(0); }; Introduction (contd.) request Client

CGI Server

response • Application servers was introduced to improve the performance of the server • The application server runs as a separate process and stays running between requests • Application servers are extensible allowing programmers to add new features as needed

3

Diagram of an Application Server

CGI 1

2 Server

Client

CGI

4

CGI

CGI

3 Application Server

1- Browser requests HTML 2- Web server sends request to application server 3 – Application generates HTML 4- Server sends HTML back to browser

Servlets • A servlet is a small piece of code that extends a server’s functionality • • A servlet is an object written in Java that is equipped to receive a request and build and send back a response • • Written in java a servlet inherits all of the language’s strength like cross platform so it is possible to develop a servlet under linux and deploy it on NT without needing to change or recompiling • • If a server supports java it can load a new servlet and there is no need to modify the server • • The servlet architecture is designed to eliminate the need to reload the servlet every time a request is made

Servlets and JSP

4 • •

• • • • • •

• •

• •

• •

• • • • • •

The servlet is loaded once as it is needed after that it stays active turning requests into responses as fast as the web server can send them Servlets completely replaced CGI The next step was to building a templating system on top of servlet A servlet reads a file and figures out what to do based on special tags present in the file and does it A Boston based company called Art Technology Group (ATG) came up with an idea to translate the special tags directly into Java and then compile and run the java code The revolutionary concept called page compilation was introduced in the ATG application server named Dynamo Sun was very impressed by the concept of page compilation and they licensed the technology for inclusion in their Java Web Server The set of special tags that ATG had defined were somewhat cumbersome and sun refined these tags to create JSP Sun considered JSP as important enough to be included as a formal part of Java 2 Enterprise Edition The flow of information through a JSP is shown in the following figure

5

Flow of information through a Java Server Page 1 Client

1. Browser requests HTML

Server 7 2

6

2. Server sends request to Java Engine 3. If needed the Java Engine reads the JSP file

Servlet

Servlet

Servlet

5

5. The servlet runs and generates HTML

HTML

6. Java Engine sends HTML to server

Java Engine 4

4. The JSP is turned into a servlet compiled and loaded

3

7. Server sends HTML back to browser

Java Server Pages (JSP) • In a simple statement Java Server Pages is a combination of Java statements and HTML tags <% if (session.isNew()) %> Welcome user nice to see you <% else %> Glad to welcome you back JSP comments • In HTML comments are written like

6

Welcome To Java News Today

Your on-line home for up to the minute Java news

§ Home Page
§ Industry news
§ Enterprise Java
§ Standard Edition Java
§ Micro edition & devices
§ Beans
§ Editorials
The include directive

7 • • • • • •

• •

• •

• •

• • •

This is a simple jsp which contain only HTML tags Let it be a home page of Java News Today The page consists of three major sections the header, the navigation, and the main content area Different pages have different content but the header and navigation will be repeated all over the site If some new content should be added with the navigation it is very difficult to go back and re-edit all the pages The solution is include directive which allows any JSP file to include other JSP or HTML files The JSP files come from a designated JSP directory The header and navigator are pulled out and placed in a separate file

The header.jsp part <%-- Begin Header --%>

Welcome To Java News Today

Your on-line home for up to the minute Java news

<%-- End Header --%> The navigation.jsp part <%-- Begin Navigation --%> § Home Page
§ Industry news
§ Enterprise Java


8 § Standard Edition Java
§ Micro edition & devices
§ Beans
§ Editorials
<%-- End Navigation --%> The simple JSP with include directives <TITLE>Java News Today!
<%@include file="global/header.jsp"%>
<%@include file="global/navigation.jsp"%>
• • • •

The include directive tag is denoted by <%@include file=“---"%> The include directive starts with a <%@ and ends with a %>

9 •

The include directive will also point the location where the file to be included is located

Templating • •

A templating is an HTML page with some spaces where the spaces are filled with text plus some way to indicate where this text can

be found • •

The advantage of templating is that many pages require the same spaces and all these spaces can be filled from the same place

eg1. <%@include file="global/header.jsp"%> is a type of templating eg2. special tag for getting date and time from system :- eg3. including user’s name : “ Good Morning Mr. Thomas Mathew”

Request Time Expressions • • •

• •

• • •

The JSP Engine turns the .jsp file into a servlet The translation happens only once that is the first time the page is requested by a user This allows no dynamic content because for a page to be dynamic it must be rebuilt each time the page is requested Request time is the stage where the servlet is run and produces output Request time is where true dynamic content really begins because it gives the request time output which is the most current one

Expressions • An expression is a small piece of Java code that as the name implies expresses something •

10 •

Expressions are indicated by placing in the special tag <%=------%>

eg. 1 + 1 equals <%= 1 + 1 %> • When the browser access this expression the resulting page will be 1 + 1 equals 2 • An expression will be evaluated at the request time and the result will be given to the browser for display

The Implicit Objects •

JSP provides a great deal of useful information that the authors can use right away and these are called implicit objects

• •

Implicit means that there is no need for authors to explicitly declare that they will use these objects , they are automatically available • • Request is one among the implicit objects • When a request goes from a user’s browser to a server a lot of information is also sent including the browser used, the computer used, the page being requested, the kinds of information the browser will accept as response etc eg. Hello user! You are using a computer called <%= request.getRemoteHost() %> • Conceptually there is no difference between this example and the previous arithmetic example • The servlet will send the first part of the HTML and evaluate the expression request.get RemoteHost() and then send the result • There are a lot of methods available in the Request Object and they are

11

Methods in the Request Object Method

Purpose

getCharacterEncoding()

The character set in which this page is encoded ( eg. ISO )

getProtocol()

The protocol used for the request such as HTTP/1.0

getScheme()

The scheme portion of the URL such as HTTP

getServerName()

The name of the computer on which server is running

getServerPort()

The port server is listening to

getRemoteAddr()

The address of the computer the request came from

getRemoteHost()

The name of the computer the request came from

getAuthType()

The type of authorization used for this request (null value if page not protected)

Methods in the Request Object (contd.) Method

Purpose

getHeader()

Any header sent by the browser

getMethod

The method used for this request (usually GET or Post but also HEAD, PUT, DELETE etc)

getPathInfo()

The path information

getPathTranslated()

The path to the requested file on the server’s local file system

getQueryString()

The query string portion of the URL (ie anything after a question mark)

getRemoteUser()

The name the user logged in as

getRequestURL()

The full request URL of the JSP

A simple Calculator Program <TITLE>A simple calculator

Enter two numbers and click the 'calculate' button.



12



calculate.jsp <TITLE>A simple calculator: results

The sum of your two numbers is <%= Integer.parseInt(request.getParameter("value1")) + Integer.parseInt(request.getParameter("value2")) %>

• •

The getParameter() returns a string value The Java’ s Integer class has a method called parseInt() that takes a string and returns an integer

Using Beans • JSP can be used to call Java Beans • JSP provides three basic tags for working with beans • To find out and use the Bean • To get a property • To set one or more properties • There are many ways to use a bean so the use tag has a number of variations • The most basic form is <jsp:useBean id=“bean name” class=“bean class” /> • The “bean name” is the name that refers to the bean • The name should be a valid Java identifier • The “bean class” is the name of a Java class that defines the bean • The trailing slash at the end of the tag signals that there is no

13 corresponding close tag There is another variation of the useBean tag that takes a type parameter as well as a class <jsp:useBean id=“name” class=“bean class” type=“another class”> • This version the bean will be cast into an object whose type is given by type •

Getting a Property • Once the bean has been obtained with jsp:useBean getting a property is as simple as using the getProperty tag which is <jsp:getProperty name=“bean name” property=“propertyname”/> • • The “property name” is the name of the property to get • • The following is an example which uses the get property <jsp:useBean id="bean1" class="com.Bean1"/> <TITLE>Beans!

Here is some data that came from bean1:

  • The name of this bean is: <jsp:getProperty name="bean1" property="name"/>
  • The 7th prime number is: <jsp:getProperty name="bean1" property="seventhPrimeNumber"/>
  • The current time is: <jsp:getProperty name="bean1" property="currentTime"/>


14
">

The information from a bean can be used anywhere on the page!



• • • •

It is not necessary for the useBean tag to appear right at the top of the page but should appear before any getProperty tags Once the bean has been loaded the getProperty tags get various properties from it The getProperty tag can be converted into an expression tag that calls the bean’s GET method directly

• • The tag <jsp:getProperty name="bean1" property="seventhPrimeNumber"/> could be rewritten as <%= bean1.getSeventhPrimeNumber()%> Setting Properties • Setting a property looks like <jsp:setProperty name="bean name " property=“property name” value=“property value"> • • The “property name” is the name of the property to set and value is the new value to assign to the property • • The following is a JSP program that is used to set the date and time in different formats • • The format property is set numerous times and each value of the

15 property will be in effect until the next change <jsp:useBean id="date" class="com.DateBean"/> <TITLE>The Date Bean

Here is the current date, in a few different formats

    <jsp:setProperty name="date" property="format" value="EEEE, MMMM dd yyyy 'at' hh:mm"/>
  • <jsp:getProperty name="date" property="currentTime"/> <jsp:setProperty name="date" property="format" value="hh:mm:ss MM/dd/yy"/>
  • <jsp:getProperty name="date" property="currentTime"/> <jsp:setProperty name="date" property="format" value="yyyyy.MMMMM.dd GGG hh:mm aaa"/>
  • <jsp:getProperty name="date" property="currentTime"/>
The Connection between Forms and Properties • The dynamic pages are driven at least partially by values that users provide through forms • • Most program logic resides in beans and many JSPs take input values from forms, pass these values into beans via setProperty tags and then display other properties representing the result of some computation • • Form values could be passed to beans by a combination of

16 techniques such as <jsp:setProperty name=“id" property=“someproperty” value=<%= request.getParameter(“formparam“) %>”> • • If the form is providing a value called formparam and if the bean has a property that is also called formparam the code can be replaced by the single tag <jsp:setProperty name=“id" property=“formparam”/> • • If the name of the form parameter and the name of the property are different then they can be connected through another variation of the setProperty tag as <jsp:setProperty name=“id" property=“propertyname” param=“paramname”/> •

The JSP uses form parameter called paramname to set the property called propertyname

• •

There is another version of setProperty tag which is very powerful <jsp:setProperty name=“id" property=“*”> • This looks through all the parameters provided by the form and all the methods provided by the bean and links them together automatically • • If the form provides values called param1, param2, and so on and the bean has methods called setParam1(), setParam2() and so on everything matches perfectly •

• •

• •

If the form provides some parameters for which there are no methods these will be ignored and no error will occur If the bean provides methods for which the form does not supply values these methods simply are not called The following is the calculator program using beans

17 •

The code that had to deal with the inputs is hidden inside the bean along with the computation

The Calculator program using Beans <jsp:useBean id="calc" class="com.CalcBean"/> <jsp:setProperty name="calc" property="*"/> <TITLE>A simple calculator: results

The sum of your two numbers is <jsp:getProperty name="calc" property="sum"/>

Bean Instances and Serialization • • Most Java objects live only in memory as long as the Java Virtual Machine that created them lives • • Through a process called serialization most bean instances can be saved into files and read back later • • Serialization eliminates all the saving complexity by providing methods that will save any object to a file no matter how complex the object is or how many other objects it contains • • Every class that is to be serialized must implement the java.io.Serializable interface • • There is a slight variation in the way the useBean tag gets a serialized bean <jsp:useBean id=“name” beanName=“bean name” type=“bean class”>

18



Here id is the name by which the JSP will use the bean



beanName should be the name of a file containing a serialized bean



The files end with .ser extension but the extension will not be included in the name

• •

type is the class or interface for which the bean is an instance The following is a JSP that uses a serialized bean to get information about a record in this case “BAD” by Michael Jackson

An example of a Serialized Bean <jsp:useBean id="album" beanName=“BAD" type="com.AlbumInfo"/> " TEXT="<jsp:getProperty name="album" property="textColor"/>">

<jsp:getProperty name="album" property="name"/>

Artist: <jsp:getProperty name="album" property="artist"/>

Year: <jsp:getProperty name="album" property="year"/>



Serialized Bean example explanation • • •

• • • •

The properties of the bean is stored in the serialized file The background and the text color comes from the bean and is a useful technique when creating online catalog The serialization makes bean to behave like a database The “BAD” bean came as part of collection of beans for all of the Michael Jackson albums To create pages for others it would only be necessary to change beanName to “Thriller” or “Dangerous”.

19

Declarations and Explicit Objects •

Similar to Implicit objects there are Explicit objects those that a JSP creates before using

• •

The tag that creates new objects is called a declaration and it specifies the name and type of the object it is creating as well as an initial value for it eg. <%! int myInteger = 8; %> •





This declares that the JSP will use a new integer called myInteger and this integer will start life with a value of 8 The explicit object is also called a variable because its value can change The semicolon is necessary to signal the end of a Java statement including declarations

• • The declaration which defines two integers is also valid <%! int myInteger = 8, anotherInteger = 12; %> • Once a variable has been declared it can be used just like an implicit object in expressions • • It is not necessary to give a variable an initial value • Java sets all integer variables to 0 if they do not have initial values • Following is a JSP which declares a number of variables and used A JSP which declares a number of variables <TITLE>Some declared variables <%! int anInteger = 5; %> <%! int anotherInt = 7; %> <%! double pi = 3.1415926; %>

The value of anInteger is now <%= anInteger %>.

The value of anotherInt is now <%= anotherInt %>.

The value of pi is now <%= pi %>.

The value of anInteger + 1 is <%= anInteger + 1 %>.

The area of a circle with a radius of 2 inches is

20 <%= pi * 2 * 2 %> inches.

<%! java.util.Date now = new java.util.Date(); %>

Today's date is <%= now.getDate() %>

Scriptlets • • A scriptlet is a piece of Java code that is sandwiched between the characters <% and %> • • Any Java code can be placed within the tag and it will run each time the page is accessed eg. <% for (int i=100; i>=1; i--) { out.print(i) out.println(“ characters are there in the drama
”); } %> • The code in a single sciptlet does not need to be self contained Three important elements of JSP code The elements

Declaration

Scriplet

Enclosed in

<%!

<%

Contains

One or more Java declarations

Java code (fragments or complete statements)

One Java expression

What it does

Creates a name possibly gives the name a value

Tells the system to do something

Has a value

When the JSP container runs it

When the page is first visited or the JSP container reinitializes the page

Whenever someone visits the page

Whenever someone visits the page

%>

Expression %>

<%=

%>

COUNTER • A counter shows how many times a page has been accessed • Counters are in use all over the Web

21 <%! int count =0; %> <TITLE>A Counter <% count = count + 1; %>

This page has been accessed <%= count %> times.

• •

The scriplet increments the counters value by 1 The next time someone access the page the count will be incremented by one

• When the server shuts down the counter value is stored in a file CONDITIONALS • Java has a mechanism that can be used in JSP called the if statement which can do one of two things based on some condition <%! int count =0; %> <TITLE>A Counter <% count = count + 1; %>

This page has been accessed <%= count %> times.

<% if (count == 1) { out.print("

Welcome, first visitor!

"); } %> • The if statement can be extended using an else part which can do one thing if a condition is satisfied and another thing if the condition is not satisfied <%! int count =0; %> <TITLE>A Counter

22 <% count = count + 1; %> <% if (count == 1) { %>

Welcome, first visitor!

<% } else { %>

You are not the first visitor. <%= count-1 %> other visitors have already been here,

<% }%> • Nesting of conditions can also be used in JSP <% String browser = request.getHeader(“User-Agent”); %> <%if (browser.indexOf(4.”) != -1) { %>

You have a recent browser, enjoy the site!

<% } else { %> <% if (browser.index.of(“MSIE”) != -1) { %>

You do not have a recent enough version of IE to use all the features of this site. You can download one here..

<% } else if (browser.index.of(“Mozilla”) != -1) { %>

You do not have a recent enough version of Netscape Navigator to use all the features of this site. You can download one here..

<% } %> <% } %> LOOP • The for loop is the most commonly used loop • A for loop has a counter that starts at some value and repeats some action until that counter reaches another value • Each time it performs the action it can also add or subtract some quantity from the counter <%! String confs[ ];%> <% for (int i=0; i
  • <%=confs[i] %> <% } %> •

    A while loop can be used when some condition continues to be true

    <% java.util.Enumeration e = request.getHeaderNames(); %>

    Here are the names of the headers that have been sent:



    23
      <% while (e.hasMoreElements()) { %>
    • <%= e.nextElement() %> <% } %>
    <TITLE>A simple calculator: results

    <% try { %> <% int result = Integer.parseInt(request.getParameter("value1")) + Integer.parseInt(request.getParameter("value2")); %>

    24

    The sum of your two numbers is <%= result %>

    <% } catch (NumberFormatException nfe) { %>

    Sorry, I was unable to compute the result, because one of the values provided was not an integer.

    <% } %> BEANS AND SCRIPLETS • Beans and scriptlets complement each other quite nicely • The scriptlet code typically can be removed entirely from a page and placed in a bean • This will leave only the code that the page needs in order to react to different input or loop over a set of data obtained from the bean • The following is another version of calculator which uses a bean • The JSP properly handles the non-numeric input • The scriptlet uses isValid() method in the bean to determine if the input is valid, if not the bean makes another property called reason available which contains a description of the problem EG: <jsp:useBean id="calc" class="com.CalcBean"/> <jsp:setProperty name="calc" property="*"/> <TITLE>A simple calculator: results <% if (calc.isValid()) { %>

    The sum of your two numbers is <jsp:getProperty name="calc" property="sum"/>

    <% } else { %>

    Sorry, I could not compute the sum becuase <jsp:getProperty name="calc" property="reason"/>

    <% } %>

    25

  • Related Documents

    Jsp
    April 2020 36
    Jsp
    May 2020 27
    Jsp
    May 2020 14
    Jsp
    May 2020 14
    Jsp
    July 2020 16
    Jsp
    November 2019 49

    More Documents from ""