SlideShare ist ein Scribd-Unternehmen logo
1 von 11
Downloaden Sie, um offline zu lesen
JavaServer Pages
By: Abdalla Mahmoud.


Contents
            JavaServer Pages................................................................................ 1
              Contents ........................................................................................... 1
              1. Introduction ................................................................................... 3
              2. First JSP ........................................................................................ 4
              3. Syntax Elements............................................................................. 4
                3.1. Comments ............................................................................... 4
                3.2. Scriptlets ................................................................................. 5
                3.3. Expressions .............................................................................. 5
                3.4. Declarations ............................................................................. 6
                3.5. Directives................................................................................. 6
                4.1. Example................................................................................... 7
                  4.1.1. JSP .................................................................................... 7
                  4.1.2. Corresponding Servlet Class .................................................. 8
              5. Implicit Variables ............................................................................ 9
              6. Hoax Example - Revisited ................................................................ 9
                6.1. Process Servlet ........................................................................ 10
                6.2. View Servlet ............................................................................ 10




                                                      1
2
1. Introduction
   JavaServer Pages are web components that generate dynamic web content. Like servlets,
JSPs process requests from agents and generate responses. However, JSPs are designed to
be more close the nature of web pages than language classes. JSPs are compared to servlets
as follows:

                        JSPs                                      Servlets
They are not java classes. They are dynamic They are java classes.
web pages.
Include content with embedded java code.     Include java code embedded with content.
They are more close to presentation logic.   They are more close the business logic.
They are not compiled.                       They are compiled and described in the
                                             deployment descriptor.
They are translated to servlets automatically They are not translated to something else
by the application server on deployment.      and deployed by themselves as primitive
The translation process in transparent to the web components.
developer.


Here's a programmatic example demonstrating the practical differences between JSPs and
servlets:

file: index.jsp                              file: WEB-INF/classes/w/
                                             IndexServlet.java
<html>                                       package w ;


  <head>                                     import javax.servlet.* ;
       <title>First JSP</title>              import javax.servlet.http.* ;
  </head>                                    import java.io.* ;


  <body>                                     public class IndexServlet extends HttpServlet {
  <%
  String name =                                  public void doGet(HttpServletRequest
       request.getParameter("user_name") ;         request, HttpServletResponse
  out.print("Welcome " + name) ;                   response) throws ServletException,
  %>                                               IOException{
  </body>
                                                   PrintWriter out =
</html>                                               response.getWriter() ;
                                                   out.println("<html>") ;
                                                   out.println("<head>") ;
                                                   out.println(
                                                         "<title>First JSP</title>") ;
                                                   out.println("</head>") ;




                                             3
out.println("<body>") ;


                                                      String name =
                                                        request.getParameter(
                                                        "user_name") ;
                                                      out.println("Welcome " + name) ;


                                                      out.println("</body>") ;
                                                      out.println("</html>") ;


                                                  }


                                              }




2. First JSP
Here's an example of a JavaServer Page that generates dynamic output:

file: index.jsp
<html>

      <head>
           <title><% out.print("First JSP") ; %></title>
      </head>

      <body>
           <%
                  String name = request.getParameter("user_name") ;
                  out.print("Welcome " + name) ;
           %>
      </body>

</html>



3. Syntax Elements
   JSP primarily enclose page contents, or static parts of the page, with embedded JSP
elements of different types of declarations and actions. Here're some syntax elements of the
JSP technology.

3.1. Comments

Comments can be included in JSPs between <%-- and --%>. See the following example:




                                             4
Example: JSP Comment
<html>

      <head>
           <title>First JSP</title>
      </head>

      <body>
           <%-- Print a welcome message to the user %-->
           <%
                String name = request.getParameter("user_name") ;
                out.print("Welcome " + name) ;
           %>
      </body>

</html>


3.2. Scriptlets

Sciptlets are snippets of java code that generate dynamic content. Scriptlets can be included
in JSPs between <% and %>. See the following example:

Example: Scriptlets
<html>

      <head>
           <title>First JSP</title>
      </head>

      <body>
           <%-- Print a welcome message to the user %-->
           <%
                String name = request.getParameter("user_name") ;
                out.print("Welcome " + name) ;
           %>
      </body>

</html>



3.3. Expressions

Expressions are java language expressions that generate values inserted within content.
Expressions can be included in JSPs between <%= and %>. See the previous example
rewritten using expressions as the following:

Example: Expressions
<html>




                                             5
<head>
           <title>First JSP</title>
      </head>

      <body>
           <%-- Print a welcome message to the user %-->
           Welcome <%= request.getParameter("user_name") %>
      </body>

