0% found this document useful (0 votes)
75 views9 pages

COMSCPBTech51538rProrPr - JSP PROGRAMS

This document provides information on the life cycle of a JSP page and how it is similar to a servlet. It includes code examples of a simple JSP page that generates dynamic HTML content using scriptlet tags. It also provides examples of how to connect to a database and perform queries from within a JSP page using Java code and scriptlets to output the results. The document compares JSP to servlets, noting that JSP allows embedding Java code within HTML tags, making it easier to manage presentation logic compared to generating raw HTML from within a servlet.

Uploaded by

Vismathi
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)
75 views9 pages

COMSCPBTech51538rProrPr - JSP PROGRAMS

This document provides information on the life cycle of a JSP page and how it is similar to a servlet. It includes code examples of a simple JSP page that generates dynamic HTML content using scriptlet tags. It also provides examples of how to connect to a database and perform queries from within a JSP page using Java code and scriptlets to output the results. The document compares JSP to servlets, noting that JSP allows embedding Java code within HTML tags, making it easier to manage presentation logic compared to generating raw HTML from within a servlet.

Uploaded by

Vismathi
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/ 9

Note : Life Cycle of JSP : Same with Servlet as internally it is a servlet

<html>
<head><title>First JSP</title></head>
<body>
<%
double num = Math.random();
if (num > 0.95) {
%>
<h2>You'll have a luck day!</h2><p>(<%= num %>)</p>
<%
} else {
%>
<h2>Well, life goes on ... </h2><p>(<%= num %>)</p>
<%
}
%>
<a href="<%= request.getRequestURL() %>"><h3>Try Again</h3></a>
</body>
</html>

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

public class ...Servlet extends HttpServlet {

// Runs when the servlet is loaded onto the server.


public void init() {
......
}

// Runs on a thread whenever there is HTTP GET request


// Take 2 arguments, corresponding to HTTP request and response
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {

// Set the MIME type for the response message


response.setContentType("text/html");
// Write to network
PrintWriter out = response.getWriter();

// Your servlet's logic here


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

// Runs as a thread whenever there is HTTP POST request


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// do the same thing as HTTP GET request
doGet(request, response);
}

// Runs when the servlet is unloaded from the server.


public void destroy() {
......
}

// Other instance variables and methods


}
Java servlet produces HTML codes by calling out.print() methods. You have to hardcode all the
HTML tags 

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

<html>
<head>
<title>Echoing HTML Request Parameters</title>
</head>
<body>
<h3>Choose an author:</h3>
<form method="get">
<input type="checkbox" name="author" value="Tan Ah Teck">Tan
<input type="checkbox" name="author" value="Mohd Ali">Ali
<input type="checkbox" name="author" value="Kumar">Kumar
<input type="submit" value="Query">
</form>
<%
String[] authors = request.getParameterValues("author");
if (authors != null) {
%>
<h3>You have selected author(s):</h3>
<ul>
<%
for (int i = 0; i < authors.length; ++i) {
%>
<li><%= authors[i] %></li>
<%
}
%>
</ul>
<a href="<%= request.getRequestURI() %>">BACK</a>
<%
}
%>
</body>
</html>
Explanations
1. This HTML page has a form with 3 checkboxes. The "name=value" pair of the checkboxes is
"author=so_and_so". No "action" attribute is specified, the default " action" is the current
page (i.e. the query will be sent to the same page).
2. The JSP scriptlet checks if the query parameter " author" exists to decide whether to
dynamically generate the enclosed codes. "author" parameter is absent when the page is first
requested. Once the client fills in the form (by checking the boxes) and submits the form,
"author" will be present in the HTTP request, and submitted to the same page for processing
(with the default <form>’s "action" attribute).
3. The request.getParameterValues() is used to retrieve all the values of the query
parameter. The values are echoed back using an unordered list.
JSP Scripting Elements
4. <%
5. String author = request.getParameter("author");
6. if (author != null && !author.equals(""))) {
7. %>
8. <p>You have choose author <%= author %></p>
9. <%
10. }
11. %>

JSP page Directive
<%-- import package java.sql.* -->
<%@ 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
<%@ include file="url" %>
<%@ include file="header.html" %>
......
<%@ include file="footer.html" %>

JSP Database Example


