Handout 34 Web Design & Development
CS-506
Lecture 34
JavaServer Pages As we concluded in our discussion on JSP, JSP is a text based document capable of returning either static or dynamic content to a client’s browser. Static content and dynamic content can be intermixed. The examples of static content are HTML, XML & Text etc. Java code, displaying properties of JavaBeans and invoking business logic defined in custom tags are all examples of dynamic content.
First run of a JSP Figure below shows what phases a JSP passed through before displaying result.
The web browser makes a request to JSP source code. This code is bifurcated into HTML and java code by the JSP parser. The java source code is compiled by the Java compiler resulting in producing a servlet equivalent code of a JSP. The servlet code is intermixed with HTML and displayed to the user. It is important to note that a JSP only passes through all these phases when it is invoked for the first time or when the changes have been made to JSP. Any later call to JSP does not undergo of compilation phase.
Benefits of JSP Convenient
We already know java and HTML. So nothing new to be learned to work with JSP.
Like servlets (as seen, ultimately a JSP gets converted into a servlet), provides an extensive infrastructure for - Tracking sessions - Reading and sending HTML headers - Parsing and decoding HTML form data
- 424 -
Handout 34 Web Design & Development
CS-506
Efficient Every request for a JSP is handled by a simple JSP java thread as JSP gets converted into a servlet. Hence, the time to execute a JSP document is not dominated by starting a process. Portable Like Servlets, JSP is also a specification and follows a well standardized API. The JVM which is used to execute a JSP file is supported on many architectures and operating systems. Inexpensive There are number of free or inexpensive Web Servers that are good for commercial quality websites.
JSP vs. Servlet Let’s compare JSP and Servlet technology by taking an example that simply plays current date. First have a look on JSP that is displaying a current date. This page more looks like a HTML page except of two strangely written lines of codes. Also there are no signs of doGet(), doPost(). <%@ page import=“java.util.*” %>
Current Date is:<%= new Date()%>
- 425 -
Handout 34 Web Design & Development
CS-506
Now, compare the JSP code above with the Servlet code given below that is also displaying the current date. //File: SearchPersonServlet.java import import import import
java.io.*; java.net.*; javax.servlet.*; javax.servlet.http.*;
import java.util.*; public class SearchPersonServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println( “” + “” + “” + “Current Date is:“ + new Date() + “
” + “” + “” );
}
out.close();
// Handles the HTTP GET method. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } // Handles the HTTP POST method. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); }
}
Clearly, a lot of code is needed to be written in the case of servlet example to perform a basic job.
- 426 -
Handout 34 Web Design & Development
CS-506
JSP Ingredients Besides HTML, a JSP may contain the following elements.
Directive Elements –
Provides global control of JSP ……..……………..
<%@
%>
Scripting Elements –
JSP comments ……………………………………...
<%--
--%>
–
declarations ……………………………………... • Used to declare instance variables & methods
<%!
%>
–
expressions ……………………………………... • A java code fragment which returns String
<%=
%>
–
scriptlets ……………………………………... • Blocks of java code
<%
%>
<jsp: .….
/>
Action Elements –
Special JSP tags ……..……………………………..
We’ll discuss in detail all the ingredients of JSP. This handout will cover only scripting elements, remaining ones will be discussed in next handouts.
Scripting Elements Comments Comments are ignored by JSP-to-servlet translator. Two types of comments are possibly used in JSP. –
HTML comment: These comments are shown in browser, means on taking view source of the web page; these sorts of comments can be read. Format of HTML comments is like to:
–
JSP comment: These comments are not displayed in browser and have format like: <%-- comment text --%>
- 427 -
Handout 34 Web Design & Development
CS-506
Expressions The format of writing a Java expression is: <%= Java expression %> These expressions are evaluated, after converted to strings placed into HTML page at the place it occurred in JSP page Examples of writing Expressions are: –
Time: <%= new java.util.Date() %>
will print current data & time after converting it to String
–
Welcome: <%= request.getParameter(“name”)%>
will print the name attribute
Scriptlets The format of writing a scriptlet is: <%= Java code %> After opening up the scriptlet tag, any kind of java code can be written inside it. This code is inserted verbatim into corresponding servlet. Example of writing a scriptlet is: –
<% String n = request.getParameter(“name”); out.println(“welcome ” + n); %> The above scriptlet reads the name attribute and prints it after appending “welcome”
- 428 -
Handout 34 Web Design & Development
CS-506
Declarations The format of writing a declaration tag is: <%! Java code %> This tag is used to declare variables and methods at class level. The code written inside this tag is inserted verbatim into servlet’s class definition. Example of declaring a class level (attribute) variable is: –
<%! private int someField = 5; %> %>
Example of declaring a class level method is: –
<%! public void someMethod ( …… ) { ……………. } %>
Code Example: Using scripting elements The next example code consists on two JSP pages namely first.jsp and second.jsp. The user will enter two numbers on the first.jsp and after pressing the calculate sum button, able to see the sum of entered numbers on second.jsp first.jsp This page only displays the two text fields to enter numbers along with a button. Enter two numbers to see their sum
- 429 -
Handout 34 Web Design & Development
CS-506
second.jsp This page retrieves the values posted by first.jsp. After converting the numbers into integers, displays their sum. <%-- Declaration--%> <%! // declaring a variable to store sum int res;
%>
// method helps in calculating the sum public int sum(int op1, int op2) { return op1 + op2; }
<%-- Scripltet--%> <% String op1 = request.getParameter("num1"); String op2 = request.getParameter("num2"); int firstNum = Integer.parseInt(op1); int secondNum = Integer.parseInt(op2);
%>
// calling method sum(), declared above in declartion tag res = sum(firstNum, secondNum);
<%-- expression used to display sum --%> Sum is: <%=res%>
- 430 -
Handout 34 Web Design & Development
CS-506
Writing JSP scripting Elements in XML Now days, the preferred way for composing a JSP pages is using XML. Although writing JSP pages in old style is still heavily used as we had shown you in the last example. Equivalent XML tags for writing scripting elements are given below:
Comments:
Declaration: <jsp:declartion>
Expression: <jsp:expression>
Scriptlet:
No equivalent tag is defined
<jsp:scriptlet>
It’s important to note that every opening tag also have a closing tag too. The second.jsp of last example is given below in XML style. <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0"> <jsp:directive.page contentType="text/xml;charset=UTF-8"/> <jsp:element name="text"> <jsp:body> <jsp:declaration> int res; public int sum(int op1, int op2) { return op1 + op2; } <jsp:scriptlet> String op1 = request.getParameter("num1"); String op2 = request.getParameter("num2"); int firstNum = Integer.parseInt(op1); int secondNum = Integer.parseInt(op2); res = sum(firstNum, secondNum); - 431 -
Handout 34 Web Design & Development
<jsp:text> Sum is: <jsp:expression> res
- 432 -
CS-506
Handout 34 Web Design & Development
References:
- 433 -
Java A Lab Course by Umair Javed
Core Servlets and JSP by Marty Hall
CS-506