</html>



3.4. Declarations

Declarations are any class valid declaration that will be included in the generated servlet.
Declarations can be used in other scriptlets and expression elements. Declarations can be
included in the JSP between <%! and %>. See the following example:

Example: Declarations
<%!

      int count ;

      public int getVisitorNumber() {
           return ++count ;
      }

%>
<html>

      <head>
           <title>Example JSP</title>
      </head>

      <body>
           Welcome, you are visitor number: <%= getVisitorNumber() %>
      </body>

</html>



3.5. Directives

Directives provide information about the page to the JSP engine. Directives can be included
in JSP pages between <%@ and %>. JSP Directives include:

                  Directive                                      Purpose
<%@ include file="header.html" %>             include a file within the page.



                                             6
<%@ page import="java.io.File" %>               import a name used in a declaration.

See the following example:

Example: Directives
<%@ page import="java.io.File" %>
<html>

          <%@ include file="header.html" %>

          <body>
               <%
                     File f = new File(request.getParameter("file")) ;
                     //display file content code
               %>
          </body>

</html>


file: header.html
<head>
     <title>First JSP</title>
</head>


4. JSP Translation Process
    As mentioned earlier, JSPs are translated transparently to servlets. Although the
translation process is transparent to the developer, knowledge of the translation process
helps understanding JSP syntax. Translation process is simple and straightforward:

      •    a _jspService() method is generated to handle all HTTP request methods.
      •    Contents are printed to the output stream in order in _jspService() mehtod.
      •    Comments are ignored.
      •    Scriptlets are embedded within the _jspService() method in order.
      •    Expressions are printed to the output stream in order within _jspService().
      •    Declarations are written within the servlet's class body.


4.1. Example

Here is an example of how a JSP is translated into a servlet in runtime.

4.1.1. JSP


example.jsp
<%!




                                               7
int count ;

     public int getVisitorNumber() {
          return ++count ;
     }

%>
<html>

     <head>
          <title>Example JSP</title>
     </head>

     <body>
          Welcome, you are visitor number: <%= getVisitorNumber() %>
     </body>

</html>


4.1.2. Corresponding Servlet Class


Runtime Class
package foo ;

import javax.servlet.* ;
import javax.servlet.http.* ;
import java.io.* ;

public class ExampleServlet extends HttpServlet {

     int count ;

     public int getVisitorNumber() {
          return ++count ;
     }

     public _jspService(HttpServletRequest request, HttpServletResponse
          response) throws ServletException, IOException {

           //bold are implicit variables generated automatically
           PrintWriter out = request.getWriter() ;
           HttpSession session = request.getSession() ;

           out.println("<html>") ;
           out.println("<head>") ;
           out.println("<title>Example JSP</title>") ;
           out.println("</head>") ;




                                       8
out.println("<body>") ;
             out.print("Welcome, you are visitor number: ") ;
             out.print(getVisitorNumber()) ;
             out.println() ;
             out.println("</body>") ;
             out.println("</html>") ;
      }

     public void goGet(HttpServletRequest request, HttpServletResponse
response)
          throws ServletException, IOException {

             _jspService(request, response) ;
      }

      public void goPost(HttpServletRequest request, HttpServletResponse
           response) throws ServletException, IOException {

             _jspService(request, response) ;

      }

      //same for rest HTTP methods methods

}




5. Implicit Variables
   Implicit variables are variables defined by the application server on translating the JSP into
the corresponding servlet. Implicit variables can be used by other scriptlets and expression
elements. Every implicit variable represent some aspect to the web developer. Here is a list
of some implicit variables:

                   Variable                                         Aspect
out                                              Response stream.
request                                          HTTP request.
response                                         HTTP response.
session                                          HTTP session object.



6. Hoax Example - Revisited
Our target is to develop a web application that allows a user to add two numbers. consist of
the following resources:



                                               9
• A form page (page.html).
     • A servlet that process and display the output (ProcessServlet).
     • A JSP that display the output (viewResult.jsp).

The web application will work in the following scenario: the user requests page.html, fill
the form, post the data. The data is processed by ProvessServlet, which will forward the
request to the viewResult JSP to view the data. Although a trivial example, it's the main
concept in separating the controller from the view in web design patterns using JSPs.

6.1. Process Servlet

file: WEB-INF/classes/webapp/ProcessServlet.java
package webapp ;

import javax.servlet.* ;
import javax.servlet.http.* ;
import java.io.*;

public class ProcessServlet extends HttpServlet {

