0% found this document useful (0 votes)
27 views14 pages

Chapter 4 Java Serverpage

Uploaded by

mehari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views14 pages

Chapter 4 Java Serverpage

Uploaded by

mehari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Chapter 8: Javaserver pages(JSP)

What is JavaServer Pages?


JavaServer Pages (JSP) is a technology for developing web pages that support dynamic content
which helps developers insert java code in HTML pages by making use of special JSP tags,
most of which start with <% and end with %>.

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.

JSPs are Internally Compiled into Java Servlets

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.

  JSP Scripting Elements

JSP provides the following scripting elements:

 JSP Comment <%-- comments -->


 JSP Expression <%= Java Expression %>
 JSP Scriptlet <% Java Statement(s) %>
 JSP Directive <%@ page|include ... %>

To simplify the access of the HTTP request and response messages, JSP has pre-defined the
following variables:

 request: corresponds to the HTTP request message.


 response: corresponds to the HTTP response message.
 out: corresponds to the HTTP response message’s output stream.

JSP comment : <%- - comments - ->

JSP comments <%-- comments --> are ignored by the JSP engine. For example,

<%-- anything but a closing tag here will be ignored -->

 JSP Expression: <%= Java Expression %>

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:

<p>The square root of 5 is <%= Math.sqrt(5) %></p>

<p>Current time is: <%= new java.util.Date() %></p>

The above JSP expressions will be converted to:

out.write("<p>The square root of 5 is ");


out.print( Math.sqrt(5) );
out.write("</p>");
out.write("<p>Current time is: ");
out.print( new java.util.Date() );

3
out.write("</p>");

You can use the pre-defined variables, such as request, in the expressions. For examples:

<p>You have choose course <%= request.getParameter("course") %></p>


<%= request.getRequestURI() %>
<%= request.getHeader("Host") %>

  JSP Scriptlet <% Java statement(s) %>

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:

String course = request.getParameter("course");


if (course != null && !course.equals(""))) {
out.write("<p>You have choose course ");
out.print( course );
out.write("</p>");
}

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 Directive <%@ page|include ... %>

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.*" %>

<%-- Set the output MIME type -->


<%@ page contentType="image/gif" %>

<%-- Set an information message for getServletInfo() method -->


<%@ page info="Hello-world example" %>

JSP include Directive

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:

<%@ include file="url" %>

For example:

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


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

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>

Hello World! <br/>


<h1>
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
</h1>
<p>
Today's date: <%= (new java.util.Date()) %>
</p>

5
</html>

The Second JSP Example


Create the second jsp web application randomnumber.jsp
1 <html>
2 <head><title>randomnumber JSP</title></head>
3 <body>
4 <%
5 double num = Math.random();
6 if (num > 0.95) {
7 %>
8 <h2>You are lucky!</h2><p>(<%= num %>)</p>
9 <%
10 } else {
11 %>
12 <h2> You can’t win ,Try more </h2><p>(<%= num %>)</p>
13 <%
14 }
15 %>
16 <a href="<%= request.getRequestURI() %>"><h3>Try Again</h3></a>
17 </body>
18 </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.

Behind the Scene

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.

 Revisit Java Servlets

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".

 Third JSP example - Reading HTML Request Parameters

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.

The request.getParameterValues() is used to retrieve all the values of the query


parameter. The values are echoed back using an unordered list.

Page Redirection Example


The Login file will used to read input (password and user name from the user) and call the
validateuser.jsp file to validate the data. If the user name and password are correct it will redirect
to checkbox.jsp page .if the data are empty or incorrect it will redirect to itself(Login.jsp)

//Login.jsp file

<body>

<form method="POST" action="validateuser.jsp">

<p>Enter your name&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input


type=text name="user" size=20></p>

<p>Enter your password&nbsp; <input type="password" name="pass" size=20></p>

<input type="submit" value="Submit" name=B1>

9
</form> </body>

//validateuser.jsp

<body>

<% String name = request.getParameter("user");

String password = request.getParameter("pass");

RequestDispatcher rd;

if(name.equals("")&& password.equals("")){

%>

<h1> User name and password can't be empty </h1>

<%

rd=request.getRequestDispatcher("Login.jsp");

rd.include(request, response);

else if (name.equals("abc") && password.equals("def")) {

rd=request.getRequestDispatcher("checkbox.jsp");

rd.forward(request, response);

else{

%>

<h1> Try to enter correct user name or password </h1>

<% 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>

JSP - Database connection


To start with basic concept, let us create a database called department, table dept1 and create
few records in the table.

Retrieving data from database:

<body>

<%@ page import = "java.sql.*" %>


<%
try{
Connection con; Statement stmt; ResultSet rs;

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>

<table width=100% border=1 cellpadding=10 cellspacing=50>


<tr>
<th>did</th>
<th>dname</th>

</tr>
<%

while (rs.next()) { %>


<tr>

<td><%= rs.getString(1) %></td>


<td><%= rs.getString(2) %></td>

</tr>
<%
}
%>
</table>
<br>

<a href="<%= request.getRequestURI() %>"><h3>Back</h3></a>


<%
rs.close();
stmt.close();
con.close();
}catch(SQLException e){}
%>
</body>

12
Inserting data to database from html form:

<body>
<%@ page import = "java.sql.*" %>

<form method="POST" action="Insertingdatatodatabase.jsp">


<p>Enter Dept ID: <input type="text" name="did" ></p>
<p>Enter Dept Name: <input type="text" name="dname" </p>
<p> <input type="submit" value="Save" ></p>
<p> <input type="reset" value="Clear"></p>
</form>
<%
try{
Connection con; PreparedStatement pst;

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");

pst = con.prepareStatement("insert into dept1 values(?,?)");


pst.setString(1,id);
pst.setString(2,name);

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

You might also like