JEE-JSP

download JEE-JSP

of 23

Transcript of JEE-JSP

  • 8/13/2019 JEE-JSP

    1/23

    1.1 Introduction to Web

    The web is a complex, international, cross platform, cross language, cross cultural mesh ofservers, clients, users, databases and quite a few artificial intelligence all connected to each otherand capable to talk to each other. The web is owned by no single entity because it cannot beconsidered as a thing but as a process, action and communication medium.

    Initially web was originated to fulfill the need for a collaborative knowledge sharing tool" (tosupport scientific work) in an international context. Now it is providing access to information,news, email, shopping and entertainment. For different people web has different meaning, tosome people it is like a newspaper, magazine or a library of any kind of books. To some people itis a radio or TV where they can access any latest information around all over the world. To some

    people it serves like a communication medium. To some people it is an open market where theycan get anything of their interest without going out of their house. So it can be concluded that its

    domain is not restricted to the boundations.

    1.2.1 Common Gateway Interface :

    The program, which generates dynamic content using CGI technology are known as CGIProgram.

    The CGIs are written in C, perl and Fortran language. Earlier the programs were written in Clanguage. Being a compiled language the C programs run very fast but the problems with thisapproach were:

    First, it was relatively difficult to change the programs. Instead of just editing a file containingthe program, the programmer must recompile the program each time there are some changes. But

    that was only the problem of one time when the program is changed after it gets compiled, thecompiled program is fast to run.

    The second problem is that C is low-level language. It is difficult to manipulate large blocks ofthe code. This is especially a problem in CGIs where the goal is to transfer the user requests intothe HTML representing server response.

    Then came the Perl for the scripting purpose. Perl programs do not need to recompile every timethey are changed because Perl is an interpreted language. Every time a Perl program runs,another program called the Perl interpreter is also loaded which reads the program, translates itinto instructions that computer can understand. This translation also takes time and hence Perl

    program sacrifice the speed at run time in favor of fast development and changes.Hence, the main disadvantage of the CGI program is that each time when a request comes to theserver from the client the CGI script written in any of the language either Perl or C is run from

    the server to create the requested page which involves creation of new process into which thescript is loaded and Perl interpreter is loaded (if the CGI is written in Perl) and then unloadedafter response is finished. The same process is repeated if the same page is requested again. Forexample if there are N requests for a web page, the script and the Perl interpreter will be loaded

  • 8/13/2019 JEE-JSP

    2/23

  • 8/13/2019 JEE-JSP

    3/23

    JSP pages are accessed fast then ASP pages because after first compilation JSP pages are notcompiled again if there is no modification in the JSP source file, while ASP are interpreted bythe .dll file residing at the server each time new request comes from the user.JSP 1.2 specification adds a new functionality to JSP pages called the Extensible Tags. Thedeveloper can create his own tags and can use them in any number of JSP pages. ASP does notfavor this feature.

    In brief the ASP and JSP technologies can be compared as the following table:

    Criteria of comparison ASP JSPScripting languages VB script, Jscript JavaWeb server IIS PWS Any web server including

    Apache, IIS, Netscapeserver

    PlatformsMicrosoft windows Solaris Operatingenvironment Microsoft

    windows, Unix, LinuxComponents Com Beans, EJBs, extensible tag

    libraryCompatibility with thelegacy database

    Yes(*Com API) Yes(JDBC API)

    Data source compatibility Any ODBC, DAO, ADOdata source

    Yes (using JDBC API)

    Custom tag extension No Yes

    * Com Connecter can be developed using any Component supporting language like VB, VCto connect to the legacy database.

    1.3 JSP Architecture :

    JSP is a part of the Java platform Enterprise Edition (J2EE), which is the Java architecture fordeveloping multi-tier enterprise applications. A JSP page is executed by a JSP engine, which isinstalled in a web server or a JSP enabled application server.The JSP request response involves a four step architecture which can be described as follows:

    When JSP engine first time receives the request for some JSP page it parses the JSP file andcreate the Java source code file.

    The second step is the compilation of this source code into the class file. This is the Servletfiles and is handled by the Servlet engine.

    The third step involved is the execution of the Servlet.

    In final step the servlet executes and response is send back to the client.

  • 8/13/2019 JEE-JSP

    4/23

    The first and second steps occur only once since the jsp is loaded or updated and third step is performed once since the server was last started. Once the Servlet is executed it becomesavailable there for the life cycle of the Java Virtual Machine, hence there is no need for itsexecution again and again.

    Fig 1.1: The Figure shows the flow of request and response when a jsp page is called.

    1.4. JSP Implementation Environment

    1.4.1. Explain, What is Web Server?

    On the Internet, Http is used for communication, which works on port 80. A web server is aServer-side application that listens to port 80. Any Http request submitted would travel over port80, and will be intercepted by assigned web server. The Web server receiving the request would

    process it or may transmit it to enterprise application like EJBs for the next level of processing.After the request has been completely processed, the web server would send appropriateresponse to the client Browser and hence complete this web-based communication.

    Apache web server is a JSP enabled web server, which can be freely downloaded fromapache.org & configured to have maximum share of the web server net.

    JSP pages can be used in combination with Servlets, HTML, XML, Applets, JavaBeanscomponents and Enterprise JavaBeans components to implement a broad Varity of applicationarchitecture.

    The main Architectures in which JSP fits can be described as follows:

    1.4.2. Two Tier Architecture:

    Two Tier Architecture is also known as Client Server Architecture. In simple 2-tier architectureonly two layers are involved in the processing, one is client and the other is server. All the

    business logic (JSP files) resides at the client and the server is devoted for the database. Theclient makes a request that is sent to the JSP file. The architecture can be better understand withthe help of following diagram:

    Client

    JSP Engine

    &Web server JSP fileCom onent

    Res onse

    Re uest

    Re uest Re uest

    Res onRes onse

  • 8/13/2019 JEE-JSP

    5/23

    Client Server

    Fig 1.2 Simple Two -Tier Architecture

    This approach has the following advantages:

    1. It is Simple and faster to program.2. The developer can easily generate dynamic content based on request and state of response.

    The main problem with the approach were:

    1. It is difficult to maintain changes.2. It is very difficult to reuse the presentation and business logic.3. No manageable for internet applications

    1.4.3. 3 - Tier Architecture:

    In Three-Tier Architecture the application involves three logical layers each of which isresponsible for well-defined tasks.The first layer of 3-Tier Architecture is the Presentation Layer, which consists of a GUI fromwhich user can send his requests and see the responses.The second or middle Tier is the Business Layer, which consists of all the business logic.The third and the last layer is the Data Layer, which stores all the data required for theApplication.

    The business layer typically consists of Java code, which can be either Java Beans, Java Servletsor simple Java classes or combination of these. This layer is independent of presentation layerand the data layer, it just receives request from the Presentation layer, processes the request andinteracts with data layer if required, and passes the response back to the Presentation layer. Themain benefit of this architecture is that being independent layers multiple use interfaces can be

    built and deployed without effecting the application which can serve different type of users like

    internet user (using HTML in presentation layer), mobile user (using WAP technology in presentation layer) and much more.

    The presentation layer can either be some HTML page or some WAP application.

    Response

    RequestGUI JSP Data

    base

    Request for data

    Selected data

  • 8/13/2019 JEE-JSP

    6/23

    The third layer, the data layer consists of the data required for the application. This data can beany standard database such as Oracle, Sybase, a set of XML documents or a directory servicelike LDAP.The 3-Tier Architecture can be better understood by the following diagram:

    Fig 1.3 Simple Three -Tier Architecture1.4.4. N- Tier Architecture:

    In N-Tier Architecture there is no hard and fast rule to define the application layers. An n-tierarchitecture can support a number of different configurations. The basic difference between 2-tier and N-tier architecture is that unlike 2-tier in N-tier architecture the application logic isdivided functionally rather than physically. N-tier architecture is very supportive to the conceptof reusing the components.

    An N-Tier Architecture can provide different layers which supports the following functionalityindividually:

    User InterfaceApplication

    Layer

    Data base

    XMLDocument

    LDAP

  • 8/13/2019 JEE-JSP

    7/23

    User Interface: Handles the user interaction with the application. For example a Web

    browser. Presentation logic: defines what the user interface displays and how a user's requests are

    handled. Business Logic: handles the application's business rules through the interaction with the

    application's data. Infrastructure Services: provides additional functionality required by the application

    components, such as messaging, transaction support etc. Data layer: the data regarding the application resides in this layer.

    Fig 1.3 Concept of Simple N-Tier Architecture

    1.5. JSP engine:

    Browser

    Presentation Lo ic

    Business Lo ic

    Services

    XML DocumentsData base

    LDAP

  • 8/13/2019 JEE-JSP

    8/23

    When the browser sends a request to the server for the JSP page, the server forwards the requestto the jsp engine. Jsp engine translates the jsp page into java Source code that is converted into aServlet class by the servlet engine. This conversion of the jsp file and compilation occurs onlywhen the file is first called after uploading or it is updated. After the first request other requestsfor the page directly goes to the Servlet Byte Code. The JSP engine is installed on a web server(Apache-Tomcat) or on the application server (Weblogic).JSP engine must support HTTP as a protocol for requests and responses, but an engine may alsosupport additional request / response protocols. The default request and response objects are oftype HttpServletRequest and HttpServletResponse respectively.Summary:

    Server side programming is needed to process the request coming from the client and togenerate the response.

    CGI scripts, Servlets, ASP and JSP are used for the purpose of server side programming.

    CGI scripts are slow and a lot of system resources are wasted due to creation of new process for each request.

    Servlets are the Java solution to the problem of CGI scripts. In servlets no new process isstarted for every request so they save system resources like memory and processor speed.

    ASP is the Microsoft solution for the Server side programming. In ASP the scriptinglanguage is VB script.

    Servlets involves business logic and presentation logic together, so they are difficult tocode.

    JSP is the solution to the problem of Servlets and separates the business logic and

    presentation logic. A JSP page is executed by a JSP engine, which is installed in a web server or a JSP

    enabled application server.

    JSP can be fitted into two tier, three tier or N-tier architecture.In two-tier architecture the layers are separated physically while in N-tier architecture the layersare separated functionally.

    2.1 JSP Basic Syntax

    JSP technology provides with the facility to mix static HTML elements with dynamic content

    that was not an easy thing with the Servlets. In simple HTML pages dynamic contents is added

  • 8/13/2019 JEE-JSP

    9/23

    by using tags. All dynamic contents come in between tags. These tags are called

    special tags in JSP. This change from HTML to JSP to include dynamic content is simple and

    quite subtle at first glance.

    2.2 JSP Templates

    A large percentage of JSP page just consists of static HTML, known as template text . In almostall respects, this HTML looks just like normal HTML, follows all the same syntax rules, and issimply passed through to the client by the servlet created to handle the page by the JSP engine.

    There are two minor exceptions to the template text is passed straight through rule.First, if

  • 8/13/2019 JEE-JSP

    10/23

    These are the tags, which, are used to create new objects and variable of any data type as well as

    providing initial value to them.

    The syntax for Declaration is given as follows:

    Declaration contains one or more variables or object declarations that end or are separated bysemicolons:

    //declaring and initializing single variable //declaring many variables

    //instantiating object

    2.3.2 JSP Expressions

    Expressions can contain any valid expression which is valid in the scripting language, if the

    scripting language is Java then expressions will follow all the Java conventions. The syntax for

    the JSP expression is given as follows

    The example of Expression can be given as follows:

  • 8/13/2019 JEE-JSP

    11/23

    Notice in the examples that statements are not ending with the semicolon. In JSP Expressions,

    expressions are not terminated by the semicolon.

    Following is the example to illustrate the use of JSP Expression:

    //declaration

    The test example for JSP expressionsthe sum is //this is JSP expression

  • 8/13/2019 JEE-JSP

    12/23

    Listing 2.1 expression.jsp

    The output screen for the above example is as follows:

    Figure 2.1 Output for expression

    2.3.3 JSP Scriptlets

    JSP Scriptlets are executed at request-processing time. They allow writing any number of validscripting language statements.Following tasks can be done within a scriptlet:

    Declare variables or methods to use later in the file. Write expressions valid in the page scripting language. Write any other statement valid in the scripting language used in the JSP page

  • 8/13/2019 JEE-JSP

    13/23

    Any text, HTML tags, or JSP elements must be outside the scriptlet.

    The syntax for using JSP Scriptlets can be given as follows:

    Scriptlets end with a semicolon (;) if the language require it.

    Example of valid scriptlet can be:

    Following example makes clear use of scriptlets in a conditional statement:


    less then dozen

    12){%>
    more then dozen


    a dozen

  • 8/13/2019 JEE-JSP

    14/23

    Listing 2.2 scriptlets.jsp

    It is must to close

  • 8/13/2019 JEE-JSP

    15/23

    2.3.4 A Complete Example using Declaration, Expression and Scriptlet

    Consider the following code:

    Listing 2.3 date.jsp

    use of declarations, expression and scriptlet today's date is/

  • 8/13/2019 JEE-JSP

    16/23

    The above example is using:

    JSP Declaration to instantiate the object of Date class, expression to print today date at the client end and scriptlet to print today date at server console at the server end.

    System.out.println is used to display any data or message at the server end, which helps in

    debugging the code.

    2.3.5 When is the Scripting Elements executed

    A JSP source file is processed in two stages Http translation time and request processing time.

    At HTTP translation time , which occurs when a user first loads a JSP page, the JSP source file iscompiled to a Java class, usually a Java servlet. The HTML tags as many JSP tags as possible are

    processed at this stage, before the user makes a request.

    Request processing time occurs when user submit some request from the JSP page. The requestis sent from the client to the server by way of the request object. The JSP container then executesthe compiled JSP file, or servlet, using the request values the user submitted.

    In JSP, declarations are processed at request processing time and are available to otherdeclarations, expression, and scriptlets in the compiled JSP file. Expressions are evaluated atrequest processing time. The value of each expression is converted to a String and inserted in

    place in the compiled JSP file. Scriptlets also are evaluated at request processing time, using thevalues of any declaration that are made available to them.

    2.4 JSP Implicit Objects

    To simplify the code JSP is provided with some predefined variables sometimes called theimplicit objects. These objects need not to be declared or instantiated anywhere but these arealready provided by the container in the implementation class.

  • 8/13/2019 JEE-JSP

    17/23

    These can be used only in the scriptlets and expressions and not in declaration. Because thedeclaration part is converted into declaration of variables used in the methods but these arealready declared with the container in the implementation class so no need for the redeclaration.

    In details these objects can be defined as follows:

    2.4.1 Request Object

    This is the object associated with HttpServletRequest class. It is responsible to take the formelements and pass to the JSP by the JSP container as a parameter to the _jspService () method.The scope of request object is request only.

    There are some important methods of Request object which are commonly used in JSP pages,these methods and their usage are listed in the following Table:

    Method Purpose

    getCharacterEncoding () The character set in which this page isencoded (e.g, ISO)

    getProtocol () The protocol used for the request(HTTP/1.0)

    getScheme () The scheme portion of the URL such asHTTP

    getServerName () The name of the computer on which theserver is running

    getServerPort () The port the server is listening

    getRemoteAddr () The address of the computer the requestcame from

    getRemoteHost () The name of the computer the requestcame from

    getAuthType () The type of authorization used for therequest (if the page is not protected it will

    be null)

    getHeader () Any header sent by the browser

    getMethod () The method used for the request (post,get)

    getPathInfo () The path info

    getPathTranslated () The path to the requested file on theservers local filesystem

  • 8/13/2019 JEE-JSP

    18/23

    getQueryString () The query string portion of the URL.(The portion after the question mark)

    getRemoteUser () The name of the user logged in as (if the page is not protected, its value will benull)

    getRemoteURI () The full request URL of the JSP.

    Table 2.1 Methods of Request Object

    2.4.2 Response Object

    This is the object associated with HttpServletResponse class. It is responsible to deliver therequested data, which is produced by the JSP to the client. It is passed to the JSP by the JSPcontainer as a parameter to the _jspService () method. The scope of response object is response.

    2.4.3 Processing Form Data Using Request and Response Object

    When user submits some data to the server from the form, it is processed there and response issend back to the user. The task of sending the data to the server and from the server to the user isaccomplished by the request and response objects.

    Consider the following Form in which user will submit his name and age to the server which will be displayed to him from the sever in response.

    The sendreq.html will contain the User From The showResp.jsp will process the request and send the response back to the user.

    The code for sendreq.html can be given as follows:

  • 8/13/2019 JEE-JSP

    19/23

    Listing 2.3

    Listing 2.4 sendreq.html

    The code for showResp.jsp can be given as follows:

    Listing 2.5 showResp.jsp

    Use of Request and Response ObjectsEnter Your name here

    This is the response of uor requestThe name of the user is
    the age of the user is

    Enter your age here

  • 8/13/2019 JEE-JSP

    20/23

    The output of the sendreq.html is

    Figure 2.2 User Form to send the request

    The responses send back to the client will be

    Figure 2.3 Response send back to the userAbove is the Response send back to the user if he enters name as Deepti agrawal and age as23.

    2.4.4 Page Object This object is associated wit h Object class and is accessed using this reference like in Java programming language. The scope of the object is

    page.

    2.4.5 PageContext Object

  • 8/13/2019 JEE-JSP

    21/23

    This object is associated w ith PageContext object. This is used to access different attributes of a page at single point. The PageContext objectholds the value of the different at tributes of the current page. The scope of the variable is Page.

    2.4.6 Session Object This object is associated with HttpSession class. This variable is used to maintain the sessioninformation. Sessions are created automatically so it is always created even if there is no sessionreference in incoming request. The session can be turn off by assigning false value to thesession attribute in of the page directive. The values in the session can be placed and retrieved byusing setAttribute () and getAttribute () methods. The scope of the object is session.

    2.4.7 Application Object

    This object is associated with the ServletContext and obtained as getServletContext.getContext

    (). JSP pages can store and retrieve the information in ServletContext object using setContext ()

    and getContext () methods rather then storing in any variable.

    The ServletContext is shared by all the servlets in the servlet engine and so the data can beretrieved anywhere in the application. The scope of the object is Application

    2.4.8 Out Object This is the object associated with the JspWriter class. In order to make the response objectuseful, this is the buffered version of PrintWriter class of JspWriter. The buffer size can be

    controlled by the buffer attribute of page directive. The scope of the object is page.

    2.4.9 Config Object This object is associated wit h the ServletConfig object. It represents the Servlet configuration. The scope of this variable is page.

    2.4.10 Exception Object This object is associated w ith java.lang.Throwable class. It refers to the runtime exception that resulted in the error page being invoked. And isavailable only in an error page. The concept of error page will be discussed later in the book

    The throwable object describing the exception may be accessed within the error page by the exception object.

    2.5 JSP Standard Actions

    JSP Actions are the special tags that affect the behaviour of the JSP at the run time and affectsthe response, which is, send back to the client. There are some standard JSP actions. These

  • 8/13/2019 JEE-JSP

    22/23

    Standard actions are provided with some basic functionality, which benefits to the author whiledesigning the web page. All JSP containers implement these actions.

    The standard action types are:

    Out of which , and are used with the JavaBeans which will be discussed in the coming chapters.

    Summary:

    The chapter introduces to you with the basic building blocks of the JSP. These can besummarized as follows:

    Scripting language is a mechanism for embedding code directly into a HTML page. Thereare three classes of the Scripting elements:

    o Declarations:

    o Expressions:

    o Scriptlets: .

    To simplify the code JSP is provided with some predefined variables sometimes called theimplicit objects. JSP has provided with the following implicit objects:

    Request Object, Response Object, Page Object, PageContext Object, Session Object,Application Object, Out Object, Config Object, Exception Object

    JSP Actions are the special tags that affect the behaviour of the JSP at the run time and to theresponse. Following actions are supported by the JSP:

    , , , , jsp:forward>,, and

    Directive provides global information that is conceptually valid independent of any specificrequest received by the JSP page, the syntax of Directive .

    There are three possible directive currently defined by the JSP specification:

    o Page:- Defines information will be available globally for that JSP

  • 8/13/2019 JEE-JSP

    23/23

    o Include:-The include directives is used to insert text and code at JSP translation time.

    o Taglib: - The taglib directive declares that the page uses custom tags, uniquely namesthe tag library defining.