     public void doPost(HttpServletRequest request, HttpServletResponse
response) throws IOException, ServletException {

         float num1 = Float.parseFloat(request.getParameter("num1")) ;
         float num2 = Float.parseFloat(request.getParameter("num2")) ;
         float result = num1 + num2 ;

         //set attribute to be shared with the delegates

         request.setAttribute("result", reuslt) ;

        //create a request dispatcher from the request object
        RequestDispatcher rd =
request.getRequestDispatcher("/viewResult.jsp") ;
        //forward the request passing request and response objects
        rd.forward(request, response) ;

    }

}


6.2. View Servlet

file: viewResult.jsp
<html>




                                           10
<head>
      <title>Result by Process Servlet</title>
   </head>

   <body>
      Result = <%= request.getAttribute("result") %>
   </body>

</html>




                                     11

Weitere ähnliche Inhalte

Was ist angesagt?

TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable Applications
Alessandro Molina
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
tutorialsruby
 
Introduction to JSP
Introduction to JSPIntroduction to JSP
Introduction to JSP
Geethu Mohan
 
Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advanced
BG Java EE Course
 

Was ist angesagt? (20)

TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable Applications
 
Library Project
Library ProjectLibrary Project
Library Project
 
JSP - Java Server Page
JSP - Java Server PageJSP - Java Server Page
JSP - Java Server Page
 
Java serverpages
Java serverpagesJava serverpages
Java serverpages
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Jsp
JspJsp
Jsp
 
Servlet and jsp interview questions
Servlet and jsp interview questionsServlet and jsp interview questions
Servlet and jsp interview questions
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Java Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet BasicJava Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet Basic
 
Zend
ZendZend
Zend
 
Django
DjangoDjango
Django
 
Django
DjangoDjango
Django
 
Servlets
ServletsServlets
Servlets
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
Bt0083 server side programing 2
Bt0083 server side programing  2Bt0083 server side programing  2
Bt0083 server side programing 2
 
Download It
Download ItDownload It
Download It
 
Mule caching strategy with redis cache
Mule caching strategy with redis cacheMule caching strategy with redis cache
Mule caching strategy with redis cache
 
RESTEasy
RESTEasyRESTEasy
RESTEasy
 
Introduction to JSP
Introduction to JSPIntroduction to JSP
Introduction to JSP
 
Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advanced
 

Andere mochten auch (8)

IBM_Participation_4
IBM_Participation_4IBM_Participation_4
IBM_Participation_4
 
Java EE Services
Java EE ServicesJava EE Services
Java EE Services
 
Persistence
PersistencePersistence
Persistence
 
Introduction to Java Enterprise Edition
Introduction to Java Enterprise EditionIntroduction to Java Enterprise Edition
Introduction to Java Enterprise Edition
 
Introduction to jsf2
Introduction to jsf2Introduction to jsf2
Introduction to jsf2
 
Overview of the AngularJS framework
Overview of the AngularJS framework Overview of the AngularJS framework
Overview of the AngularJS framework
 
CBSE XII Database Concepts And MySQL Presentation
CBSE XII Database Concepts And MySQL PresentationCBSE XII Database Concepts And MySQL Presentation
CBSE XII Database Concepts And MySQL Presentation
 
eCertificate-JAVA-2
eCertificate-JAVA-2eCertificate-JAVA-2
eCertificate-JAVA-2
 

Ähnlich wie JavaServer Pages

6 introduction-php-mvc-cakephp-m6-views-slides
6 introduction-php-mvc-cakephp-m6-views-slides6 introduction-php-mvc-cakephp-m6-views-slides
6 introduction-php-mvc-cakephp-m6-views-slides
MasterCode.vn
 

Ähnlich wie JavaServer Pages (20)

Jsp intro
Jsp introJsp intro
Jsp intro
 
Web&java. jsp
Web&java. jspWeb&java. jsp
Web&java. jsp
 
Web&java. jsp
Web&java. jspWeb&java. jsp
Web&java. jsp
 
Jsp sasidhar
Jsp sasidharJsp sasidhar
Jsp sasidhar
 
Presentation
PresentationPresentation
Presentation
 
Jsp1
Jsp1Jsp1
Jsp1
 
Jsp presentation
Jsp presentationJsp presentation
Jsp presentation
 
JSP.pptx
JSP.pptxJSP.pptx
JSP.pptx
 
[Laptrinh.vn] lap trinh Spring Framework 3
[Laptrinh.vn] lap trinh Spring Framework 3[Laptrinh.vn] lap trinh Spring Framework 3
[Laptrinh.vn] lap trinh Spring Framework 3
 
ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentation
 
React
React React
React
 
