+ All Categories
Home > Documents > 1 1. 1 2 J2EE Servlets 1 3 Java Executables: Application, Applet, Servlet Servlets: background A...

1 1. 1 2 J2EE Servlets 1 3 Java Executables: Application, Applet, Servlet Servlets: background A...

Date post: 27-Dec-2015
Category:
Upload: lily-collins
View: 239 times
Download: 0 times
Share this document with a friend
70
1 1
Transcript

1 1

1 2

J2EEServlets

1 3

• 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].

1 4

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 5

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 6

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 7

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 8

HTML: forms

1 9

• 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

1 10

• 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

1 11

• 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

1 12

• 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.

1 13

(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

1 14

• 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>

1 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> </HTML>

GetWithTextFields.htm

1 16

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 17

• 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>

1 18

• 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

1 19

First Servlet:

doGet()

1 20

• 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

1 21

• 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

1 22

• 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

1 23

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 24

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.

1 25

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.

1 26

• 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.

1 27

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 28

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()

1 29

• 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

1 30

• 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

1 31

• 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

1 32

First Servlets:

doPost()

1 33

• 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>

1 34

• 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

1 35

• Here we see our html page with the form that triggers the post.

First Servlets: doPost()

SimplePost.htm

ShowParameters

1 36

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 37

First Servlets:

sendRedirect()

1 38

• 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”)

1 39

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 40

• 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.

1 41

• 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.

1 42

First Servlets:

Servlet to Servlet

1 43

• 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

1 44

• 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

1 45

• And here is the ‘SlapServlet’

SlapServlet

First Servlets: Servlet to Servlet

1 46

• What? Why was this “SlapServlet” not found?The path looks correct, as we can see from the directory.In short, everything looks great.

1 47

First Servlets:

Why web.xml is Needed

1 48

• 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

1 49

• Let’s add our SlapServlet to this list and see what happens.

web.xml

First Servlets: Why web.xml is Needed

1 50

• Success! Now we have been able to call a servlet from another servlet.

First Servlets: Why web.xml is Needed

1 51

First Servlets:

Cookies

1 52

• 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.

1 53

• 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 wasplaced in some computer by theNYTimes. If means something onlyto them.

1 54

• 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.

1 55

First Servlets:

Session Tracking

1 56

• 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

1 57

• 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

1 58

• Luckily, the Servlet API has a neat way to solve this problem.

First Servlets: Session Tracking

1 59

public class MySessionServlet extends HttpServlet{ public void doPost( HttpServletRequest req, HttpServletResponse res ) {

} }

• We start off with our typical Servlet.

1 60

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 61

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 62

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 63

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.

1 64

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.

1 65

• Now let’s execute a servlet that does this.

First Servlets: Session Tracking

1 66

1 67

1 68

• So, I have:Compiled the ShowSession servletPlaced it in the correct directory

What else do I need to do to make this servlet execute?

First Servlets: Session Tracking

1 69

• Register the servlet in the web.xml file!• This file is found in the WEB-INF directory

First Servlets: Session Tracking

1 70


Recommended