0% found this document useful (0 votes)
3 views

JSP

Java Server Pages (JSP) technology is an extension of servlets that simplifies web application development by allowing the integration of HTML and Java code. JSP offers advantages such as easier maintenance, faster development, and the ability to create custom tags, making it preferable for applications with less data processing. The document covers JSP fundamentals, scripting elements, implicit objects, directives, actions, and the life cycle of a JSP page.

Uploaded by

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

JSP

Java Server Pages (JSP) technology is an extension of servlets that simplifies web application development by allowing the integration of HTML and Java code. JSP offers advantages such as easier maintenance, faster development, and the ability to create custom tags, making it preferable for applications with less data processing. The document covers JSP fundamentals, scripting elements, implicit objects, directives, actions, and the life cycle of a JSP page.

Uploaded by

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

Java Server

Pages
Topics
 JSP Fundamentals
 JSP Scripting Elements
 JSP Implicit Objects
 JSP Directives
 JSP Actions
 JSP Example (Loan Calculator)
 Servlets & JSPs together
 Tag Libraries
 Deploying and Running a JSP Application
Introduction
JSP technology is used to create web
application just like Servlet technology.
 It can be thought of as an extension to servlet
because it provides more functionality than
servlet such as expression language, jstl etc.
A JSP page consists of HTML tags and JSP tags.
The jsp pages are easier to maintain than
servlet because we can separate designing
and development.
It provides some additional features such as
Expression Language, Custom Tag etc.
Problems with Servlets
Designing in servlet is difficult and slows
down the application.
Writing complex business logic makes the
application difficult to understand.
You need a Java Runtime Environment on
the server to run servlets.
If your application is build on using servlet
technology, it is very difficult for
enhancement and bug fixing.
The Anatomy of a JSP Page

A JSP page is simply a regular web page


with JSP elements
Everything in the page that is not a JSP
element is called template text .
Template text can really be any text: HTML,
WML, XML, or even plain text.
it can be used with any markup language.
Template text is always passed straight
through to the browser.
Comparsion Between Servlet
and JSP
 JSPServletsJSP is a webpage scripting
language that can generate dynamic content.
 Servlets are Java programs that are already
compiled which also creates dynamic web
content.
 JSP run slower compared to Servlet as it takes
compilation time to convert into Java Servlets.
 Servlets run faster compared to JSP.
 JSP is easier to code in JSP than in Java Servlets.
 Its little much code to write here.
 In MVC, jsp act as a view.
 In MVC, servlet act as a controller.
Comparsion Between Servlet
and JSP
JSP are generally preferred when there is
not much processing of data required.
servlets are best for use when there is
more processing and manipulation
involved.
The advantage of JSP programming over
servlets is that we can build custom
tags which can directly call Java beans.
There is no such custom tag facility in
servlets.
Advantage of JSP over
Servlet
Extension to Servlet
Easy to maintain
Fast Development: No need to recompile
and redeploy
Less code than Servlet
Sample JSP Program
<html>
<head><title>Hello
World</title></head>
<body>
<%
out.println("Hello World");
%>
</body>
</html>
Java Server Pages (JSP)
Architecture
 JSPs run in two Receive HTTP Server
Request
phases JSP Container
 Translation Phase Page Compiler Servlet

 Execution Phase JSP Servlet No Parse JSP


Current?
 In translation phase Yes
JSP Servlet
JSP page is compiled Loaded?
Generate JSP
Servlet Source

into a servlet Yes No


Compile JSP
Load Servlet
 called JSP Page Servlet

Implementation
class Generate
JSP Page Servlet

 In execution phase Response

the compliled JSP is


processed Send
Response
Life cycle of a JSP Page
Translation of JSP Page
Compilation of JSP Page
Classloading (class file is loaded by the
classloader)
Instantiation (Object of the Generated Servlet is
created).
Initialization ( jspInit() method is invoked by the
container).
Reqeust processing ( _jspService() method is
invoked by the container).
Destroy ( jspDestroy() method is invoked by the
container).
Java Server Pages (JSP)
Fundamentals
 Java Server Pages are HTML pages
embedded with snippets of Java code.
 It is an inverse of a Java Servlet
 Four different elements are used in
constructing JSPs
 Scripting Elements
 Implicit Objects
 Directives
 Actions
Scripting Elements
Types
 There are three kinds of scripting
