Servlet
Upcoming SlideShare
Loading in...5
×
 

Servlet

on

  • 898 views

 

Statistics

Views

Total Views
898
Views on SlideShare
898
Embed Views
0

Actions

Likes
0
Downloads
47
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

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

    Servlet Servlet Presentation Transcript

    • Java II--Copyright © 2001-2005 Tom Hunter
    • Java II--Copyright © 2001-2005 Tom HunterJ2EEServlets
    • Java II--Copyright © 2001-2005 Tom Hunter• Java Executables: Application, Applet, ServletServlets: background• A Servlet is a type of Java program that runs only on theserver.• Servlets were introduced in 1998 with J2EE or the Java 2Enterprise Edition.• Servlets are Java’s replacement for CGI [CommonGateway Interface].
    • Java II--Copyright © 2001-2005 Tom HunterServlets: background• Although a normal HTML page executes in a web server,a Servlet needs a special container called a Web ApplicationServer, commonly abbreviated as WAS.• When running inside a WAS, a Servlet sits inside a placecalled a Servlet Container.
    • Java II--Copyright © 2001-2005 Tom HunterServlets: background• A Servlet is only loaded once. Thereafter, a new thread iscreated for every new call to the servlet. This eliminatesmuch of the overhead that plagued CGI.• To begin, our Servlet Container will be a free webapplication server called “Tomcat.”
    • Java II--Copyright © 2001-2005 Tom HunterServlets: understanding Tomcat• Tomcat has a particular directory structure that you mustuse. The webapps directory holds everything theserver will serve up.In our case, there is a javaclass folder.The presence of this javaclass folderbelow the webapps folder means thatjavaclass must be made part of the URLpath name. The html is located in thejavaclass folder.
    • Java II--Copyright © 2001-2005 Tom HunterServlets: understanding the Tomcat web.xml• For a Web Application, there is a special configuration filecalled web.xml that must be located in the WEB-INFdirectory. We will learn more about this file.web.xmlAs you can see, there are noservlets registered yet.
    • Java II--Copyright © 2001-2005 Tom HunterHTML: forms
    • Java II--Copyright © 2001-2005 Tom Hunter• Nearly everyone is familiar with HTMLHTML: 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 needsomething 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 ACTIONspecifies.• Do You notice anything else unusual on this displayedpage?HTML: basic FormsWhen a GET is executed, it will pull in any data that isassociated with the form. The name-value pairs of the formare 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 doessomething 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 InputFields.• Notice the two TEXT INPUT fields have names. Let’swatch 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 HunterHTML: 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 HunterHTML: 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 aPOST.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 differentway.HTML: POST
    • Java II--Copyright © 2001-2005 Tom HunterFirst 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 foreither of two events to happen.• An HTML page executes either aGET or aPOST• When some HTML page executes a GET or a POSTusing the name of a particular Servlet, the Web ApplicationServer responds by executing that Servlet’s doGet() ordoPost() 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 thedoGet() method to do some work for me. I give it twoboxes. The first box [HttpServletRequest] is full with theinformation I want it to work on. The second box[HttpServletResponse] is empty. Any information thatcomprises the response I will expect to find in the secondbox.HttpServletRequest—full when called.HttpServletResponse—empty when first called.First Servlet
    • Java II--Copyright © 2001-2005 Tom Hunterimport java.io.*;import java.text.*;import java.util.*;import javax.servlet.*;import javax.servlet.http.*;public class HelloWorldServlet extends HttpServlet{}Our first step is extendingHttpServlet. By definition, whenwe extend HttpServlet, our class“is a” Servlet.
    • Java II--Copyright © 2001-2005 Tom Hunterimport 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 Thisoverrides the one we inherit from HttpServlet.Note: for the override to succeed, the signatureof our doGet() method must match this oneexactly. That means: method name, argumentsand thrown exceptions.
    • Java II--Copyright © 2001-2005 Tom Hunterimport 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 theresponse box. We are getting a reference toits “writer” and then we are writing plain textto it.
    • Java II--Copyright © 2001-2005 Tom Hunter• Our HelloWorldServlet is located in the classesdirectory.First Servlets: placement of file in Tomcat4.1.24Our servlet is placed inside this“classes” directory.If our class was also in a package,then that path would start withinthe classes directory. Forexample, if our servlet was locatedin: package mypackage1,then the classes directorywould have a directory within itcalled “mypackage1” andinside that directory we wouldfind ourHelloWorldServlet.
    • Java II--Copyright © 2001-2005 Tom HunterFirst Servlets: executing the servlet• To cause our HelloWorldServlet to be executed, we mustplace this on the command line:http://localhost:8080/javaclass/servlet/HelloWorldServletNotice how the output is plain text, notHTML. We can change that easily besetting the content type.
    • Java II--Copyright © 2001-2005 Tom Hunterimport 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 doyour first out.println()
    • Java II--Copyright © 2001-2005 Tom Hunter• For these past two servlets, we have not had to do anyconfiguration—which is not usually the case.Normally, you will need to register your servlet in a specialfile called web.xml.First Servlets: configuring the web.xml fileweb.xmlIf your servlet is located in a package, thenthe entire path must be reflected in the lowerparameter. For example, ifHelloWorldServlet was in thepackage 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 executeour 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 HelloWorldHtmlServletservlet in response to a submit button having been pressed..First Servlets: calling a servlet through a submitSubmitButtonCallServlet.htm
    • Java II--Copyright © 2001-2005 Tom HunterFirst Servlets:doPost()
    • Java II--Copyright © 2001-2005 Tom Hunter• Until now all of our Servlets have been called by doing adoGet()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 theservlet 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 ofthe 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 ourform 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 thepost.First Servlets: doPost()SimplePost.htmShowParameters
    • Java II--Copyright © 2001-2005 Tom Hunterimport 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 HunterFirst 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, adecision needs to be made.For this purpose, we rely on a method that can send the userto a new page depending on what data was entered.This command will tell the server to send the user to the pageindicated by the argument of the method.First Servlets: sendRedirect()request.sendRedirect( “/javaclass/BadCreditCard.htm”)
    • Java II--Copyright © 2001-2005 Tom Hunterimport 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 oran absolute URL are acceptable.
    • Java II--Copyright © 2001-2005 Tom Hunter• This html file “SimplePostWithCheck.htm” willPOST to the CheckParameters ServletFirst Servlets: sendRedirect()Here, you see I am aboutto submit this HTMLform with nothing in thecredit card field.
    • Java II--Copyright © 2001-2005 Tom Hunter• The HTML page POSTs to the Servlet, which does the testand decides whether to send to the success page or the failurepage.First Servlets: sendRedirect()I have made it so this link returns the user to theSimplePostWithCheck.htm page.
    • Java II--Copyright © 2001-2005 Tom HunterFirst 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 causeanother Servlet to be loaded.First Servlets: Servlet to ServletSimplePostWithSlap.htm
    • Java II--Copyright © 2001-2005 Tom Hunter• The HTML page on the previous slide executed a POSTagainst this Servlet, causing this Servlet to execute itsdoPost() method. If the input was bad, we don’t even seethis servlet because it just does the sendRedirect().CheckParametersWithSlapFirst Servlets: Servlet to Servlet
    • Java II--Copyright © 2001-2005 Tom Hunter• And here is the ‘SlapServlet’SlapServletFirst Servlets: Servlet to Servlet
    • Java II--Copyright © 2001-2005 Tom Hunter• What? Why was this “SlapServlet” not found?The path looks correct, as wecan see from the directory.In short, everything looks great.
    • Java II--Copyright © 2001-2005 Tom HunterFirst Servlets:Why web.xml is Needed
    • Java II--Copyright © 2001-2005 Tom Hunter• The answer can be found in that web.xml file Imentioned earlier.• Notice that we have not registered any servlets yet in thisfile. Normally, you would list every Servlet in here.First Servlets: Why web.xml is Neededweb.xml
    • Java II--Copyright © 2001-2005 Tom Hunter• Let’s add our SlapServlet to this list and see what happens.web.xmlFirst Servlets: Why web.xml is Needed
    • Java II--Copyright © 2001-2005 Tom Hunter• Success! Now we have been able to call a servlet fromanother servlet.First Servlets: Why web.xml is Needed
    • Java II--Copyright © 2001-2005 Tom HunterFirst Servlets:Cookies
    • Java II--Copyright © 2001-2005 Tom Hunter• When you go to a regular HTML web page, every time youget a page, you’re anonymous. The server does not rememberthat it just gave you a previous page. Every time you request aweb 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’tremember you from page to page, it would be impossible todo 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 themost common is a Cookie.• A Cookie is a small text file the server places in yourcomputer. It allows the server to remember who you are.For example, this screencapture shows a Cookie that wasplaced in my computer by theNYTimes. If means something onlyto them.
    • Java II--Copyright © 2001-2005 Tom Hunter• However, because of various privacy concerns, it is entirelypossible that users may have disabled cookies.First Servlets: Cookies• In programming for the web, you must be prepared to copewith that—meaning you must be able to remember who auser is from page to page without relying on cookies.
    • Java II--Copyright © 2001-2005 Tom HunterFirst Servlets:Session Tracking
    • Java II--Copyright © 2001-2005 Tom Hunter• Recall that HTTP is a “stateless” protocol, which meansthat every page starts from square one, opening a separateconnection 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 associateswith a session database entry on the server.URL-rewriting—the identity of the user is passed frompage to page in the URL.Hidden form fields—the identity of the user is kept on thepage itself in a form tag the user can’t seeFirst 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) wasappended to the URL. The user is unaware of this.First Servlets: Session Tracking• This URL-rewriting will work even if the user hascookies disabled. Still, with this approach, thesessionid must be appended for every single URLthis 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 thisproblem.First Servlets: Session Tracking
    • Java II--Copyright © 2001-2005 Tom Hunterpublic class MySessionServlet extends HttpServlet{public void doPost( HttpServletRequest req, HttpServletResponse res ){}}• We start off with our typical Servlet.
    • Java II--Copyright © 2001-2005 Tom Hunterpublic 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 handover any session object it contains. The argument truemeans “If you don’t already have a session objectassociated with this user, create one. (If we had put false,that would have meant, “If you don’t find a sessionobject, don’t create one.” )• An HttpSession object lives on the server. A usermoving from page to page carries around the primarykey of the HttpSession object that lives on theserver.
    • Java II--Copyright © 2001-2005 Tom Hunterpublic 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 theMyThang object into the session.
    • Java II--Copyright © 2001-2005 Tom Hunterpublic 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, thenthang will be null. Always dip your toe in the waterfirst to see if your object is null. (Otherwise, you’ll throwa NullPointerException
    • Java II--Copyright © 2001-2005 Tom Hunterpublic 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 bigbean in the session and then pull out the sub-components.This key value “empl” can beany name you want. But whenyou try to pull it out of thesession, you have to use thesame name as when it went in.
    • Java II--Copyright © 2001-2005 Tom Hunterpublic 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 gotsomething out of thesession, you can putthings into the session.Here, we created an instance ofMyObject and then placed it in thesession.We needed to create the name-valueassociation between the reference to theMyObject (here called mine) and theString key we will use later to retrieve it.• Bear in mind that you erase any previous value (if oneexists) 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 directoryFirst Servlets: Session Tracking
    • Java II--Copyright © 2001-2005 Tom Hunter