Servlets
Upcoming SlideShare
Loading in...5
×
 

Servlets

on

  • 1,802 views

 

Statistics

Views

Total Views
1,802
Views on SlideShare
1,802
Embed Views
0

Actions

Likes
0
Downloads
62
Comments
0

0 Embeds 0

No embeds

Accessibility

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Servlets Servlets Presentation Transcript

  • Java II--Copyright © 2001-2005 Tom Hunter
  • Java II--Copyright © 2001-2005 Tom Hunter J2EE Servlets
  • Java II--Copyright © 2001-2005 Tom Hunter • Java Executables: Application, Applet, Servlet Servlets: background • 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].
  • Java II--Copyright © 2001-2005 Tom Hunter 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.
  • Java II--Copyright © 2001-2005 Tom Hunter 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.”
  • Java II--Copyright © 2001-2005 Tom Hunter 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.
  • Java II--Copyright © 2001-2005 Tom Hunter 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.
  • Java II--Copyright © 2001-2005 Tom Hunter HTML: forms
  • Java II--Copyright © 2001-2005 Tom Hunter • Nearly everyone is familiar with HTML HTML: basic HTML <HTML> <HEAD> <TITLE>This is raw html</TITLE> </HEAD> <BODY> This is the part that displays in the page. </BODY> </HTML> BasicHtml.htm
  • Java II--Copyright © 2001-2005 Tom Hunter • The simplest way to trigger an action is through a hyperlink. HTML: basic Links <HTML> <HEAD> <TITLE>Basic Link</TITLE> </HEAD> <BODY> This is a <A HREF="BasicHtml.htm">hyperlink</A> to <CODE>BasicHtml.htm</CODE>. </BODY> </HTML> BasicLink.htm
  • Java II--Copyright © 2001-2005 Tom Hunter • 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. HTML: basic Forms <HTML> <HEAD> <TITLE>This is raw html</TITLE> </HEAD> <BODY> <FORM ACTION="BasicHtml.htm"> <INPUT TYPE="SUBMIT"> </FORM> </BODY> </HTML> SubmitButtonForm.htm
  • Java II--Copyright © 2001-2005 Tom Hunter • The result of the Submit is doing what the ACTION specifies. • Do You notice anything else unusual on this displayed page? HTML: basic Forms 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.
  • Java II--Copyright © 2001-2005 Tom Hunter (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. HTML: GET <HTML> <HEAD> <TITLE>GET html</TITLE> </HEAD> <BODY> <FORM ACTION="BasicHtml.htm"> <INPUT TYPE="SUBMIT"> </FORM> </BODY> </HTML> SubmitButtonForm.htm
  • Java II--Copyright © 2001-2005 Tom Hunter • 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: 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> </HTML>
  • Java II--Copyright © 2001-2005 Tom Hunter 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> </HTML> GetWithTextFields.htm
  • Java II--Copyright © 2001-2005 Tom Hunter 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> </HTML>
  • Java II--Copyright © 2001-2005 Tom Hunter • 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: POST <HTML> <HEAD> <TITLE>This is raw html</TITLE> </HEAD> <BODY> <FORM METHOD=“POST” ACTION="BasicHtml.htm"> <INPUT TYPE="SUBMIT"> </FORM> </BODY> </HTML>
  • Java II--Copyright © 2001-2005 Tom Hunter • 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. HTML: POST
  • Java II--Copyright © 2001-2005 Tom Hunter First Servlet: doGet()
  • Java II--Copyright © 2001-2005 Tom Hunter • 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. First Servlet
  • Java II--Copyright © 2001-2005 Tom Hunter • 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. First Servlet
  • Java II--Copyright © 2001-2005 Tom Hunter • 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. First Servlet
  • Java II--Copyright © 2001-2005 Tom Hunter import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import 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.
  • Java II--Copyright © 2001-2005 Tom Hunter import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import 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.
  • Java II--Copyright © 2001-2005 Tom Hunter import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import 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.
  • Java II--Copyright © 2001-2005 Tom Hunter • Our HelloWorldServlet is located in the classes directory. First Servlets: placement of file in Tomcat4.1.24 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.
  • Java II--Copyright © 2001-2005 Tom Hunter 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.
  • Java II--Copyright © 2001-2005 Tom Hunter import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorldHtmlServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType( “text/html” ); 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>” ); } } You must set this before you do your first out.println()
  • Java II--Copyright © 2001-2005 Tom Hunter • 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. First Servlets: configuring the web.xml file 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
  • Java II--Copyright © 2001-2005 Tom Hunter • Now, we will use one of our usual HTML links to execute our HelloWorldHtmlServlet. First Servlets: calling a servlet through a link <HTML> <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> BasicLink.htm
  • Java II--Copyright © 2001-2005 Tom Hunter • Next, we will execute our HelloWorldHtmlServlet servlet in response to a submit button having been pressed.. First Servlets: calling a servlet through a submit SubmitButtonCallServlet.htm
  • Java II--Copyright © 2001-2005 Tom Hunter First Servlets: doPost()
  • Java II--Copyright © 2001-2005 Tom Hunter • 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— —we were again executing a doGet(). First Servlets: doPost() <BODY>This link will cause the <FORM ACTION=”http://localhost:8080/javaclass/servlet/HelloWorldHtmlServlet"> </FORM> </BODY>
  • Java II--Copyright © 2001-2005 Tom Hunter • 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: First Servlets: doPost() <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> SimplePost.htm
  • Java II--Copyright © 2001-2005 Tom Hunter • Here we see our html page with the form that triggers the post. First Servlets: doPost() SimplePost.htm ShowParameters
  • Java II--Copyright © 2001-2005 Tom Hunter import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import 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); } }
  • Java II--Copyright © 2001-2005 Tom Hunter First Servlets: sendRedirect()
  • Java II--Copyright © 2001-2005 Tom Hunter • 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. This command will tell the server to send the user to the page indicated by the argument of the method. First Servlets: sendRedirect() request.sendRedirect( “/javaclass/BadCreditCard.htm”)
  • Java II--Copyright © 2001-2005 Tom Hunter import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; 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); } } This is known as a “relative URL”. Either a relative or an absolute URL are acceptable.
  • Java II--Copyright © 2001-2005 Tom Hunter • This html file “SimplePostWithCheck.htm” will POST to the CheckParameters Servlet First Servlets: sendRedirect() Here, you see I am about to submit this HTML form with nothing in the credit card field.
  • Java II--Copyright © 2001-2005 Tom Hunter • The HTML page POSTs to the Servlet, which does the test and decides whether to send to the success page or the failure page. First Servlets: sendRedirect() I have made it so this link returns the user to the SimplePostWithCheck.htm page.
  • Java II--Copyright © 2001-2005 Tom Hunter First Servlets: Servlet to Servlet
  • Java II--Copyright © 2001-2005 Tom Hunter • 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. First Servlets: Servlet to Servlet SimplePostWithSlap.htm
  • Java II--Copyright © 2001-2005 Tom Hunter • 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 First Servlets: Servlet to Servlet
  • Java II--Copyright © 2001-2005 Tom Hunter • And here is the ‘SlapServlet’ SlapServlet First Servlets: Servlet to Servlet
  • Java II--Copyright © 2001-2005 Tom Hunter • What? Why was this “SlapServlet” not found? The path looks correct, as we can see from the directory. In short, everything looks great.
  • Java II--Copyright © 2001-2005 Tom Hunter First Servlets: Why web.xml is Needed
  • Java II--Copyright © 2001-2005 Tom Hunter • 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. First Servlets: Why web.xml is Needed web.xml
  • Java II--Copyright © 2001-2005 Tom Hunter • Let’s add our SlapServlet to this list and see what happens. web.xml First Servlets: Why web.xml is Needed
  • Java II--Copyright © 2001-2005 Tom Hunter • Success! Now we have been able to call a servlet from another servlet. First Servlets: Why web.xml is Needed
  • Java II--Copyright © 2001-2005 Tom Hunter First Servlets: Cookies
  • Java II--Copyright © 2001-2005 Tom Hunter • 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. First Servlets: Cookies • 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.
  • Java II--Copyright © 2001-2005 Tom Hunter • A “session” is a way to remember you from page to page. First Servlets: Cookies • 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 my computer by the NYTimes. If means something only to them.
  • Java II--Copyright © 2001-2005 Tom Hunter • However, because of various privacy concerns, it is entirely possible that users may have disabled cookies. First Servlets: 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.
  • Java II--Copyright © 2001-2005 Tom Hunter First Servlets: Session Tracking
  • Java II--Copyright © 2001-2005 Tom Hunter • 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 First Servlets: Session Tracking
  • Java II--Copyright © 2001-2005 Tom Hunter • 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. First Servlets: Session Tracking • 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. <INPUT TYPE=“HIDDEN” NAME=“session” VALUE=“…”> Hidden Form Field
  • Java II--Copyright © 2001-2005 Tom Hunter • Luckily, the Servlet API has a neat way to solve this problem. First Servlets: Session Tracking
  • Java II--Copyright © 2001-2005 Tom Hunter public class MySessionServlet extends HttpServlet { public void doPost( HttpServletRequest req, HttpServletResponse res ) { } } • We start off with our typical Servlet.
  • Java II--Copyright © 2001-2005 Tom Hunter 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.
  • Java II--Copyright © 2001-2005 Tom Hunter 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.
  • Java II--Copyright © 2001-2005 Tom Hunter 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
  • Java II--Copyright © 2001-2005 Tom Hunter 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 is the more common approach. You put one big bean in the session and then pull out the sub- components. 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.
  • Java II--Copyright © 2001-2005 Tom Hunter 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 ); } } • Just as you got something out of the session, you can put things into the session. 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. • Bear in mind that you erase any previous value (if one exists) associated with that key when you add a new one.
  • Java II--Copyright © 2001-2005 Tom Hunter • Now let’s execute a servlet that does this. First Servlets: Session Tracking
  • Java II--Copyright © 2001-2005 Tom Hunter
  • Java II--Copyright © 2001-2005 Tom Hunter
  • Java II--Copyright © 2001-2005 Tom Hunter • 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? First Servlets: Session Tracking
  • Java II--Copyright © 2001-2005 Tom Hunter • Register the servlet in the web.xml file! • This file is found in the WEB-INF directory First Servlets: Session Tracking
  • Java II--Copyright © 2001-2005 Tom Hunter