Title: Web Application and JavaBeans
1Web Applicationand JavaBeans
2Saving Data Between Request
- When a variable is to be used in multiple pages
(e.g., username), we need to find a method to
store the variable and pass it around - One method is to store the value in a hidden form
variable and preserved the variable in all forms - However, it is insecure because
- One can directly input the variables and values
in the URL and ruins the JSP/Servlet - In a worse case, one can view the HTML source to
find out the values of the hidden variables it
will be dangerous if the hidden item is a bank
account or credit card number - Also, if you are using GET method to send the
form, all variable values are shown in the URL
3Using session object
- A better alternative is using session object
- HTTP is not a session-oriented protocol
- There is no permanent connection between a
browser and a Web server the server has no idea
what is happening on the browser - The Web server will not associate the new
connection to any of its previous connection - JSP and Servlet can store the session information
on the server through a single key that the
client remembers. - HttpSession objects can only be used in
HttpServlets only. - Setting/getting attributes from an invalidated or
timed-out session will lead to IllegalStateExcepti
on
4How Sessions Work
5How Sessions Work
- When the servlet container creates a session, it
sends a session key to the browser in the form of
a cookie - A session cookie is usually not saved to disk
because it is a normally short-lived and session
will be terminated after the browser shuts down - When the browser asks the server for a page
again, the server looks at its session cookie and
find the session corresponding to the browsers
session key - The Servlet container will also check its
sessions and get rid of those that have not been
used in a long time - It is to clear up the sessions which have been
gone (due to removal of session cookie in the
browser)
6Forcing a New Session
- Suppose a user wants to re-login and clear up the
things he have placed in the shopping cart - You need to start over with a clean state
- If the things are not cleared up, one who have
forgotten to logout may have a risk that other
can see what he have bought. - The getSession method in the request object
enables you to control the creation of new
session. - request.getSession(false) will return you the old
session and will not create one if none existed - request.getSession(true) will return the current
session to you. If no session is currently
existing, it will create a new session and return
to you.
7Force a New Session (Code)
- // Get the old session// but dont create a new
one even none existHttpSession oldSess
request.getSession(false) - if (oldSess ! null) // exists an old session
- oldSess.invalidate() // forced termination
-
- // Create a fresh new session session
request.getSession(true) - The above program segment will force a new
session to be created for the user
8Session Termination
- A session can be terminated in two ways
- Force the termination by calling invalidate()
- Servlet engine times the session out
- You may need to do some cleanup of session data
- For example, you may have a database connection
stored in the session. - Though it will be eliminated by Javas garbage
collector eventually, you should not keep the
large object that you do not need
9Handling Sessions without Cookies
- JSP and servlet sessions rely on HTTPs cookie
mechanism to preserve the session identifier
between request - However, cookies have been abused and many Web
users now disable cookies within their browser - Servlet API provides a way for you to insert a
session ID into a URL so that sessions can be
handled without using cookies - public String encodeURL(String url)
- public String encodeRedirectURL(String url)
10Example on Session without Using Cookies
- lthtmlgt ltbodygt
- lth1gtURL Rewriting Demolt/h1gt
- lt // See if the session already contains the
name. - String name (String) session.getAttribute("name
") - if (name ! null) // session exists, show the
name - out.println("Hello, "name"!")
- gt
- lta href"ltresponse.encodeURL("RewriteDemo2.jsp
")gt"gt - Click here to continuelt/agt
- lt
- else if (request.getParameter("name") ! null)
- // get name from input request
- session.setAttribute("name", request.getParamete
r("name")) - response.sendRedirect(response.encodeRedirectURL
( "RewriteDemo2.jsp")) - else
- gt
- ltform action"ltresponse.encodeURL("RewriteDemo.j
sp")gt"gt - Please enter your name ltinput typetext
name"name"gtltpgt - ltinput type"submit" value"Login!"gt
11Redirect Page for the Example
- lthtmlgt
- ltbodygt
- lth1gt
- Hello ltsession.getAttribute("name")gt!
- lt/h1gt
- ltpgt See, I still remembered your name.
- lt/bodygt
- lthtmlgt
12Application Object
- Storing attributes to application object is
similar to storing the value in a static variable - However, a servlet container knows to which web
application a page belongs - An identical JSP may deploy to different web
application at the same time - When you use static variables, the value change
may influence other web applications - If you use application object to store the
values, the change will only influence the web
application you are working on
13JavaBeans
- A JavaBean is a reusable software component that
is written in the Java programming language - Usually, we define the following three
characteristics for a JavaBean - A JavaBean must be a public class
- It must have a constructor with no argument
- We must use the provided get/set methods to
access the data in the JavaBean - Using JavaBeans can encapsulate the logic into a
Java class and make use of it inside the JSP
14Using JavaBeans in JSP
- Though we can directly create a JavaBean object
inside a declaration/scriplet/expression, it will
cluttered our code - Instead, we will use JSP action tag to apply the
bean - ltjspuseBeangt create Javabeans
- ltjspgetPropertygt and ltjspsetPropertygt allows
you to manipulate bean properties (the attribute
of the class)
15ltjspuseBeangt tag
- Syntax
- ltjspuseBean id"name" scope"___"
class"myPackage.myClass" /gt - The JSP engine will first search for an existing
bean with the same ID - The location to find the bean depends on the
scope - scope can be one of the following value page,
request, session or application - The default scope (if none is specified) is page
- If none is found, JSP engine will create a new
instance of the specified class
16Interaction between JavaBeans and JSP Scriptlets
- The created bean can be used by all scriptlets in
the JSP through the given ID as the variable
name. - Page scope JavaBeans are not accessible from a
servlet - In fact, after you created a bean in a JSP, when
you access it again - ltjspuseBean id"myBean" scope"request"
class"example.TestBean" /gt - the servlet/JSP will access the bean in the
session - example.TestBean theBean request.getAttribute("m
yBean")
17Setting Bean Properties
- Syntax
- ltjspsetProperty name"beanName"
property"propertyName" value"propertyValue" /gt - You can use expression tag inside your
setProperty action to set the value - The String value passed into the bean will be
automatically converted using the following
conversion methods - boolean or Boolean Boolean.valueOf
- byte or Byte Byte.valueOf
- char or Character Character.valueOf
- double or Double Double.valueOf
- float or Float Float.valueOf
- int or Integer Integer.valueOf
- long or Long Long.valueOf
18Setting Properties Directly from Request
Parameters
- When the values from the form variables are
needed to copy to the beans, the task can be
automatically done in this way - ltjspsetProperty name"myBean" param"paramName"
property"propertyName" /gt - If the property name is the same as the parameter
name, the param part can be omitted - ltjspsetProperty name"myBean"
property"propertyName" /gt - For multiple values, you can specify for the
parameter name - ltjspsetProperty name"myBean" property"" /gt
- The JSP Engine determines whether to find a value
from the parameter by finding if "value" keyword
I is present in the call.
19Getting Bean Properties
- Syntax
- ltjspgetProperty name"myBean" property"firstName
" /gt - The getProperty action is identical to the JSP
expression - lt ((examples.TestBean) request.getAttribute("myB
ean").getFirstName() gt - In fact, you can even access the bean properties
in a more simple way - ltmyBean.getFirstName()gt
20Example of a JavaBean
- package examples
- public class TestBean implements
java.io.Serializable - protected String firstName
- protected String lastName
- protected int age
- public TestBean()
- public String getFirstName() return
firstName - public void setFirstName(String aFirstName)
- firstName aFirstName
- public String getLastName() return
lastName - public void setLastName(String aLastName)
- lastName aLastName
- public int getAge() return age
- public void setAge(int anAge) age anAge
21JSP Example on Setting Bean Property
- ltHTMLgt
- ltBODYgt
- lt-- Create an instance of the bean --gt
- ltjspuseBean id"myBean" class"examples.TestBean"
/gt - lt-- Copy the parameters into the bean --gt
- ltjspsetProperty name"myBean" property""/gt
- The bean values areltbrgt
- First Name ltjspgetProperty name"myBean"
property"firstName"/gtltBRgt - Last Name ltjspgetProperty name"myBean"
property"lastName"/gtltBRgt - Age ltjspgetProperty name"myBean"
property"age"/gtltBRgt - lt/BODYgt
- lt/HTMLgt
22Initializing a New Bean
- You may want to set some of the properties of the
bean and do other initialization when creating
it. - Java codes and the setProperty tag can be placed
with the useBean tag - If the bean has been created, the code inside the
useBean tab will be skipped
23JSP Example on Initializaing a Bean
- ltHTMLgt ltBODYgt
- lt-- Create an instance of the bean --gt
- ltjspuseBean id"myBean" class"examples.TestBean"
scope"session"gt - I initialized the bean.ltBRgt
- ltjspsetProperty name"myBean"
property"firstName" - value"blah"/gt
- lt out.println("I ran some Java code during
the init, tooltPgt") gt - lt/jspuseBeangt
- lt-- Copy the parameters into the bean --gt
- ltjspsetProperty name"myBean" property""/gt
- The bean values areltbrgt
- First Name ltjspgetProperty name"myBean"
property"firstName"/gtltBRgt - Last Name ltjspgetProperty name"myBean"
property"lastName"/gtltBRgt - Age ltjspgetProperty name"myBean"
property"age"/gtltBRgt - lt/BODYgt lt/HTMLgt
24Building Web Applications
- In a web application, we need to assign work to
different components includes - static HTML pages, JSPs, servlets and other
objects - a task should be delegated to a right component
- In the first JSP specification, the uses of JSPs
and servlets are defined as two model
architectures
25Model 1 Architecture
- JSPs accept client requests, decide which model
to take next and present the result - JSPs work with JavaBeans (or other services) to
affect business objects and generate the contents - JSP always remains in control of the application
- However, we will then have a considerable amount
of business logic in the JSPs in form of
scriptlets throughout the page
26Model 1 Architecture (cont'd)
27Model 2 Architecture
- A servlet accepts a client request, handles the
processing and then forwards to a JSP for
presentation - The servlet can access the business objects,
obtain the information that needs to be displayed
and pass it along to a JSP for presentation - Business logic is kept in the servlet and JSPs
are strictly for presentation - The view of the information will constructed
using directives, standard/custom action and
Expression Language (EL) - Less coupling between components makes the
application flexible and easier to maintain
28Model 2 Architecture and MVC Paradigm
29Model-View-Controller Paradigm
- Model-View-Controller (MVC) paradigm is a way of
dividing an application into three distinct areas - Controller, which is really the input that
changes the system - Model, which is the data that describes the
system - View, which is the display of the data (in the
form of textual, graphical, or even in a file) - Using a car as an example
- gas pedal, brake and steering wheel are
controllers. They send signals to models. - engine, suspension, transmission and etc. are
models - Speedometer, tachometer, fuel gauge and idiot
lights are views.
30MVC Approach of Building Web Applications
- An example of applying MVC to build a complete
web application - The controller servlet connects to the security
server and obtains the user profile - The controller servlet grabs some info from the
database and stores in the request object - If there is an error fetching the data, the
controller servlet forwards to an error JSP - If the user is manager, the controller servlet
forwards to a JSP that displays the manager's
view of the data - If the user is not a manager, the controller
servlet forwards to the regular display JSP - The display JSP grab the info from the reuqest
object and display it
31A Complete Example Shopping Cart
- A modern architectural pattern to design a web
application is to use Model-View-Controller (MVC) - Model represents the data describing the system
and their behavior - View represents the presentation of data
- Controller is the input that changes the system
- When designing applications, we should focus on
the model first - That is, we should now create some Java classes
that implements the behavior of a shopping cart. - These classes should be usable independent of the
JSP/servlet
32Data Objects Item, Billing Shipping
- Item class refers to the things that are stored
in the shopping cart and have the following
attributes - productCode, description, price, quantity
- Billing class holds the credit card data and has
the following attributes - nameOnCard, creditCardType, creditCardNumber,
creditCardExpiration - Shipping class holds the following attributes
- name, address1, address2, city, state, country,
postalCode, email
33- package examples.cart
- public class Item implements java.io.Serializable
- public String productCode
- public String description
- public double price
- public int quantity
- public Item()
- public Item(String aProductCode, String
aDescription, double aPrice, int aQuantity) - productCode aProductCode description
aDescription price aPrice quantity
aQuantity -
- public String getProductCode() return
productCode - public void setProductCode(String aProductCode)
- productCode aProductCode
- public String getDescription() return
description - public void setDescription(String aDescription)
- description aDescription
- public double getPrice() return price
- public void setPrice(double aPrice) price
aPrice - public int getQuantity() return quantity
34Data Object Shopping Cart
- Our shopping cart will store the items in a
vector - Main methods are getItems (get all items),
addItem and removeItem. - When the shopping cart is checked out, the
billing and shipping information are to be
completed and stored in the database through the
method completeOrder - in this demo, we store the data in file for
simplicity
35- package examples.cart
- import java.util.
- import java.io.
- public class ShoppingCart implements
java.io.Serializable - // The shopping cart items are stored in a
Vector - protected Vector items
- public ShoppingCart() items new Vector()
- // A clone is return so that modifying the
vector won't affect // the cart. - public Vector getItems() return (Vector)
items.clone() - public void addItem(Item newItem)
items.addElement(newItem) - public void removeItem(int index)
items.removeElementAt(index) - // For demo only, order number reset when server
restarts - protected static int nextOrderNumber 1
- // Submits the order and returns a confirmation
number - public String completeOrder(Shipping shipping,
Billing billing) throws ShoppingCartException - try
- int orderNumber 0
- // Make sure no other threads use the same
order number - synchronized (this)
36- // Print order to file instead of database for
simplicity - PrintWriter out new PrintWriter( new
FileOutputStream("order"orderNumber)) - out.println(shipping.name)
- out.println(shipping.address1)
- if (shipping.address2 ! null) out.println(s
hipping.address2) - out.print(shipping.city)
- if (shipping.state!null) out.print(",
"shipping.state) - if (shipping.postalCode ! null) out.print("
"shipping.postalCode) - out.println(" "shipping.country)
- out.println(shipping.email)
- out.println(billing.nameOnCard)
- out.println(billing.creditCardType)
- out.println(billing.creditCardNumber)
- out.println(billing.creditCardExpiration)
- Enumeration e items.elements()
- while (e.hasMoreElements())
- Item item (Item) e.nextElement()
- out.println(item.productCode ","
item.quantity) -
37Display the Contents of the Shopping Cart
- You will display your shopping cart in a JSP
- To enable it to be displayed in different pages,
your JSP is not a complete Web page itself, i.e.,
it has no ltHTMLgt or ltBODYgt tags - Other pages will include this cart page in their
page - The shopping cart will contain a link to the
RemoveItemServlet, which will remove items from
your cart
38JSP for Shopping Cart
- lt_at_ page language"java" import"examples.cart.,j
ava.util.,java.text." gt - lt-- Show the header with the shopping cart image
--gt - lttable border"0"gt
- lttrgtlttdgtltimg src"cart4.png"gtlttdgtlth1gtShopping
Cartlt/h1gt - lt/tablegt
- lt
- // Get the current shopping cart from the user's
session - ShoppingCart cart (ShoppingCart)
session.getAttribute("ShoppingCart") - if (cart null) // create cart if not exists
- cart new ShoppingCart()
- session.setAttribute("ShoppingCart", cart)
-
- Vector items cart.getItems() // Get the items
from the cart - if (items.size() 0) // Cart is empty
- out.println("lth3gtYour shopping cart is
empty.lt/h3gt") - else
- gt
39- lt-- Display the header for the shopping cart
table --gt - ltbrgt
- lttable border4gt
- lttrgtltthgtDescriptionlt/thgtltthgtQuantitylt/thgtltthgtPrice
lt/thgtlt/trgt - lt
- int numItems items.size()
- // Get a formatter to write out currency values
- NumberFormat currency NumberFormat.getCurrencyI
nstance() - for (int i0 i lt numItems i)
- Item item (Item) items.elementAt(i)
- gt
- lttrgtlttdgtltitem.descriptiongtlt/tdgt
- lttdgtltitem.quantitygtlt/tdgt
- lttdgtltcurrency.format(item.price)gtlt/tdgt
- lttdgt
- lta href"/shoppingcart/RemoveItemServlet?itemlt
igt"gt - Removelt/agtlt/tdgtlt/trgt
- lt gt
- lt/TABLEgt
40Displaying the Product Catalog
- To add item to your shopping cart, you can create
an Item object in three ways - Client browsers send all information to create
the item - Create the item in sessions/application and pull
it out if user want to add one into his/her cart - Retrieve the item information from the
server/database - In this example, we use the second method to
implement the add links in the product catalog - The item will be added into your cart through the
AddToShoppingCart servlet
41JSP for Product Catalog
- lt_at_ page language"java" import"examples.cart.,j
ava.net.,java.text." gt - lt!
- // Declare a constant for the number of items to
show on a page - public static final int ITEMS_PER_PAGE 5
- gt
- lthtmlgtltbody bgcolor"ffffff"gt
- lta href"/shoppingcart/ViewShoppingCart.jsp"gtView
Shopping Cartlt/agt - ltpgt lth1gtAvailable Productslt/h1gt
- lttable border"1"gt
- lttrgtltthgtDescriptionltthgtQuantityltthgtPrice
- lt // Get the shared product catalog
- ProductCatalog catalog (ProductCatalog) appli
cation.getAttribute("ProductCatalog") - // If the shared product catalog hasn't been
created yet, create it - if (catalog null)
- synchronized (application)
- catalog new ProductCatalog()
- application.setAttribute("ProductCatal
og", catalog) -
-
42- lt // Get the next starting position for
displaying catalog items - String startingPositionStr (String)
request.getParameter("StartingPosition") - int startingPosition 0
- if (startingPositionStr ! null)
- try
- startingPosition Integer.parseInt(startin
gPositionStr) - catch (Exception ignore)
-
- // Get ITEMS_PER_PAGE items at a time
- Item items catalog.getItems(startingPositio
n, ITEMS_PER_PAGE) - NumberFormat currency NumberFormat.getCurrencyI
nstance() - for (int i0 i lt items.length i)
- Item item itemsi
- String addItemURL "/shoppingcart/AddToShoppi
ngCartServlet?" "productCode"
URLEncoder.encode(item.getProductCode())
"description"URLEncoder.encode(item.getDescript
ion()) "quantity" URLEncoder.encode(""ite
m.getQuantity()) "price"URLEncoder.encode("
"item.getPrice()) - gt
- lttrgtlttdgtltitem.getDescription()gtlt/tdgtlttdgtltitem
.getQuantity()gt - lt/tdgtlttdgtltitem.getPrice()gtlt/tdgt
- lttdgtlta href"ltaddItemURLgt"gtAdd to Shopping
Cartlt/agtlt/tdgtlt/trgt - lt
43- lttable border"0"gt
- lttrgt
- lt
- if (startingPosition gt 0)
- int prevPosition startingPosition-ITEMS_PER_PA
GE - // Don't let the starting position go negative
- if (prevPosition lt 0) prevPosition 0
- // Write out a link to display the previous
catalog page - out.println( "lttdgtlta href\"/shoppingcart
/ShowProductCatalog2.jsp?" "StartingPosition"
prevPosition"\"gtltltPrevlt/agtlt/tdgt") -
- // Compute the next starting position in the
catalog - int nextPosition startingPositionITEMS_PER_PAG
E - if (catalog.itemsAvailable(nextPosition))
- // Write out a link to display the next catalog
page - out.println( "lttdgtlta href\"/shoppingcart
/ShowProductCatalog2.jsp?" StartingPosition"
nextPosition"\"gtNextgtgtlt/agtlt/tdgt") -
- gt
- lt/trgt
- lt/tablegt
44Java Code for Product Catalog
- package examples.cart
- import java.util.Vector
- public class ProductCatalog
- protected Item items
- public ProductCatalog()
- // Set up an array of items that represents the
catalog - items new Item
- new Item("PBJG-1", "Pale Blue Japanese Guitar",
700.00, 1), - new Item("PBJZ-1", "Pale Blue Japanese Zither",
1400.00, 1), - new Item("PBJS-1", "Peanut Butter Jelly
Sandwich", 1.00, 1), - // more items to add here
-
-
- // returns an array containing all the items in
the catalog - public Item getItems() return getItems(0,
items.length)
45- // returns an array containing a subset of items
from the catalog - public Item getItems(int startingLocation, int
numItems) - if (numItems gt items.length) numItems
items.length - if (startingLocationnumItems gt
items.length) startingLocation items.length -
numItems - Item returnItems new ItemnumItems
- System.arraycopy(items, startingLocation,
returnItems, 0, numItems) - return returnItems
-
- public boolean itemsAvailable(int
startingLocation) - if (startingLocation gt items.length) return
false - return true
-
- public Item findItemByProductCode(String
productCode) - for (int i0 i lt items.length i)
- if (itemsi.getProductCode().equals(productCode
)) - return itemsi
-
- return null
-
46AddToShoppingCartServlet.java
- package examples.cart
- import javax.servlet.
- import javax.servlet.http.
- import java.io.
- public class AddToShoppingCartServlet extends
HttpServlet - public void service(HttpServletRequest request,
HttpServletResponse response) throws IOException,
ServletException - String productCode request.getParameter("produc
tCode") - String description request.getParameter("descri
ption") - int quantity Integer.parseInt(request.getParam
eter("quantity")) - double price Double.parseDouble(request.getPa
rameter("price")) - Item item new Item(productCode, description,
price, quantity) - HttpSession session request.getSession()
- ShoppingCart cart (ShoppingCart)
session.getAttribute("ShoppingCart") // get
the cart - // If there is no shopping cart, create one
- if (cart null)
- cart new ShoppingCart()
- session.setAttribute("ShoppingCart", cart)
-
- cart.addItem(item)
47Deploying your Shopping Cart
- The complete example is placed in the course
homepage as a zipped file - Unzipped it and placed the shoppingcart folder in
the webapps folder - You may need to compile the servlet classes
explicitly - To compile the files, you should first set the
classpath of your machine to include the
followings classpath .c\tomcat\common\lib\se
rvlet-api.jar(the tomcat folder should be
substitute to your installed folder) - Then, compile the file using javac d
WEB-INF\classes .javaThe file will then be
automatically placed in the respective folder and
organized in appropriate subfolders.
48Deploying a Web Application
- To make your web application to be deployed as a
folder, you need to - Write a Deployment Descriptor (web.xml)
- Package your files into a folder with a subfolder
called WEB-INF - Place the web.xml file into the subfolder WEB-INF
- Place the compiled class files into a subfolder
named "classes" under WEB-INF - Place the necessary jar files (e.g. JDBC driver)
in a subfolder named "lib" under WEB-INF
49Deployment Descriptor
- lt?xml version"1.0" encoding"ISO-8859-1"?gt
- ltweb-app xmlns"http//java.sun.com/xml/ns/j2ee"x
mlnsxsi"http//www.w3.org/2001/XMLSchema-instanc
e"xsischemaLocation"http//java.sun.com/xml/ns/
j2ee http//java.sun.com/xml/ns/j2ee/web-app_2_4.
xsd"version"2.4"gt - ltdisplay-namegtShopping Cart Examplelt/display-name
gt - ltdescriptiongtAn Example using sessions to creat
a shopping cartlt/descriptiongt - ltservletgt ltservlet-namegtAddToShoppingCartServlet
lt/servlet-namegt ltservlet-classgt examples.cart.A
ddToShoppingCartServlet lt/servlet-classgt - lt/servletgt
- ltservletgt ltservlet-namegtCheckoutServletlt/servlet
-namegt ltservlet-classgt examples.cart.Checkou
tServlet lt/servlet-classgt - lt/servletgt
50Deployment Descriptor (cont'd)
- ltservletgt ltservlet-namegtRemoveItemServletlt/servl
et-namegt ltservlet-classgt examples.cart.RemoveIt
emServletlt/servlet-classgtlt/servletgt - ltservlet-mappinggt ltservlet-namegtAddToShoppingCar
tServletlt/servlet-namegt lturl-patterngt/AddToShoppi
ngCartServletlt/url-patterngtlt/servlet-mappinggt -
- ltservlet-mappinggt ltservlet-namegtCheckoutServletlt
/servlet-namegt lturl-patterngt/CheckoutServletlt/url
-patterngtlt/servlet-mappinggt -
- ltservlet-mappinggt ltservlet-namegtRemoveItemServle
tlt/servlet-namegt lturl-patterngt/RemoveItemServletlt
/url-patterngtlt/servlet-mappinggt - lt/web-appgt
51Deployment Descriptor Sections
- The lt?xml ?gt tag defines the files as an XML
file. All XML should contain this tag. - The ltweb-appgt tag defines the main element for
this file and says that this XML file describe a
web application. - Inside the ltweb-appgt tag, we have ltdisplay-namegt
and ltdescriptiongt tag to provide brief
descriptions of the application - A web.xml file can contain any number of servlet
definitions, each defined by a ltservletgt tag - Inside a servlet tag, it must contain at least a
ltservlet-namegt and a ltservlet-classgt tag - Definition is not enough, you must also specify a
ltservlet-mappinggt tag, which maps a URL to a
servlet - Inside a servlet mapping tag, it must contain a
ltservlet-namegt and a lturl-patterngt
52URL Pattern in Servlet Mapping
- A request URI consists of three parts
- requestURI contextPath servletPath pathInfo
- Each application has a context, and the context
path of the application is the path in the URL
representing the application - The ServletPath is the part we concerned in
defining a lturl-patterngt - A string beginning with "/" and ends with "/" is
used path-mapping it will examine the part of
URI after the contextPath and make the longest
possible match in determining which servlet is
invoked - A String beginning with "." is an extension
mapping - A String containing only a "/" maps to
application's default servlet the servlet must
be invoked if no match is found - Any other string requires an exact match
53Examples of URL Pattern Matching
- If we used a url-pattern of "/myservlet/", we
invoke the servlet with any URL whose servlet
path started with "/myservlet/" - http//localhost8080/myservlet/
- http//localhost8080/myservlet/lowerLevel
- If we used ".bar" for the url-pattern, we invoke
the servlet when it is with such an extension - http//localhost8080/myservlet/abc.bar
- Changing the url-pattern to "/" makes our servlet
the default servlet it will be invoked whenever
a match for the URL cannot be found - In the given example, the url-pattern is to be
exact matched
54Bean-Based Web Application
- In the last example, all shopping cart classes
item, shopping cart, catelog and etc. are
JavaBeans - Using useBean tags, we can make the servlets to
very short JSPs. - Try the updated example given in the course
homepage
55AddToShoopingCart (JSP version)
- lt-- Get a reference to the shopping cart --gt
- ltjspuseBean id"cart" class"examples.cart.Shoppi
ngCart" scope"session"/gt - lt-- Create an item object --gt
- ltjspuseBean id"item" class"examples.cart.Item"
scope"page"/gt - lt-- Copy the request parameters into the item
--gt - ltjspsetProperty name"item" property""/gt
- lt-- Add the item to the shopping cart --gt
- lt cart.addItem(item) gt
- lt-- Display the product catalog again --gt
- ltjspforward page"ShowCartAfterAdd.jsp"/gt
56Using JavaBeans to Access Database
- Accessing database within the scriptlet messed
the Java code with the HTML - One solution is to encapsulate the database
connection and access code into a JavaBean SQL
will be passed into the bean as parameter and
Resultset will be returned to the JSP - The more sensible way is to let the JavaBean to
access the database and then control and return
the result according to the Bean's properties - The following example show how JavaBeans can be
used to access the database - Try implement the jsp part yourself
57A Sample Database Access Class
- import java.sql.
- public class SQLBean
- String DBDriver "sun.jdbc.odbc.JdbcOdbcDriver"
- String DBURL "jdbcodbcmyDatabase"
- Connection conn null
- ResultSet rs null
- public SQLBean(String driver, String url)
- setDBDriver(driver)
- setDBURL(url)
- try Class.forName(DBDriver)
- catch (ClassNotFoundException e)
- e.printStackTrace()
-
- public SQLBean(String url) this(DBDriver,
url) - public SQLBean() this(DBDriver, DBURL)
58- public void setDBDriver(String driver)
DBDriver driver - public String getDBDriver () return DBDriver
- public void setDBURL(String url) DBURL url
- public String getDBURL () return url
- public void executeUpdate (String sql)
- try
- conn DriverManager.getConnection(DBURL)
- Statement stmt conn.createStatement()
- stmt.executeUpdate(sql)
- catch (SQLException sqle)
sqle.printStackTrace() - finally if (conn!null) conn.close()
-
- public ResultSet executeQuery (String sql)
- rs null
- try
- conn DriverManager.getConnection(DBURL)
- Statement stmt conn.createStatement()
- rs stmt.executeQuery(sql)
- catch (SQLException sqle)
sqle.printStackTrace()
59A JavaBean Controlling Result
- import java.sql.
- public class UserBean
- private String username, password, message
- private boolean login, changed
- public UserBean()
- SQLBean dbconn new SQLBean("jdbcodbcstudent"
) - username null password null
- login false changed false
- message "User not yet login"
-
- public void setUsername(String user)
- username user changed true
-
- public String getUsername() return username
- public void setPassword(String passwd)
- password passwd changed true
-
60- public boolean getLogin()
- if (changed)
- ResultSet rs dbconn.executeQuery(
- "Select from users where username'"
- username "'")
- if(rs.next())
- if(rs.getString("password").equals(password))
- login true
- message "User login successfully"
- else
- login false
- message "Wrong password"
-
- else
- login false
- message "No such user"
-
-
- changed false