elements
 Declarations
 Scriptlets
 Expressions
Declarations
Basics
 Declarations are used to define methods
& instance variables
 Do not produce any output that is sent to
client
 Embedded in <%! and %> delimiters
Example:
<%!
Public void jspDestroy() {
System.out.println(“JSP Destroyed”);
}
Public void jspInit() {
System.out.println(“JSP Loaded”);
}
int myVar = 123;
%>
 The functions and variables defined are
available to the JSP Page as well as to the
servlet in which it is compiled
Declaration Tag
<%! … %>
Allows you to declare page wide variables
and methods.
 <%! int counter = 0; %>
 <%! Vector beanList = new Vector(); %>
 Methods and variables have class scope
 Note, code must end with ; like any java code
Scriptlets
Basics
 Used to embed java code in JSP pages.
 Contents of JSP go into _JSPpageservice()
method
 Code should comply with syntactical and
semantic constuct of java
 Embedded in <% and %> delimiters
Example:
<%
int x = 5;
int y = 7;
int z = x + y;
%>
Scriptlet Tag
<% … %>
Used to include small pieces of Java code

 <html>
 <body>
 <% out.print("welcome to jsp"); %>
 </body>
 </html>
Index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/
>
</form>
</body>
</html>
Welcome.jsp
<html>
<body>
<%
String name=request.getParameter("unam
e");
out.print("welcome "+name);
%>
</form>
</body>
</html>
Expressions
Basics
 Used to write dynamic content back to the
browser.
 JSP expression tag is written to the output stream
of the response.
 So you need not write out.print() to write data. It is
mainly used to print the values of variable or method.
 If the output is an object then the result of calling
toString on the object is output to the browser
 Embedded in <%= and %> delimiters
Example:
 <%=“Fred”+ “ “ + “Flintstone %>
prints “Fred Flintstone” to the browser
 <%=Math.sqrt(100)%>
prints 10 to the browser
Expression Tag
<%= … %>
Accepts any Java expression, evaluates
the expression, converts to a String, and
displays.
<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>
JSP expression tag that prints
current time
<html>
<body>
Current Time: <
%= java.util.Calendar.getInstance().getTim
e() %>
</body>
</html>
Index.jsp
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname"><br/
>
<input type="submit" value="go">
</form>
</body>
</html>
Welcome.jsp
<html>
<body>
<
%= "Welcome "+request.getParameter("un
ame") %>
</body>
</html>
Java Implicit Objects
Scope
 Implicit objects provide access to server
side objects
 e.g. request, response, session etc.
 There are four scopes of the objects
 Page: Objects can only be accessed in the
page where they are referenced
 Request: Objects can be accessed within all
pages that serve the current request.
(Including the pages that are forwarded to
and included in the original jsp page)
 Session: Objects can be accessed within the
JSP pages for which the objects are defined
 Application: Objects can be accessed by all
JSP pages in a given context
Java Implicit Objects
List
 request: Reference to the current request
 response: Response to the request
 session: session associated woth current request
 application: Servlet context to which a page
belongs
 pageContext: Object to access request,
response, session and application associated
with a page
 config: Servlet configuration for the page
 out: Object that writes to the response output
stream
 page: instance of the page implementation class
(this)
 exception: Available with JSP pages which are
error pages
Java Implicit Objects
Example
<html> <p>
<head> Storing a string to the application...<br>
<title>Implicit Objects</title> <% application.setAttribute("name", "Meeraj"); %>
</head> Retrieving the string from application...<br>
<body style="font-family:verdana;font-size:10pt"> <b>Name:</b>
<p> <%= application.getAttribute("name") %>
Using Request parameters...<br> </p>
<b>Name:</b> <%= request.getParameter("name") %> <p>
</p> Storing a string to the page context...<br>
<p> <% pageContext.setAttribute("name", "Meeraj"); %>
<% out.println("This is printed using the out implicit Retrieving the string from page context...</br>
variable"); %>
<b>Name:</b>
</p>
<%= pageContext.getAttribute("name") %>
<p>
</p>
Storing a string to the session...<br>
</body>
<% session.setAttribute("name", "Meeraj"); %>
</html>
Retrieving the string from session...<br>
<b>Name:</b> <%= session.getAttribute("name") %>
</p>
Example Implicit Objects
Deploy & Run
 Save file:
 $TOMCAT_HOME/webapps/jsp/Implicit.jsp
 Access file
 http://localhost:8080/jsp/Implicit.jsp?name=Sanjay
 Results of the execution

Using Request parameters...


Name: sanjay
This is printed using the out implicit variable
Storing a string to the session...
Retrieving the string from session...
Name: Meeraj
Storing a string to the application...
Retrieving the string from application...
Name: Meeraj
Storing a string to the page context...
Retrieving the string from page context...
Name: Meeraj
Directives
Basics & Types
 Messages sent to the JSP container
 Aids the container in page translation
 Used for
 Importing tag libraries
 Import required classes
 Set output buffering options
 Include content from external files
 The jsp specification defines three directives
 Page: provder information about page, such as scripting
language that is used, content type, or buffer size
 Include – used to include the content of external files
 Taglib – used to import custom actions defined in tag
libraries
Page Directives
Basics & Types
 Page directive sets page properties used during
translation
 JSP Page can have any number of directives
 Import directive can only occur once
 Embedded in <%@ and %> delimiters
 Different directives are
 Language: (Default Java) Defines server side scripting
language (e.g. java)
 Extends: Declares the class which the servlet compiled from
JSP needs to extend
 Import: Declares the packages and classes that need to be
imported for using in the java code (comma separated list)
 Session: (Default true) Boolean which says if the session
implicit variable is allowed or not
 Buffer: defines buffer size of the jsp in kilobytes (if set to
none no buffering is done)
Page Directives
Types con’t.
 Different directives are (cont’d.)
 autoFlush:When true the buffer is flushed when max buffer
size is reached (if set to false an exception is thrown when
buffer exceeds the limit)
 isThreadSafe: (default true) If false the compiled servlet
implements SingleThreadModel interface
 Info: String returned by the getServletInfo() of the compiled
servlet
 errorPage: Defines the relative URI of web resource to which
the response should be forwarded in case of an exception
 contentType: (Default text/html) Defines MIME type for the
output response
 isErrorPage: True for JSP pages that are defined as error
pages
 pageEncoding: Defines the character encoding for the jsp
page
Page Directives
Example
<%@
page language=“java”
buffer=“10kb”
autoflush=“true”
errorPage=“/error.jsp”
import=“java.util.*, javax.sql.RowSet”
%>
Include Directive
Basics
 Used to insert template text and JSP code
during the translation phase.
 The content of the included file specified by the
directive is included in the including JSP page
 Example
 <%@ include file=“included.jsp” %>
JSP Actions
Basics & Types
 Processed during the request processing phase.
 As opposed to JSP directives which are processed during
translation
 Standard actions should be supported by J2EE compliant
web servers
 Custom actions can be created using tag libraries
 The different actions are
 Include action
 Forward action
 Param action
 useBean action
 getProperty action
 setProperty action
 plugIn action
JSP Actions
Include
 Include action used for including resources in a JSP
page
 Include directive includes resources in a JSP page at
translation time
 Include action includes response of a resource into the
response of the JSP page
 Same as including resources using RequestDispatcher
interface
 Changes in the included resource reflected while accessing
the page.
 Normally used for including dynamic resources
 Example
 <jsp:include page=“inlcudedPage.jsp”>
 Includes the the output of includedPage.jsp into the page
where this is included.
JSP Actions
Forward
 Forwards the response to other web
specification resources
 Same as forwarding to resources using
RequestDispatcher interface
 Forwarded only when content is not committed
to other web application resources
 Otherwise an IllegalStateException is thrown
 Can be avoided by setting a high buffer size for the
forwarding jsp page
 Example
 <jsp:forward page=“Forwarded.html”>
 Forwards the request to Forwarded.html
JSP Actions
Param
 Used in conjunction with Include & Forward
actions to include additional request
parameters to the included or forwarded
resource
 Example
<jsp:forward page=“Param2.jsp”>
<jsp:param name=“FirstName” value=“Sanjay”>
</jsp:forward>
 This will result in the forwarded resource having an
additional parameter FirstName with a value of
Sanjay
JSP Actions
useBean
 Creates or finds a Java object with the defined scope.
 Object is also available in the current JSP as a scripting variable
 Syntax:
<jsp:useBean id=“name”
scope=“page | request | session | application”
class=“className” type=“typeName” |
bean=“beanName” type=“typeName” |
type=“typeName” />
 At least one of the type and class attributes must be present
 We can’t specify values for bith the class and bean name.
 Example
<jsp:useBean id=“myName” scope=“request”
class=“java.lang.String”>
<% firstName=“Sanjay”; %>
</jsp:useBean>
JSP Actions
get/setProperty
 getProperty is used in conjunction with useBean to get
property values of the bean defined by the useBean action
 Example (getProperty)
 <jsp:getProperty name=“myBean” property=“firstName” />
 Name corresponds to the id value in the useBean
 Property refers to the name of the bean property
 setProperty is used to set bean properties
 Example (setProperty)
 <jsp:setProperty name=“myBean” property=“firstName”
value=“Sanjay”/>
 Sets the name property of myBean to SanjayExample (setProperty)
 <jsp:setProperty name=“myBean” property=“firstName”
param=“fname”/>
 Sets the name property of myBean to the request parameter fname
 <jsp:setProperty name=“myBean” property=“*”>
 Sets property to the corresponding value in request
JSP Actions
plugIn
 Enables the JSP container to render appropriate HTML
(based on the browser type) to:
 Initiate the download of the Java plugin
 Execution of the specified applet or bean
 plugIn standard action allows the applet to be embedded in
a browser neutral fashion
 Example
<jsp: plugin type=“applet” code=“MyApplet.class” codebase=“/”>
<jsp:params>
<jsp:param name=“myParam” value=“122”/>
</jsp:params>
<jsp:fallback><b>Unable to load applet</b></jsp:fallback>
</jsp:plugin>
JSP Comments
There are two types of comments in a JSP
page: server side comments and client side
comments.
The server side comments, or hidden
comments, is visible only on the server side
because it is removed during JSP page
translation.A server side comments is of
the form
<%-- comments --%>
This type of comments can be used for
documentation, such as the author(s), the date,
and the copyright notice of the revision, an
identifier and a description about the JSP page for
web developers.
This type of comments can also be used to
"comment out" some portions of the Java code of
a JSP page.
An alternative way to place a "comment" in JSP is
to use the comment mechanism of the scripting
language. For example:
<% /** this is a comment ... **/ %>
Example
Loan Calculator
Header.jsp
Gets input to compute loan from user  index.jsp
Footer.jsp

Selects the right jsp for calculating loan controller.jsp


Computes loan based Header.jsp Computes loan based


on simple interest
simple.jsp compound.jsp on simple interest
Footer.jsp

error.jsp Calculate loan error.jsp Calculate loan


Handles error if Handles error if
exception is thrown exception is thrown
Loan Calculator
index.jsp
<html> <tr>
<head> <td>Simple:</td>
<title>Include</title> <td><input type="radio" name="type" value="S" /></td>
</head> </tr>
<body style="font-family:verdana;font-size:10pt;">
<tr>
<%@ include file="header.html" %>
<td>Period:</td>
<form action="controller.jsp">
<td><input type="text" name="period"/></td>
<table border="0" style="font-family:verdana;font-
size:10pt;"> </tr>
<tr> </table>
<td>Amount:</td> <input type="submit" value="Calculate"/>
<td><input type="text" name="amount" /> </form>
</tr> <jsp:include page="footer.jsp"/>
<tr>
</body>
<td>Interest in %:</td>
</html>
<td><input type="text" name="interest"/></td>
</tr>
<tr>
<td>Compound:</td>
<td><input type="radio" name="type" value="C"
checked/></td>
</tr>
Loan Calculator
Miscelaneous
controller.jsp error.jsp
<% <%@ page isErrorPage="true" %>

String type = request.getParameter("type"); <html>


<head>
if(type.equals("S")) {
<title>Simple</title>
%>
</head>
<jsp:forward page="/simple.jsp"/>
<body style="font-family:verdana;font-size:10pt;">
<%
<%@ include file="header.html" %>
} else {
<p style="color=#FF0000"><b><%=
%> exception.getMessage() %></b></p>
<jsp:forward page="/compound.jsp"/> <jsp:include page="footer.jsp"/>

<% </body>

} </html>
header.jsp
%>
<h3>Loan Calculator</h3>
footer.jsp
<%= new java.util.Date() %>
Loan Calculator
simple.jsp
<%@ page errorPage="error.jsp" %> <html>
<%! <head>

public double calculate(double amount, double <title>Simple</title>


interest, int period) { </head>
if(amount <= 0) { <body style="font-family:verdana;font-size:10pt;">
throw new IllegalArgumentException("Amount <%@ include file="header.html" %>
should be greater than 0: " + amount); <%
} double amount =
if(interest <= 0) { Double.parseDouble(request.getParameter("amo
unt"));
throw new IllegalArgumentException("Interest double interest =
should be greater than 0: " + interest); Double.parseDouble(request.getParameter("inter
} est"));
int period =
if(period <= 0) {
Integer.parseInt(request.getParameter("period"));
throw new IllegalArgumentException("Period should %>
be greater than 0: " + period);
<b>Pincipal using simple interest:</b>
}
<%= calculate(amount, interest, period) %>
return amount*(1 + period*interest/100);
<br/><br/>
}
<jsp:include page="footer.jsp"/>
%> </body>
</html>
Loan Calculator
compound.jsp
<%@ page errorPage="error.jsp" %> <html>
<%! <head>

public double calculate(double amount, double <title>Compound</title>


interest, int period) { </head>
if(amount <= 0) { <body style="font-family:verdana;font-size:10pt;">
throw new IllegalArgumentException("Amount <%@ include file="header.html" %>
should be greater than 0: " + amount); <%
} double amount =
if(interest <= 0) { Double.parseDouble(request.getParameter("amo
unt"));
throw new IllegalArgumentException("Interest double interest =
should be greater than 0: " + interest); Double.parseDouble(request.getParameter("inte
} rest"));
int period =
if(period <= 0) {
Integer.parseInt(request.getParameter("period"))
throw new IllegalArgumentException("Period should ;
be greater than 0: " + period); %>
} <b>Pincipal using compound interest:</b>
return amount*Math.pow(1 + interest/100, period); <%= calculate(amount, interest, period) %>
} <br/><br/>
%> <jsp:include page="footer.jsp"/>
</body>
</html>
Example
Inventory
Runs the SQL query
for listing inventory ListServlet

Takes the RowSet in the


context and renders it List.jsp

Renders form for new item


Runs SQL query to get a Deletes a record
record from item from the item table
EditServlet New.html DeleteServlet

Takes a RowSet and


renders a form for editing
Edit.jsp CreateServlet
Runs SQL query to
Runs SQL query to create new record
update the data in the
item table after editing UpdateServlet
Inventory
ListServlet
package edu.albany.mis.goel.servlets; public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException {
import javax.servlet.ServletException;
try {
import javax.servlet.ServletConfig;
// Load the driver class
import javax.servlet.http.HttpServlet;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
import javax.servlet.http.HttpServletRequest;
// Define the data source for the driver
import javax.servlet.http.HttpServletResponse;
String sourceURL = "jdbc:odbc:inventoryDB";
import javax.sql.DataSource;
RowSet rs = new CachedRowSet();
import javax.sql.RowSet;
rs.setUrl(sourceURL);
import sun.jdbc.rowset.CachedRowSet;
rs.setCommand("select * from item");
public class ListServlet extends HttpServlet {
rs.execute();
public void init(ServletConfig config) throws
ServletException { req.setAttribute("rs", rs);
super.init(config); getServletContext().getRequestDispatcher("/List.jsp").
} forward(req, res);
public void doPost(HttpServletRequest req, } catch(Exception ex) {
HttpServletResponse res)
throw new ServletException(ex);
throws ServletException {
}
doGet(req, res);
}
}
}
Inventory
EditServlet
package edu.albany.mis.goel.servlets; public void doGet(HttpServletRequest req,
HttpServletResponse res)
import javax.servlet.ServletException; throws ServletException {
import javax.servlet.ServletConfig; try {
import javax.servlet.http.HttpServlet; // Load the driver class
import javax.servlet.http.HttpServletRequest; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
import javax.servlet.http.HttpServletResponse; // Define the data source for the driver
import java.sql.DriverManager; String sourceURL = "jdbc:odbc:inventoryDB";
import javax.sql.DataSource; RowSet rs = new CachedRowSet();
import javax.sql.RowSet;
rs.setUrl(sourceURL);
import sun.jdbc.rowset.CachedRowSet;
rs.setCommand("select * from item where id = ?");
rs.setInt(1, Integer.parseInt(req.getParameter("id")));
public class EditServlet extends HttpServlet {
rs.execute();
public void init(ServletConfig config) throws
ServletException { req.setAttribute("rs", rs);
super.init(config);
} getServletContext().getRequestDispatcher("/Edit.jsp
").forward(req, res);
public void doPost(HttpServletRequest req,
HttpServletResponse res) } catch(Exception ex) {
throws ServletException { throw new ServletException(ex);
doGet(req, res); }
} }
}
Inventory
UpdateServlet
package edu.albany.mis.goel.servlets; // Create a connection through the DriverManager class
con = DriverManager.getConnection(sourceURL);
import javax.servlet.ServletException; System.out.println("Connected Connection");
import javax.servlet.ServletConfig; PreparedStatement stmt= con.prepareStatement
import javax.servlet.http.HttpServlet;
("update item " + "set name = ?, " + "description = ?, " + "price = ?, "
import javax.servlet.http.HttpServletRequest;
+ "stock = ? " + "where id = ?");
import javax.servlet.http.HttpServletResponse;
stmt.setString(1, req.getParameter("name"));
import javax.sql.DataSource;
stmt.setString(2, req.getParameter("description"));
import javax.naming.InitialContext;
stmt.setDouble(3, Double.parseDouble(req.getParameter("price")));
import java.sql.DriverManager;
import java.sql.Connection; stmt.setInt(4, Integer.parseInt(req.getParameter("stock")));
import java.sql.PreparedStatement; stmt.setInt(5, Integer.parseInt(req.getParameter("id")));
import java.sql.ResultSet; stmt.executeUpdate();
public class UpdateServlet extends HttpServlet { stmt.close();
public void init(ServletConfig config) throws ServletException { getServletContext().getRequestDispatcher("/List").
super.init(config); forward(req, res);
} } catch(Exception ex) {
public void doPost(HttpServletRequest req, HttpServletResponse res) throw new ServletException(ex);
throws ServletException {
} finally {
doGet(req, res);
try {
}
if(con != null) {
public void doGet(HttpServletRequest req, HttpServletResponse res)
con.close();
throws ServletException {
}
Connection con = null;
try { } catch(Exception ex) {

// Load the driver class throw new ServletException(ex);


Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); }
// Define the data source for the driver }
String sourceURL = "jdbc:odbc:inventoryDB"; }
}
Inventory
DeleteServlet
package edu.albany.mis.goel.servlets; try {
// Load the driver class
import javax.servlet.ServletException; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
import javax.servlet.ServletConfig; // Define the data source for the driver
import javax.servlet.http.HttpServlet;
String sourceURL = "jdbc:odbc:inventoryDB";
import javax.servlet.http.HttpServletRequest;
// Create a connection through the DriverManager class
import javax.servlet.http.HttpServletResponse;
con = DriverManager.getConnection(sourceURL);
import javax.sql.DataSource;
System.out.println("Connected Connection");
import javax.naming.InitialContext;
import java.sql.Connection; // Create Statement

import java.sql.DriverManager; PreparedStatement stmt =


import java.sql.PreparedStatement; con.prepareStatement("delete from item where id = ?");
import java.sql.ResultSet; stmt.setInt(1, Integer.parseInt(req.getParameter("id")));
public class DeleteServlet extends HttpServlet { stmt.executeUpdate();
public void init(ServletConfig config) throws ServletException { stmt.close();
super.init(config); getServletContext().getRequestDispatcher("/List").
} forward(req, res);
public void doPost(HttpServletRequest req, HttpServletResponse res)
} catch(Exception ex) {
throws ServletException {
throw new ServletException(ex);
doGet(req, res);
} finally {
}
try {
public void doGet(HttpServletRequest req, HttpServletResponse res)
if(con != null) con.close();
throws ServletException {
Connection con = null; } catch(Exception ex) {
throw new ServletException(ex);
}
}
}
Inventory
CreateServlet
package edu.albany.mis.goel.servlets; // Define the data source for the driver
String sourceURL = "jdbc:odbc:inventoryDB";
import javax.servlet.ServletException; // Create a connection through the DriverManager class
import javax.servlet.ServletConfig; con = DriverManager.getConnection(sourceURL);
import javax.servlet.http.HttpServlet;
System.out.println("Connected Connection");
import javax.servlet.http.HttpServletRequest;
PreparedStatement stmt = con.prepareStatement
import javax.servlet.http.HttpServletResponse;
("insert into item " + "(name,description,price,stock) " +
import javax.sql.DataSource;
"values (?, ?, ?, ?)");
import javax.naming.InitialContext;
import java.sql.DriverManager; stmt.setString(1, req.getParameter("name"));

import java.sql.Connection; stmt.setString(2, req.getParameter("description"));


import java.sql.PreparedStatement; stmt.setDouble(3, Double.parseDouble(req.getParameter("price")));
import java.sql.ResultSet; stmt.setInt(4, Integer.parseInt(req.getParameter("stock")));
public class CreateServlet extends HttpServlet { stmt.executeUpdate();
public void init(ServletConfig config) throws ServletException { stmt.close();
super.init(config); getServletContext().getRequestDispatcher("/List").forward(req, res);
}
public void doPost(HttpServletRequest req, HttpServletResponse res) } catch(Exception ex) {
throws ServletException { throw new ServletException(ex);
doGet(req, res); } finally {
} try {
public void doGet(HttpServletRequest req, HttpServletResponse res) if(con != null) con.close();
throws ServletException {
} catch(Exception ex) {
Connection con = null;
throw new ServletException(ex);
try { // Load the driver class
}
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
}
}
Inventory
Edit.jsp
<%@page contentType="text/html"%> <tr>
<jsp:useBean id="rs" scope="request" type="javax.sql.RowSet" /> <td><b>Price:</b></td>
<html> <td>
<head> <input name="price" type="text" value="<%= rs.getString(4) %>"/>
<title>Inventory - Edit</title> </td>
</head> </tr>
<body style="font-family:verdana;font-size:10pt;"> <tr>
<%
<td><b>Stock:</b></td>
if(rs.next()) {
<td>
%>
<input name="stock" type="text" value="<%= rs.getString(5) %>"/>
<form action="Update">
</td>
<input name="id" type="hidden" value="<%= rs.getString(1) %>"/>
</tr>
<table cellpadding="5" style="font-family:verdana;font-size:10pt;">
<tr>
<tr>
<td></td>
<td><b>Name:</b></td>
<td>
<td>
<input type="submit" value="Update"/>
<input name="name" type="text" value="<%= rs.getString(2) %>"/>
</td>
</td>

</tr> </tr>

<tr> </table>
<td><b>Description:</b></td> <%
<td> }
<input name="description" type="text" value="<%= rs.getString(3) %>
%>"/>
</body>
</td>
</html>
</tr>
Inventory
Edit.jsp
<%@page contentType="text/html"%> <tr>
<jsp:useBean id="rs" scope="request" type="javax.sql.RowSet" /> <td><%= rs.getString(2) %></td>
<td><%= rs.getString(3) %></td>

<html> <td><%= rs.getString(4) %></td>


<td><%= rs.getString(5) %></td>
<head>
<td>
<title>Inventory - List</title>
<a href="Delete?id=<%= rs.getString(1) %>">
</head>
Delete
<body style="font-family:verdana;font-size:10pt;">
</a>
<table cellpadding="5" style="font-family:verdana;font-size:10pt;">
</td>
<tr>
<td>
<th>Name</th> <a href="Edit?id=<%= rs.getString(1) %>">
<th>Description</th> Edit
<th>Price</th> </a>
<th>Stock</th> </td>
<th></th> </tr>
<th></th> <%
</tr> }

<% %>
</table>
while(rs.next()) {
<a href="New.html">New Item</a>
%>
</body>
</html>
Inventory
New.html
<html> <tr>
<head> <td></td>
<title>Inventory - Add New Item</title> <td><input type="submit" value="Create"/></td>
</head> </tr>
<body style="font-family:verdana;font-size:10pt;">
</table>
<form action="Create">
<table cellpadding="5" style="font-family:verdana;font-size:10pt;"> </body>
<tr> </html>
<td><b>Name:</b></td>
<td><input name="name" type="text"/></td>
</tr>
<tr>
<td><b>Description:</b></td>
<td><input name="description" type="text"/></td>
</tr>
<tr>
<td><b>Price:</b></td>
<td><input name="price" type="text"/></td>
</tr>
<tr>
<td><b>Stock:</b></td>
<td><input name="stock" type="text"/></td>
</tr>

You might also like