6 introduction-php-mvc-cakephp-m6-views-slides
6 introduction-php-mvc-cakephp-m6-views-slides6 introduction-php-mvc-cakephp-m6-views-slides
6 introduction-php-mvc-cakephp-m6-views-slides
 
jsp tutorial
jsp tutorialjsp tutorial
jsp tutorial
 
JSP
JSPJSP
JSP
 
Java script tutorial
Java script tutorialJava script tutorial
Java script tutorial
 
Html JavaScript and CSS
Html JavaScript and CSSHtml JavaScript and CSS
Html JavaScript and CSS
 
Chap4 4 2
Chap4 4 2Chap4 4 2
Chap4 4 2
 
4. jsp
4. jsp4. jsp
4. jsp
 
FYBSC IT Web Programming Unit III Javascript
FYBSC IT Web Programming Unit III JavascriptFYBSC IT Web Programming Unit III Javascript
FYBSC IT Web Programming Unit III Javascript
 
Jsp and jstl
Jsp and jstlJsp and jstl
Jsp and jstl
 

Kürzlich hochgeladen

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Kürzlich hochgeladen (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

JavaServer Pages

  • 1. JavaServer Pages By: Abdalla Mahmoud. Contents JavaServer Pages................................................................................ 1 Contents ........................................................................................... 1 1. Introduction ................................................................................... 3 2. First JSP ........................................................................................ 4 3. Syntax Elements............................................................................. 4 3.1. Comments ............................................................................... 4 3.2. Scriptlets ................................................................................. 5 3.3. Expressions .............................................................................. 5 3.4. Declarations ............................................................................. 6 3.5. Directives................................................................................. 6 4.1. Example................................................................................... 7 4.1.1. JSP .................................................................................... 7 4.1.2. Corresponding Servlet Class .................................................. 8 5. Implicit Variables ............................................................................ 9 6. Hoax Example - Revisited ................................................................ 9 6.1. Process Servlet ........................................................................ 10 6.2. View Servlet ............................................................................ 10 1
  • 2. 2
  • 3. 1. Introduction JavaServer Pages are web components that generate dynamic web content. Like servlets, JSPs process requests from agents and generate responses. However, JSPs are designed to be more close the nature of web pages than language classes. JSPs are compared to servlets as follows: JSPs Servlets They are not java classes. They are dynamic They are java classes. web pages. Include content with embedded java code. Include java code embedded with content. They are more close to presentation logic. They are more close the business logic. They are not compiled. They are compiled and described in the deployment descriptor. They are translated to servlets automatically They are not translated to something else by the application server on deployment. and deployed by themselves as primitive The translation process in transparent to the web components. developer. Here's a programmatic example demonstrating the practical differences between JSPs and servlets: file: index.jsp file: WEB-INF/classes/w/ IndexServlet.java <html> package w ; <head> import javax.servlet.* ; <title>First JSP</title> import javax.servlet.http.* ; </head> import java.io.* ; <body> public class IndexServlet extends HttpServlet { <% String name = public void doGet(HttpServletRequest request.getParameter("user_name") ; request, HttpServletResponse out.print("Welcome " + name) ; response) throws ServletException, %> IOException{ </body> PrintWriter out = </html> response.getWriter() ; out.println("<html>") ; out.println("<head>") ; out.println( "<title>First JSP</title>") ; out.println("</head>") ; 3
  • 4. out.println("<body>") ; String name = request.getParameter( "user_name") ; out.println("Welcome " + name) ; out.println("</body>") ; out.println("</html>") ; } } 2. First JSP Here's an example of a JavaServer Page that generates dynamic output: file: index.jsp <html> <head> <title><% out.print("First JSP") ; %></title> </head> <body> <% String name = request.getParameter("user_name") ; out.print("Welcome " + name) ; %> </body> </html> 3. Syntax Elements JSP primarily enclose page contents, or static parts of the page, with embedded JSP elements of different types of declarations and actions. Here're some syntax elements of the JSP technology. 3.1. Comments Comments can be included in JSPs between <%-- and --%>. See the following example: 4
  • 5. Example: JSP Comment <html> <head> <title>First JSP</title> </head> <body> <%-- Print a welcome message to the user %--> <% String name = request.getParameter("user_name") ; out.print("Welcome " + name) ; %> </body> </html> 3.2. Scriptlets Sciptlets are snippets of java code that generate dynamic content. Scriptlets can be included in JSPs between <% and %>. See the following example: Example: Scriptlets <html> <head> <title>First JSP</title> </head> <body> <%-- Print a welcome message to the user %--> <% String name = request.getParameter("user_name") ; out.print("Welcome " + name) ; %> </body> </html> 3.3. Expressions Expressions are java language expressions that generate values inserted within content. Expressions can be included in JSPs between <%= and %>. See the previous example rewritten using expressions as the following: Example: Expressions <html> 5
  • 6. <head> <title>First JSP</title> </head> <body> <%-- Print a welcome message to the user %--> Welcome <%= request.getParameter("user_name") %> </body> </html> 3.4. Declarations Declarations are any class valid declaration that will be included in the generated servlet. Declarations can be used in other scriptlets and expression elements. Declarations can be included in the JSP between <%! and %>. See the following example: Example: Declarations <%! int count ; public int getVisitorNumber() { return ++count ; } %> <html> <head> <title>Example JSP</title> </head> <body> Welcome, you are visitor number: <%= getVisitorNumber() %> </body> </html> 3.5. Directives Directives provide information about the page to the JSP engine. Directives can be included in JSP pages between <%@ and %>. JSP Directives include: Directive Purpose <%@ include file="header.html" %> include a file within the page. 6
  • 7. <%@ page import="java.io.File" %> import a name used in a declaration. See the following example: Example: Directives <%@ page import="java.io.File" %> <html> <%@ include file="header.html" %> <body> <% File f = new File(request.getParameter("file")) ; //display file content code %> </body> </html> file: header.html <head> <title>First JSP</title> </head> 4. JSP Translation Process As mentioned earlier, JSPs are translated transparently to servlets. Although the translation process is transparent to the developer, knowledge of the translation process helps understanding JSP syntax. Translation process is simple and straightforward: • a _jspService() method is generated to handle all HTTP request methods. • Contents are printed to the output stream in order in _jspService() mehtod. • Comments are ignored. • Scriptlets are embedded within the _jspService() method in order. • Expressions are printed to the output stream in order within _jspService(). • Declarations are written within the servlet's class body. 4.1. Example Here is an example of how a JSP is translated into a servlet in runtime. 4.1.1. JSP example.jsp <%! 7
  • 8. int count ; public int getVisitorNumber() { return ++count ; } %> <html> <head> <title>Example JSP</title> </head> <body> Welcome, you are visitor number: <%= getVisitorNumber() %> </body> </html> 4.1.2. Corresponding Servlet Class Runtime Class package foo ; import javax.servlet.* ; import javax.servlet.http.* ; import java.io.* ; public class ExampleServlet extends HttpServlet { int count ; public int getVisitorNumber() { return ++count ; } public _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //bold are implicit variables generated automatically PrintWriter out = request.getWriter() ; HttpSession session = request.getSession() ; out.println("<html>") ; out.println("<head>") ; out.println("<title>Example JSP</title>") ; out.println("</head>") ; 8
  • 9. out.println("<body>") ; out.print("Welcome, you are visitor number: ") ; out.print(getVisitorNumber()) ; out.println() ; out.println("</body>") ; out.println("</html>") ; } public void goGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { _jspService(request, response) ; } public void goPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { _jspService(request, response) ; } //same for rest HTTP methods methods } 5. Implicit Variables Implicit variables are variables defined by the application server on translating the JSP into the corresponding servlet. Implicit variables can be used by other scriptlets and expression elements. Every implicit variable represent some aspect to the web developer. Here is a list of some implicit variables: Variable Aspect out Response stream. request HTTP request. response HTTP response. session HTTP session object. 6. Hoax Example - Revisited Our target is to develop a web application that allows a user to add two numbers. consist of the following resources: 9
  • 10. • A form page (page.html). • A servlet that process and display the output (ProcessServlet). • A JSP that display the output (viewResult.jsp). The web application will work in the following scenario: the user requests page.html, fill the form, post the data. The data is processed by ProvessServlet, which will forward the request to the viewResult JSP to view the data. Although a trivial example, it's the main concept in separating the controller from the view in web design patterns using JSPs. 6.1. Process Servlet file: WEB-INF/classes/webapp/ProcessServlet.java package webapp ; import javax.servlet.* ; import javax.servlet.http.* ; import java.io.*; public class ProcessServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { float num1 = Float.parseFloat(request.getParameter("num1")) ; float num2 = Float.parseFloat(request.getParameter("num2")) ; float result = num1 + num2 ; //set attribute to be shared with the delegates request.setAttribute("result", reuslt) ; //create a request dispatcher from the request object RequestDispatcher rd = request.getRequestDispatcher("/viewResult.jsp") ; //forward the request passing request and response objects rd.forward(request, response) ; } } 6.2. View Servlet file: viewResult.jsp <html> 10
  • 11. <head> <title>Result by Process Servlet</title> </head> <body> Result = <%= request.getAttribute("result") %> </body> </html> 11