Database: ebookshop
Table: books
+-------+----------------------------+---------------+---------+-------+
| id | title | author | price | qty |
| (INT) | (VARCHAR(50)) | (VARCHAR(50)) | (FLOAT) | (INT) |
+-------+----------------------------+---------------+---------+-------+
| 1001 | Java for dummies | Tan Ah Teck | 11.11 | 11 |
| 1002 | More Java for dummies | Tan Ah Teck | 22.22 | 22 |
| 1003 | More Java for more dummies | Mohammad Ali | 33.33 | 33 |
| 1004 | A Cup of Java | Kumar | 44.44 | 44 |
| 1005 | A Teaspoon of Java | Kevin Jones | 55.55 | 55 |
+-------+----------------------------+---------------+---------+-------+
query.jsp
<html>
<head>
<title>Book Query</title>
</head>
<body>
<h1>Another E-Bookstore</h1>
<h3>Choose Author(s):</h3>
<form method="get">
<input type="checkbox" name="author" value="Tan Ah Teck">Tan
<input type="checkbox" name="author" value="Mohd Ali">Ali
<input type="checkbox" name="author" value="Kumar">Kumar
<input type="submit" value="Query">
</form>
<%
String[] authors = request.getParameterValues("author");
if (authors != null) {
%>
<%@ page import = "java.sql.*" %>
<%
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:8888/ebookshop", "myuser", "xxxx"); // <==
Check!
// Connection conn =
// DriverManager.getConnection("jdbc:odbc:eshopODBC"); // Access
Statement stmt = conn.createStatement();

String sqlStr = "SELECT * FROM books WHERE author IN (";


sqlStr += "'" + authors[0] + "'"; // First author
for (int i = 1; i < authors.length; ++i) {
sqlStr += ", '" + authors[i] + "'"; // Subsequent authors need a
leading commas
}
sqlStr += ") AND qty > 0 ORDER BY author ASC, title ASC";

// for debugging
System.out.println("Query statement is " + sqlStr);
ResultSet rset = stmt.executeQuery(sqlStr);
%>
<hr>
<form method="get" action="order.jsp">
<table border=1 cellpadding=5>
<tr>
<th>Order</th>
<th>Author</th>
<th>Title</th>
<th>Price</th>
<th>Qty</th>
</tr>
<%
while (rset.next()) {
int id = rset.getInt("id");
%>
<tr>
<td><input type="checkbox" name="id" value="<%= id %>"></td>
<td><%= rset.getString("author") %></td>
<td><%= rset.getString("title") %></td>
<td>$<%= rset.getInt("price") %></td>
<td><%= rset.getInt("qty") %></td>
</tr>
<%
}
%>
</table>
<br>
<input type="submit" value="Order">
<input type="reset" value="Clear">
</form>
<a href="<%= request.getRequestURI() %>"><h3>Back</h3></a>
<%
rset.close();
stmt.close();
conn.close();
}
%>
</body>
</html>
xplanations
1. This HTML page has a form with 3 checkboxes. The "name=value" pair of the checkboxes is
"author=so_and_so". No "action" attribute is specified, hence, it defaulted to current page.
The processing script is contained in the same page.
2. The method request.getParameter("author") is used to check if the query parameter
"author" exists.  "author" is absent during the first reference of the page.
3. The <%@ page .. %> contains a JSP "page" directive to import the java.sql package.
4. The scriptlet performs the database query operation. The steps are:
1. Establish a database connection via a java.sql.Connection object;
2. Allocate a java.sql.Statement object under the Connection;
3. Prepare a SQL SELECT string;
4. Execute the SQL SELECT using executeQuery() method. The result of query is
returned in an object of java.sql.ResultSet;
5. Process the ResultSet row by row via ResultSet.next();
6. Free resources and close the Connection.
b. The query result is tabulated in a HTML table. Note the mixing of HTML and Java in
producing the table.
Notice that JSP carries out the presentation much better and neater than servlet. The presentation
can be changed easily with JSP. The JSP pages can be created and modified using a WYSIWYG web
authoring tool and reload to see the effect on the presentation.  Whereas, in the case of servlet, you
have to explicitly code all the HTML tags inside the servlet program and re-compile the program.
Ordering - "order.jsp"
<html>
<head>
<title>Order Book</title>
</head>

<body>
<h1>Another E-Bookstore</h1>
<h2>Thank you for ordering...</h2>

<%
String[] ids = request.getParameterValues("id");
if (ids != null) {
%>
<%@ page import = "java.sql.*" %>
<%
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:8888/ebookshop", "myuser", "xxxx"); // <==
Check!
// Connection conn =
// DriverManager.getConnection("jdbc:odbc:eshopODBC"); // Access
Statement stmt = conn.createStatement();
String sqlStr;
int recordUpdated;
ResultSet rset;
%>
<table border=1 cellpadding=3 cellspacing=0>
<tr>
<th>Author</th>
<th>Title</th>
<th>Price</th>
<th>Qty In Stock</th>
</tr>
<%
for (int i = 0; i < ids.length; ++i) {
// Subtract the QtyAvailable by one
sqlStr = "UPDATE books SET qty = qty - 1 WHERE id = " + ids[i];
recordUpdated = stmt.executeUpdate(sqlStr);
// carry out a query to confirm
sqlStr = "SELECT * FROM books WHERE id =" + ids[i];
rset = stmt.executeQuery(sqlStr);
while (rset.next()) {
%>
<tr>
<td><%= rset.getString("author") %></td>
<td><%= rset.getString("title") %></td>
<td>$<%= rset.getInt("price") %></td>
<td><%= rset.getInt("qty") %></td>
</tr>
<% }
rset.close();
}
stmt.close();
conn.close();
}
%>
</table>
<a href="query.jsp"><h3>BACK</h3></a>
</body>
</html>

Page Redirection :

<jsp:include> or <Jsp:forward>
Jsp with Servlet:

Handling Error:

MVC Model and (JSP:UseBean> tag

Other Design Pattern

JSTL

You might also like