700 likes | 891 Vues
Java II. J2EE Servlets. 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.
E N D
Java II 1
J2EE Servlets 1
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
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
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
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 javaclassfolder below the webappsfolder means that javaclassmust be made part of the URL path name. The html is located in the javaclassfolder. 1
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
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
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 <AHREF="BasicHtml.htm">hyperlink</A> to <CODE>BasicHtml.htm</CODE>. </BODY> </HTML> 1
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
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
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> </HTML> 1
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> </HTML> 1
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> </HTML> 1
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> 1
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
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
First Servlet: doGet() 1
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
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
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
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. 1
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, HttpServletResponseresponse) 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
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, HttpServletResponseresponse) 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
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
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
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, HttpServletResponseresponse) 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() 1
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
First Servlets: calling a servlet through a link • Now, we will use one of our usual HTML links to execute our HelloWorldHtmlServlet. <HTML> <HEAD> <TITLE>Basic Link</TITLE> </HEAD> <BODY>This link will cause the <AHREF=“http://localhost:8080/javaclass/servlet/HelloWorldHtmlServlet"> HelloWorldHtmlServlet</A> to be called. </BODY> </HTML> BasicLink.htm 1
First Servlets: calling a servlet through a submit • Next, we will execute our HelloWorldHtmlServletservlet in response to a submit button having been pressed.. SubmitButtonCallServlet.htm 1
First Servlets: doPost() 1
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— —we were again executing a doGet(). <BODY>This link will cause the <FORM ACTION=”http://localhost:8080/javaclass/servlet/HelloWorldHtmlServlet"> </FORM> </BODY> 1
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
First Servlets: doPost() • Here we see our html page with the form that triggers the post. SimplePost.htm ShowParameters 1
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); } } 1
First Servlets: sendRedirect() 1
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. This command will tell the server to send the user to the page indicated by the argument of the method. request.sendRedirect( “/javaclass/BadCreditCard.htm”) 1
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. 1
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
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
First Servlets: Servlet to Servlet 1
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
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
First Servlets: Servlet to Servlet • And here is the ‘SlapServlet’ SlapServlet 1
• What? Why was this “SlapServlet” not found? The path looks correct, as we can see from the directory. In short, everything looks great. 1
First Servlets: Why web.xml is Needed 1
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
First Servlets: Why web.xml is Needed • Let’s add our SlapServlet to this list and see what happens. web.xml 1
First Servlets: Why web.xml is Needed • Success! Now we have been able to call a servlet from another servlet. 1