Transcript Servlets

1
1
J2EE
Servlets
1
2
Servlets: background
• Java Executables: Application, Applet, Servlet
• A Servlet is a type of Java program that runs only on the
server.
• Servlets were introduced in 1998 with J2EE or the Java 2
Enterprise Edition.
• Servlets are Java’s replacement for CGI [Common
Gateway Interface].
1
3
Servlets: background
• Although a normal HTML page executes in a web server,
a Servlet needs a special container called a Web Application
Server, commonly abbreviated as WAS.
• When running inside a WAS, a Servlet sits inside a place
called a Servlet Container.
1
4
Servlets: background
• A Servlet is only loaded once. Thereafter, a new thread is
created for every new call to the servlet. This eliminates
much of the overhead that plagued CGI.
• To begin, our Servlet Container will be a free web
application server called “Tomcat.”
1
5
Servlets: understanding Tomcat
• Tomcat has a particular directory structure that you must
use.
The webapps directory holds everything the
server will serve up.
In our case, there is a javaclass folder.
The presence of this javaclass folder
below the webapps folder means that
javaclass must be made part of the URL
path name. The html is located in the
javaclass folder.
1
6
Servlets: understanding the Tomcat web.xml
• For a Web Application, there is a special configuration file
called web.xml that must be located in the WEB-INF
directory. We will learn more about this file.
web.xml
As you can see, there are no
servlets registered yet.
1
7
HTML: forms
1
8
HTML: basic HTML
• Nearly everyone is familiar with HTML
BasicHtml.htm
<HTML>
<HEAD>
<TITLE>This is raw html</TITLE>
</HEAD>
<BODY>
This is the part that displays in the page.
</BODY>
</HTML>
1
9
HTML: basic Links
• The simplest way to trigger an action is through a hyperlink.
BasicLink.htm
<HTML>
<HEAD>
<TITLE>Basic Link</TITLE>
</HEAD>
<BODY>
This is a <A HREF="BasicHtml.htm">hyperlink</A>
to <CODE>BasicHtml.htm</CODE>.
</BODY>
</HTML>
1
10
HTML: basic Forms
• If you want to place a submit button on a page, you need
something called a “form”.
• This puts a “Submit” button on the HTML page.
• When the button is clicked, the ACTION page is loaded.
SubmitButtonForm.htm
<HTML>
<HEAD>
<TITLE>This is raw html</TITLE>
</HEAD>
<BODY>
<FORM ACTION="BasicHtml.htm">
<INPUT TYPE="SUBMIT">
</FORM>
</BODY>
</HTML>
1
11
HTML: basic Forms
• The result of the Submit is doing what the ACTION
specifies.
• Do You notice anything else unusual on this displayed
page?
When a GET is executed, it will pull in any data that is
associated with the form. The name-value pairs of the form
are included after the question mark.
1
12
HTML: GET
(There is a second type of button whose type = “button”.
However, this button is of type = “submit”. )
• When the button type is “submit”, clicking on it does
something special. It executes a GET.
SubmitButtonForm.htm
<HTML>
<HEAD>
<TITLE>GET html</TITLE>
</HEAD>
<BODY>
<FORM ACTION="BasicHtml.htm">
<INPUT TYPE="SUBMIT">
</FORM>
</BODY>
1
</HTML>
13
HTML: GET
• This also executes a GET but it adds two Text Input
Fields.
• Notice the two TEXT INPUT fields have names. Let’s
watch what happens to those names when we do the GET.
<HTML>
<HEAD>
<TITLE>GET Form with Text Fields html</TITLE>
</HEAD>
<BODY>
<FORM ACTION="BasicHtml.htm">
First Name:
<INPUT TYPE=“TEXT” NAME=“firstName”><BR>
Last Name:
<INPUT TYPE=“TEXT” NAME=“lastName”><BR>
<INPUT TYPE="SUBMIT">
</FORM>
</BODY>
1
</HTML>
14
HTML: GET
GetWithTextFields.htm
<HTML>
<HEAD>
<TITLE>GET Form with Text Fields html</TITLE>
</HEAD>
<BODY>
<FORM ACTION="BasicHtml.htm">
First Name:
<INPUT TYPE=“TEXT” NAME=“firstName”><BR>
Last Name:
<INPUT TYPE=“TEXT” NAME=“lastName”><BR>
<INPUT TYPE="SUBMIT">
</FORM>
</BODY>
1
</HTML>
15
HTML: GET
<HTML>
<HEAD>
<TITLE>GET Form with Text Fields html</TITLE>
</HEAD>
<BODY>
<FORM ACTION="BasicHtml.htm">
First Name:
<INPUT TYPE=“TEXT” NAME=“firstName”><BR>
Last Name:
<INPUT TYPE=“TEXT” NAME=“lastName”><BR>
<INPUT TYPE="SUBMIT">
</FORM>
</BODY>
1
</HTML>
16
HTML: POST
• If you add a second parameter of METHOD = “POST”,
then clicking on the Submit button executes a POST.
• There are important differences between a GET and a
POST.
<HTML>
<HEAD>
<TITLE>This is raw html</TITLE>
</HEAD>
<BODY>
<FORM METHOD=“POST” ACTION="BasicHtml.htm">
<INPUT TYPE="SUBMIT">
</FORM>
</BODY>
</HTML>
1
17
HTML: POST
• When you look at the resultant URL following a POST,
you see that the “?” is not there.
• For a POST, the data is gathered in a different way.
1
18
First Servlet:
doGet()
1
19
First Servlet
• A Servlet is a Java program that runs only on a server.
•A Servlet sits around all day in a running server waiting for
either of two events to happen.
• An HTML page executes either a
GET or a
POST
• When some HTML page executes a GET or a POST
using the name of a particular Servlet, the Web Application
Server responds by executing that Servlet’s doGet() or
doPost() method.
1
20
First Servlet
• A Servlet is just another Java class.
• A Servlet extends the class HttpServlet
• A Servlet has two central methods: doGet(), doPost()
• When either one of these methods is executed by a web page,
the method receives two arguments:
HttpServletRequest—full when called.
HttpServletResponse—empty when first called.
1
21
First Servlet
• One of these methods calls works like this: I’m asking the
doGet() method to do some work for me. I give it two
boxes. The first box [HttpServletRequest] is full with the
information I want it to work on. The second box
[HttpServletResponse] is empty. Any information that
comprises the response I will expect to find in the second
box.
HttpServletRequest—full when called.
HttpServletResponse—empty when first called.
1
22
import
import
import
import
import
java.io.*;
java.text.*;
java.util.*;
javax.servlet.*;
javax.servlet.http.*;
public class HelloWorldServlet extends HttpServlet
{
}
Our first step is extending
HttpServlet. By definition, when
we extend HttpServlet, our class
“is a” Servlet.
1
23
import
import
import
import
import
java.io.*;
java.text.*;
java.util.*;
javax.servlet.*;
javax.servlet.http.*;
public class HelloWorldServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
}
}
Next, we add in our doGet() method This
overrides the one we inherit from HttpServlet.
Note: for the override to succeed, the signature of
our doGet() method must match this one
exactly. That means: method name, arguments and
thrown exceptions.
1
24
import
import
import
import
import
java.io.*;
java.text.*;
java.util.*;
javax.servlet.*;
javax.servlet.http.*;
public class HelloWorldServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
PrintWriter out = response.getWriter();
out.println( “Hello World” );
}
}
Finally, we are taking advantage of the
response box. We are getting a reference to its
“writer” and then we are writing plain text to it.
1
25
First Servlets: placement of file in Tomcat4.1.24
• Our HelloWorldServlet is located in the classes
directory.
Our servlet is placed inside this
“classes” directory.
If our class was also in a package,
then that path would start within
the classes directory. For
example, if our servlet was
located in: package
mypackage1, then the
classes directory would have a
directory within it called
“mypackage1” and inside that
directory we would find our
HelloWorldServlet.
1
26
First Servlets: executing the servlet
• To cause our HelloWorldServlet to be executed, we must
place this on the command line:
http://localhost:8080/javaclass/servlet/HelloWorldServlet
Notice how the output is plain text, not
HTML. We can change that easily be
setting the content type.
1
27
import
import
import
import
import
java.io.*;
java.text.*;
java.util.*;
javax.servlet.*;
javax.servlet.http.*;
public class HelloWorldHtmlServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType( “text/html” );
You must set this before you do
your first out.println()
PrintWriter out = response.getWriter();
out.println( “<HTML>” );
out.println( “<HEAD><TITLE>Hello World!</TITLE></HEAD>” );
out.println( “<BODY>” );
out.println( “<H1>Hello World</H1>” );
out.println( “</BODY>” );
out.println( “</HTML>” );
}
}
1
28
First Servlets: configuring the web.xml file
• For these past two servlets, we have not had to do any
configuration—which is not usually the case.
Normally, you will need to register your servlet in a special
file called web.xml.
web.xml
If your servlet is located in a package, then
the entire path must be reflected in the lower
parameter. For example, if
HelloWorldServlet was in the
package mypackage1 then this lower
<servlet-class> tag would contain:
mypackage1.HelloWorldServlet
1
29
First Servlets: calling a servlet through a link
• Now, we will use one of our usual HTML links to execute
our HelloWorldHtmlServlet.
<HTML>
BasicLink.htm
<HEAD>
<TITLE>Basic Link</TITLE>
</HEAD>
<BODY>This link will cause the
<A HREF=“http://localhost:8080/javaclass/servlet/HelloWorldHtmlServlet">
HelloWorldHtmlServlet</A> to be called.
</BODY>
</HTML>
1
30
First Servlets: calling a servlet through a submit
• Next, we will execute our HelloWorldHtmlServlet
servlet in response to a submit button having been pressed..
SubmitButtonCallServlet.htm
1
31
First Servlets:
doPost()
1
32
First Servlets: doPost()
• Until now all of our Servlets have been called by doing a
doGet()
When we executed a servlet on the command line like this—
http://localhost:8080/javaclass/servlet/HelloWorldHtmlServlet
—we were doing a doGet().
Likewise, when we used the submit button to execute the
servlet using the form and the action tag—
<BODY>This link will cause the
<FORM ACTION=”http://localhost:8080/javaclass/servlet/HelloWorldHtmlServlet">
</FORM>
</BODY>
—we were again executing a doGet().
1
33
First Servlets: doPost()
• The doGet() is not secure because it allows the values of
the variables on the page to be seen in the URL.
Instead, it is better to use a doPost().
• The doPost() is triggered by making one change to our
form tag:
SimplePost.htm
<HTML>
<HEAD><TITLE>A Sample FORM using POST</TITLE></HEAD>
<BODY>
<FORM ACTION="/javaclass/servlet/coreservlets.ShowParameters"
METHOD="POST">
First Name: <INPUT TYPE="TEXT" NAME="firstName"><BR>
Last Name: <INPUT TYPE="TEXT" NAME="lastName"><BR>
Card Num:
<INPUT TYPE="PASSWORD" NAME="cardNum"><BR>
<INPUT TYPE="SUBMIT" VALUE="Submit Order">
</FORM>
</BODY>
</HTML>
1
34
First Servlets: doPost()
• Here we see our html page with the form that triggers the
post.
SimplePost.htm
ShowParameters
1
35
import
import
import
import
java.io.*;
javax.servlet.*;
javax.servlet.http.*;
java.util.*;
public class ShowParameters extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println( "<HTML><HEAD><TITLE>Reading Parameters</TITLE></HEAD><BODY>" );
String fName = (String) request.getParameter( "firstName" );
String lName = (String) request.getParameter( "lastName" );
String cNum = (String) request.getParameter( "cardNum" );
out.println( "<BR>First Name=" + fName + "<BR>" );
out.println( "<BR>Last Name=" + lName + "<BR>" );
out.println( "<BR>Card Numb=" + cNum + "<BR>" );
out.println( "</BODY></HTML>" );
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doPost( request, response);
}
}
1
36
First Servlets:
sendRedirect()
1
37
First Servlets: sendRedirect()
• Normally, a website is larger than two pages. And,
depending on the information that was input by the user, a
decision needs to be made.
For this purpose, we rely on a method that can send the user
to a new page depending on what data was entered.
request.sendRedirect( “/javaclass/BadCreditCard.htm”)
This command will tell the server to send the user to the
page indicated by the argument of the method.
1
38
import
import
import
import
java.io.*;
javax.servlet.*;
javax.servlet.http.*;
java.util.*;
This is known as a “relative URL”. Either a relative or
an absolute URL are acceptable.
public class CheckParameters extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String fName = (String) request.getParameter( "firstName" );
String lName = (String) request.getParameter( "lastName" );
String cNum = (String) request.getParameter( "cardNum" );
if( cNum != null && cNum.length() > 0 )
{
out.println( "<HTML><HEAD><TITLE>Reading Parameters</TITLE></HEAD><BODY>" );
out.println( "<BR>First Name=" + fName + "<BR>" );
out.println( "<BR>Last Name=" + lName + "<BR>" );
out.println( "<BR>Card Numb=" + cNum + "<BR>" );
out.println( "</BODY></HTML>" );
}
else
{
response.sendRedirect( “/javaclass/BadCreditCard.htm” );
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doPost( request, response);
1
}
}
39
First Servlets: sendRedirect()
• This html file “SimplePostWithCheck.htm” will
POST to the CheckParameters Servlet
Here, you see I am about
to submit this HTML
form with nothing in the
credit card field.
1
40
First Servlets: sendRedirect()
• The HTML page POSTs to the Servlet, which does the test
and decides whether to send to the success page or the failure
page.
I have made it so this link returns the user to the
SimplePostWithCheck.htm page.
1
41
First Servlets:
Servlet to Servlet
1
42
First Servlets: Servlet to Servlet
• Just as a Servlet can cause an HTML page to be loaded,
as we saw in the previous example, a Servlet can cause
another Servlet to be loaded.
SimplePostWithSlap.htm
1
43
First Servlets: Servlet to Servlet
• The HTML page on the previous slide executed a POST
against this Servlet, causing this Servlet to execute its
doPost() method. If the input was bad, we don’t even see
this servlet because it just does the sendRedirect().
CheckParametersWithSlap
1
44
First Servlets: Servlet to Servlet
• And here is the ‘SlapServlet’
SlapServlet
1
45
• What? Why was this “SlapServlet” not found?
The path looks correct, as we
can see from the directory.
In short, everything looks great.
1
46
First Servlets:
Why web.xml is Needed
1
47
First Servlets: Why web.xml is Needed
• The answer can be found in that web.xml file I
mentioned earlier.
• Notice that we have not registered any servlets yet in this
file. Normally, you would list every Servlet in here.
web.xml
1
48
First Servlets: Why web.xml is Needed
• Let’s add our SlapServlet to this list and see what happens.
web.xml
1
49
First Servlets: Why web.xml is Needed
• Success! Now we have been able to call a servlet from
another servlet.
1
50
First Servlets:
Cookies
1
51
First Servlets: Cookies
• When you go to a regular HTML web page, every time you
get a page, you’re anonymous. The server does not remember
that it just gave you a previous page. Every time you request a
web page, you’re a brand new visitor in the eyes of the server.
• But that’s not really a good thing. If the server didn’t
remember you from page to page, it would be impossible to
do something like use a Shopping Cart.
• To fill that need, the idea of a “session” was developed.
1
52
First Servlets: Cookies
• A “session” is a way to remember you from page to page.
• There are several ways to achieve that goal, but one of the
most common is a Cookie.
• A Cookie is a small text file the server places in your
computer. It allows the server to remember who you are.
For example, this screen
capture shows a Cookie that was
placed in some computer by the
NYTimes. If means something only
to them.
1
53
First Servlets: Cookies
• However, because of various privacy concerns, it is entirely
possible that users may have disabled cookies.
• In programming for the web, you must be prepared to cope
with that—meaning you must be able to remember who a
user is from page to page without relying on cookies.
1
54
First Servlets:
Session Tracking
1
55
First Servlets: Session Tracking
• Recall that HTTP is a “stateless” protocol, which means
that every page starts from square one, opening a separate
connection to the server.
• So, how can the server keep track of you?
• There are three common ways around this:
Cookies—the cookie acts like a primary key that associates
with a session database entry on the server.
URL-rewriting—the identity of the user is passed from
page to page in the URL.
Hidden form fields—the identity of the user is kept on the
page itself in a form tag the user can’t see
1
56
First Servlets: Session Tracking
• Earlier we saw an example of a Cookie.
• This screen capture shows how a Session ID (SID) was
appended to the URL. The user is unaware of this.
• This URL-rewriting will work even if the user has
cookies disabled. Still, with this approach, the
sessionid must be appended for every single URL
this page accesses.
Hidden Form Field
<INPUT TYPE=“HIDDEN” NAME=“session” VALUE=“…”>
1
57
First Servlets: Session Tracking
• Luckily, the Servlet API has a neat way to solve this
problem.
1
58
public class MySessionServlet extends HttpServlet
{
public void doPost( HttpServletRequest req, HttpServletResponse res )
{
}
}
• We start off with our typical Servlet.
1
59
public class MySessionServlet extends HttpServlet
{
public void doPost( HttpServletRequest req, HttpServletResponse res )
{
HttpSession session = req.getSession( true );
}
}
• From the request object [req], we are asking it to hand
over any session object it contains. The argument true
means “If you don’t already have a session object
associated with this user, create one. (If we had put false,
that would have meant, “If you don’t find a session
object, don’t create one.” )
• An HttpSession object lives on the server. A user
moving from page to page carries around the primary
key of the HttpSession object that lives on the
server.
1
60
public class MySessionServlet extends HttpServlet
{
public void doPost( HttpServletRequest req, HttpServletResponse res )
{
HttpSession session = req.getSession( true );
MyThang thang = (MyThang)session.getAttribute( “thang” );
}
}
• Here we’re getting something out of the session.
• For this to work, somebody must have already put the
MyThang object into the session.
1
61
public class MySessionServlet extends HttpServlet
{
public void doPost( HttpServletRequest req, HttpServletResponse res )
{
HttpSession session = req.getSession( true );
MyThang thang = (MyThang)session.getAttribute( “thang” );
if( thang != null )
{
// It’s your thang, do what you wanna do…
}
}
}
• If the object we want was not found in the session, then
thang will be null. Always dip your toe in the water
first to see if your object is null. (Otherwise, you’ll throw
a NullPointerException
1
62
public class MySessionServlet extends HttpServlet
{
public void doPost( HttpServletRequest req, HttpServletResponse res )
{
HttpSession session = req.getSession( true );
EmployeeBean emp = (EmployeeBean)session.getAttribute( “empl” );
if( emp != null )
{
String name = emp.getName();
String ssn = emp.getSSN();
}
}
}
This key value “empl” can be
any name you want. But when
you try to pull it out of the
session, you have to use the
same name as when it went in.
• This is the more common approach. You put one big
bean in the session and then pull out the sub1
components.
63
public class MySessionServlet extends HttpServlet
{
public void doPost( HttpServletRequest req, HttpServletResponse res )
{
MyObject mine = new MyObject( “this”, 29, “that” );
HttpSession session = req.getSession( true );
session.setAttribute( “mykey”, mine );
}
}
Here, we created an instance of
MyObject and then placed it in the
session.
We needed to create the name-value
association between the reference to the
MyObject (here called mine) and the
String key we will use later to retrieve it.
• Just as you got
something out of the
session, you can put
things into the session.
• Bear in mind that you erase any previous value (if one
exists) associated with that key1 when you add a new one.
64
First Servlets: Session Tracking
• Now let’s execute a servlet that does this.
1
65
1
66
1
67
First Servlets: Session Tracking
• So, I have:
Compiled the ShowSession servlet
Placed it in the correct directory
What else do I need to do to make this servlet execute?
1
68
First Servlets: Session Tracking
• Register the servlet in the web.xml file!
• This file is found in the WEB-INF directory
1
69
1
70