Professional Documents
Culture Documents
Week 2
• User Authorization
• URL Rewriting
• Persistent cookies
• Data about the user and the user’s state can be saved in a shared
object.
import java.util.*;
GSIA E-Commerce Technologies II
public class VisitTracker {
Date d = (Date)nameDatePairs.get(name);
return d;
}
}
• The following will keep track of the date of the last visit.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import javax.servlet.*; GSIA E-Commerce Technologies II
import javax.servlet.http.*;
public class CookieDemo extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res
throws ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
Cookie[] c = req.getCookies();
// If this person has been here before then we should have
// a cookiedemouser field assigned to a unique id.
String id = null;
if (c[i].getName().equals("cookiedemouser")) {
id = c[i].getValue();
}
break;
}
}
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
session.setAttribute("dateofvisit", new
GSIA E-Commerce Technologies II Date());
}}
Servlets and JDBC
• A simple servlet that:
GenerateHTML.java
This class has methods to generate
HTML text. Subclasses return
HTML forGSIAparticular pages
E-Commerce Technologies II
GenerateHTML.java
public class GenerateHTML{ getHeader() generates an HTML header,
public String getHeader(String s) { getting the page title from getTitle()
return "<html><Header><title>"+ getTitle(s)+"</title></header>";
}
public String getTitle(String s) { getTitle() should be overridden in subclasses
return "Page Title"; to generate a page title specific to each page
}
public String getBody(String s) {
return "<body>"+ getBodyText(s) + "</body></html>";
} getBody() generates the body of the HTML page, enclosing page-specific
contents from getBodyText()
The init() method is called when the servlet is first created and is
not called again for each user request. Be sure to call the base class
init() with super.init(config);
Overrides
getTitle() to
name the
page “Login
Screen”
GSIA E-Commerce Technologies II
doPost() is Called Again
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
//Code relating to response object was already reviewed
Cookie[] c = req.getCookies(); An array of cookies is instantiated to hold the
boolean sessionExists = false; cookies from the request object
boolean loggedIn = false;
if (c==null) If the array is null, there are no cookies, so the
out.println(doLogin(res)); Login Screen is generated
else {
for (int i=0;i<c.length;i++) { Otherwise, each cookie is checked.
if (c[i].getName().equals("exists")) The getName() method gets the name
of the cookie attribute. The Login
sessionExists = true; screen added the “exists” cookie, so
if (c[i].getName().equals("user")) { sessionExists will be set to true. We
loggedIn = true; have not yet seen the “user” cookie,
user = c[i].getValue(); so loggedIn will remain false.
}
} The getValue() method gets
GSIA the data that
E-Commerce has been
Technologies II added to that cookie.
if (sessionExists) {
if (loggedIn)
out.println(processTrans(req, res, user));
else
sessionExists is true.
out.println(giveOptions(req, res));
}
loggedIn is false. The
else response object
out.println(doLogin(res)); therefore prints the
out.close(); results of giveOptions()
}
}
Both the request and response
object are passed
GSIA E-Commerce Technologies II
giveOptions()
public String giveOptions
(HttpServletRequest req, HttpServletResponse res) {
SELECT *
FROM customer
WHERE username = user
AND password = password;
GSIA E-Commerce Technologies II
The ResultSet’s next() method will only be true if the select
if (r.next()) { statement returned data (ie the user and password are valid)
code +=(gen.getBody(r.getString("balance")));
The data in the balance attribute is taken from the ResultSet and passed to
getBody()
Cookie c = new Cookie("user",user);
res.addCookie(c);
A cookie named “User” is created containing the
return code; username and added to the response object
}
//Code if r.next is falseGSIA
willE-Commerce Technologies II
be reviewed later
GenerateOptions
public class GenerateOptions extends GenerateHTML {
public String getTitle(String s) {
Overrides getTitle() to name the
return "Welcome "+s;
page Welcome followed by the
} username
try{
If no match was
if (r.next) found in the
//Previously reviewed code database or if
else { there is an
return(getRejection("missing")); SQLException,
we pass a
} particular String
} to getRejection()
catch(SQLException e) { and return the
return(getRejection("db")); result to doPost()
} GSIA E-Commerce Technologies II
getRejection()
public String getRejection(String s) {
GenerateReject gen = new GenerateReject(); Missing or invalid
String problem ="Error"; username and password
if (s.equals("missing"))
problem = "You did not enter a valid user name and password.";
if (s.equals("db"))
problem = "Database Error"; SQLException
if (s.equals("overdraw"))
problem="You may not withdraw more than your balance.";
if (s.equals("invalid"))
problem="You must fill out the form correctly.";
The request and response object and the username are passed
GSIA E-Commerce Technologies II
processTrans()
public String processTrans
(HttpServletRequest req, HttpServletResponse res, String user) {
boolean isDouble = true;
double amount=0; Since the form text fields are Strings,
try { “amount” needs to be wrapped in a
Double object before it may be placed in a
double variable
Double d = new Double(req.getParameter("amount"));
amount = d.doubleValue();
}
If the amount is non-numeric or blank, an
catch (Exception e) {
exception will be thrown. The catch
isDouble = false; clause sets the boolean isDouble to false
}
GSIA E-Commerce Technologies II
if (isDouble) {
try {
If the amount can convert to a double, the servlet begins preparing
an SQL statement. (Most is the same for deposits or withdrawals.)
Statement s = con.createStatement();
String s1="UPDATE customer SET balance =(";
String s2=") WHERE username =\'"+user+"\';";
ResultSet r;
The radio button contents are retrieved from the request object
GSIA E-Commerce Technologies II
If the withdraw radio button was
if (action.equals("withdraw")) { selected, the servlet checks to
if (amount > currentBalance) prevent overdrawing the account.
If there is an overdraw, the results
return(getRejection("overdraw")); of the error method, getRejection()
else { are returned to doPost()
amount = currentBalance-amount;
int success = s.executeUpdate(s1+amount+s2);
return(getUpdate(success,amount));
}
If the current balance is high enough, the servlet combines the two parts of the
} query String, surrounding the new balance and returns the results of the
getUpdate() method
else { A deposit works the
amount +=currentBalance; same way, except that it
int success = s.executeUpdate(s1+amount+s2); does not worry about
overdrafts
return(getUpdate(success,amount));
} executeUpdate() returns the number of rows changed or 0
//Rest of method will be if no update was made. This and the updated balance get
//examined later GSIApassed
E-Commerce Technologies II
to getUpdate()
Database Integrity Question
The current balance was selected, additional code was run,
and then the balance was updated.
<In> -- </In>
<Out>
<Topic>Homework 1</Topic>
<Location>homework/Lab1.doc</Location>
</Out>
</Lecture>
<Lecture>
<Date>January 24</Date>
<Reading></Reading>
<Slides>
<Topic></Topic>
<Location></Location>
</Slides>
<In> Homework 1 </In>
<Out>
<Topic></Topic>
<Location></Location>
</Out>
</Lecture>
<Lecture>
<Date>January 31</Date>
<Reading>--</Reading>
<Slides>
<Topic></Topic>
<Location></Location>
</Slides>
<In>--</In>
<Out>
<Topic></Topic>
<Location></Location>
</Out>
</Lecture>
: GSIA E-Commerce Technologies II
</Schedule>
schedule.xsl
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="/">
<HTML>
<HEAD>
<TITLE>
<xsl:value-of select="Schedule/CourseTitle"/>
</TITLE>
</HEAD>
<font size="1">[
<a href="../index.html">Home</a> |
<b>Schedule</b> |
<a href="syllabus.htm">Syllabus</a> |
<a href="coursedes.htm">Course description</a> |
<a href="faq/faq.txt">FAQ</a>
]
</font>
<xsl:template match="Schedule/CourseTitle">
<br></br><br></br>
</xsl:template>
GSIA E-Commerce Technologies II
<xsl:template match="Schedule/Lecture">
<tr>
<td>
<!-- printing the date -->
<xsl:value-of select = "Date"/>
</td>
</td>
</tr>
</xsl:template>
</xsl:stylesheet>
XmlDocument result;
super.init(config);
try {
}
catch(IOException e) {
System.out.println("I/O Problem!!" + e);
}
catch(TransformException e) {
System.out.println("A transformation problem!");
}
catch(SAXException e) {
System.out.println("A SAX problem!");
}
} GSIA E-Commerce Technologies II
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
result.write(out);
out.close();
}