Chapter 4 Java Serverpage
Chapter 4 Java Serverpage
A JavaServer Pages component is a type of Java servlet that is designed to fulfill the role of a
user interface for a Java web application. Web developers write JSPs as text files that combine
HTML elements, and embedded JSP actions and commands.
Using JSP, you can collect input from users through web page forms, present records from a
database or another source, and create web pages dynamically.
JSP tags can be used for a variety of purposes, such as retrieving information from a database or
registering user preferences, accessing JavaBeans components, passing control between pages
and sharing information between requests, pages etc.
Following diagram shows the position of JSP container and JSP files in a Web Application.
1
JSP Processing:
The following steps explain how the web server creates the web page using JSP:
As with a normal page, your browser sends an HTTP request to the web server.
The web server recognizes that the HTTP request is for a JSP page and forwards it to a
JSP engine. This is done by using the URL or JSP page which ends with .jsp instead of
.html.
The JSP engine loads the JSP page from disk and converts it into a servlet content. This
conversion is very simple in which all template text is converted to println( ) statements
and all JSP elements are converted to Java code that implements the corresponding
dynamic behavior of the page.
The JSP engine compiles the servlet into an executable class and forwards the original
request to a servlet engine.
A part of the web server called the servlet engine loads the Servlet class and executes it.
During execution, the servlet produces an output in HTML format, which the servlet
engine passes to the web server inside an HTTP response.
The web server forwards the HTTP response to your browser in terms of static HTML
content.
Finally web browser handles the dynamically generated HTML page inside the HTTP
response exactly as if it were a static page.
That is to say, anything that can be done using JSPs can also be accomplished using Java
servlets. However, it is important to note that servlets and JSPs are complementary technologies,
NOT replacement of each other. Servlet can be viewed as "HTML inside Java", which is better
for implementing business logic - as it is Java dominant. JSP, on the other hand, is "Java inside
HTML", which is superior for creating presentation - as it is HTML dominant.
2
Apache Tomcat Server
JSPs, like servlets, are server-side programs run inside a HTTP server. To support JSP/servlet, a
Java-capable HTTP server is required. Tomcat Server (@ http://tomcat.apache.org) is the official
reference implementation (RI) for Java servlet and JSP, provided free by Apache (@
http://www.apache.org) - an open-source software foundation.
To simplify the access of the HTTP request and response messages, JSP has pre-defined the
following variables:
JSP comments <%-- comments --> are ignored by the JSP engine. For example,
JSP Expression can be used to insert a single Java expression directly into the response
message. This expression will be placed inside a out.print() method. Hence, the expression
will be evaluated and printed out as part of the response message. Any valid Java expression can
be used. There is no semi-colon at the end of the expression. For examples:
3
out.write("</p>");
You can use the pre-defined variables, such as request, in the expressions. For examples:
JSP scriptlets allow you to do more complex operations than inserting a single Java expression
(with the JSP expression). JSP scriptlets let you insert an arbitrary sequence of valid Java
statement(s) into the service() method of the converted servlet. All the Java statements in a
scriptlet are to be terminated with a semi-colon. For example:
<%
String course = request.getParameter("course");
if (course != null && !course.equals(""))) {
%>
<p>You have choose course <%= course %></p>
<%
}
%>
In the converted servlet, the above will be inserted into the service() method as follows:
Notice that the Java codes inside a scriptlet are inserted exactly as they are written, and used as
the programming logic. The HTML codes are passed to an out.write() method and written out
as part of the response message.
JSP directives provide instructions to the JSP engine. The syntax of the JSP directive is:
<%@ directive_name
attribute1="value1"
attribute2="value2"
......
attributeN="valueN" %>
4
JSP page Directive
The "page" directive lets you import classes and customize the page properties. For examples,
<%-- import package java.sql.* is similar to the next page directive code -->
<%@ page import="java.sql.*" %>
The "include" directive lets you include another file(s) at the time when the JSP page is
compiled into a servlet. You can include any JSP files, or static HTML files. You can use
include directive to include navigation bar, copyright statement, logo, etc. on every JSP
pages. The syntax is:
For example:
The first jsp example: "Java inside HTML" Let's begin with a simple JSP example.
Create a web application project called JSPProject and create jsp file and call its name
myfirstjsp.jsp
<title>JSP Page</title>
5
</html>
It is important to note that the client is not able to "view" the original JSP script (otherwise, you
may have security exposure), but merely the result generated by the script.
Explanations
1. A JSP script is a regular HTML page containing Java programs. Recall that JSP is "Java
inside HTML" (whereas servlet is "HTML inside Java"). The Java statements are
enclosed by <% ... %> (called JSP scriptlet) or <%= ... %> (called JSP expression).
2. JSP Scriptlet <% ... %> is used to include Java statements.
3. JSP Expression <%= ... %> is used to evaluate a single Java expression and display its
result.
4. The method request.getRequestURI() is used to retrieve the URL of the current page.
This is used in the anchor tag <a> for refreshing the page to obtain another random
number.
When a JSP is first accessed, Tomcat converts the JSP into a servlet; compile the servlet, and
execute the servlet. Check out the generated servlet for "first.jsp", and study the JSP-to-
servlet conversion.
The relevant part of the generated servlet is extracted as follows (with some simplifications):
1 out.write("<html>\r\n ");
2 double num = Math.random();
3 if (num > 0.95) {
6
4 out.write("<h2>You are lucky!");
5 out.write("</h2><p>(");
6 out.print( num );
7 out.write(")</p>\r\n");
8 } else {
9 out.write("\r\n ");
10 out.write("<h2>You can’t win ,Try more ");
11 out.write("</h2><p>(");
12 out.print( num );
13 out.write(")</p>\r\n ");
14 }
15 out.write("<a href=\"");
16 out.print( request.getRequestURI() );
17 out.write("\">");
18 out.write("<h3>Try Again</h3></a>\r\n");
19 out.write("</html>\r\n");
Explanation
1. The HTML statements are written out as part of the response via out.write(), as "it is".
2. The JSP scriptlets <% ... %> are kept, as "it is", in the converted servlet as the program
logic.
3. The JSP expressions <%= ... %> are placed inside a out.print(). Hence, the
expression will be evaluated, and the result of the evaluation written out as part of the
response message.
Compare the JSP script and the internally generated servlet, you shall understand that servlet is
"HTML inside Java", whereas JSP is "Java inside HTML".
Subsequent accesses to the same JSP will be much faster, because they will be re-directed to the
converted and compiled servlet directly (no JSP-to-servlet conversion and servlet compilation
needed again), unless the JSP has been modified.
A typical Java servlet (as shown below) contains three kinds of methods: init(), destroy(),
and one or more service() methods such as doGet() and doPost(). init() runs when the
servlet is loaded. destroy() runs when the servlet is unloaded. service() runs once per HTTP
request. The service() methods takes two arguments: request and response, corresponding
to the HTTP request and response messages respectively. A PrintWriter called out is created
for writing out the response to the network.
1 import java.io.*;
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4
5 public class ...Servlet extends HttpServlet {
6
7 // Runs when the servlet is loaded onto the server.
8 public void init() {
7
......
}
9
10
11 // Runs on a thread whenever there is HTTP GET request
12 // Take 2 arguments, corresponding to HTTP request and response
13 public void doGet(HttpServletRequest request, HttpServletResponse
14 response)
15 throws IOException, ServletException {
16
17 // Set the MIME type for the response message
18 response.setContentType("text/html");
19 // Write to network
20 PrintWriter out = response.getWriter();
21
22 // Your servlet's logic here
23 out.println("<html>");
24 out.println( ...... );
25 out.println("</html>");
26 }
27
28 // Runs as a thread whenever there is HTTP POST request
29 public void doPost(HttpServletRequest request, HttpServletResponse
30 response)
31 throws IOException, ServletException {
32 // do the same thing as HTTP GET request
33 doGet(request, response);
34 }
35
36 // Runs when the servlet is unloaded from the server.
37 public void destroy() {
38 ......
39 }
40
41
// Other instance variables and methods
}
Java servlet produces HTML codes by calling out.print() methods. You have to hardcode all
the HTML tags (and cannot use any WYSIWYG web authoring tools). Any change to the web
page's presentation (such as background color and font size) requires re-coding and re-
compilation of servlet program. Servlet, in a nutshell, is "HTML inside Java", whereas JSP is
"Java inside HTML".
Enter the following JSP script and save as "checkbox.jsp" in your Jspproject directory.
1 <html>
2 <head>
3 <title>Reading HTML Request Parameters</title>
4 </head>
5 <body>
6 <h3>Choose course(s):</h3>
7 <form method="get">
8
8 <input type="checkbox" name="course" value="OOP">OOP
9 <input type="checkbox" name="course" value="C++">C++
10 <input type="checkbox" name="course" value="PHP">PHP
11 <input type="submit" value="select">
12 </form>
13
14 <%
15 String[] arr = request.getParameterValues("course");
16 if (arr != null) {
17 %>
18 <h3>You have selected cours(s):</h3>
19 <ul>
20 <%
21 for (int i = 0; i < arr.length; ++i) {
22 %>
23 <li><%= arr[i] %></li>
24 <%
25 }
26 %>
27 </ul>
28 <a href="<%= request.getRequestURI() %>">BACK</a> //refresh or reload page
29 <%
30 }
31 %>
32 </body>
33 </html>
Browse the JSP page created and study the generated servlet.
//Login.jsp file
<body>
9
</form> </body>
//validateuser.jsp
<body>
RequestDispatcher rd;
if(name.equals("")&& password.equals("")){
%>
<%
rd=request.getRequestDispatcher("Login.jsp");
rd.include(request, response);
rd=request.getRequestDispatcher("checkbox.jsp");
rd.forward(request, response);
else{
%>
<% rd=request.getRequestDispatcher("Login.jsp");
rd.include(request, response);
} %>
</body>
10
Including jsp or html file and creating link on index.jsp
Rename index file as Home.jsp, include myfirstjsp.jsp at the top and randomnumber.jsp at the bottom
and create a link for the jsp files checkbox.jsp and randomnumber.jsp, make any home page design
</head>
<%@include file="myfirstjsp.jsp" %> <%--redirect to myfirstjsp.jsp --%>
<body bgcolor="pink">
<table >
<tr>
<td> <a href="checkbox.jsp"><h3>checkbox</h3></a></td>
<td > <a href="randomnumber.jsp"><h3>Randomnumber</h3></a></td>
</tr>
<tr>
<td> <a href="checkbox.jsp"> <h3>checkbox</h3></a></td>
</tr>
<tr>
<td > <a href="randomnumber.jsp"> <h3>Randomnumber</h3></a></td>
</tr>
</table>
<%@include file="randomnumber.jsp" %> <%--redirect to randomnumber.jsp --%>
</body>
</html>
<body>
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "department",
"department");
stmt=con.createStatement();
11
String sql = "select * from dept1 ";
rs = stmt.executeQuery(sql);
%>
<hr>
</tr>
<%
</tr>
<%
}
%>
</table>
<br>
12
Inserting data to database from html form:
<body>
<%@ page import = "java.sql.*" %>
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "department",
"department");
String id = request.getParameter("did");
String name = request.getParameter("dname");
int i = pst.executeUpdate();
if(i!=0){
%>
<h1>Record has been inserted </h1>
<%
}
else{
%>
<h1>failed to insert the data</h1>
<% }
pst.close();
con.close();
}catch(SQLException e){}
%>
</body>
13
14