MC06_Servlet - Lecturer EEPIS

indexadjustmentInternet και Εφαρμογές Web

13 Νοε 2013 (πριν από 3 χρόνια και 9 μήνες)

81 εμφανίσεις

1


Mobile Computing



Chapter 6


Distributed System with Java Servlets






2

1.Topics


Introduction to Java Servlets


Generic Servlet API Classes


HTTP Servlet API Classes


Requests and Responses in Servlets


Servlets in the Enterprise

3

2.Introduction to Java Servlets


Servlets work in a client/server model


Also seen as a request
-
response model


Request sent to servlet


Response returned to client


Requests can be sent to servlets in many different
protocols


Any that a standard Web server supports


HTTP(S)


FTP


SMTP

4

Introduction to Java Servlets(Cont’s)


Servlets are used to move processing to the
server


Alter the processing balance


Create n
-
tier distributed applications


Connect to backend databases


Connect to remote objects

5

Introduction to Java Servlets(Cont’s)


Servlets are used to extend the server’s capabilities


Add functionality to server


Regardless of platform


Write servlet once, run anywhere


Create intelligent agents


Monitor systems and update pages

6

3.Using Servlet API Classes


3.1 Generic Servlet Classes


Javax.servlet.GenericServlet


Basic servlet class


Normally subclassed to provida a custom service


Javax.servlet.ServletRequest


Provides information about client’s request


Access client data by reading the client’s input stream


Javax.servlet.ServletResponse


Used to respond to the client


Can send the data using the client’s output stream

7


Generic Servlet Classes(Cont’s)


The basic class for servlet


Provides three major methods for overriding


init()


Called once when the servlet is loaded


public void service(…)


This is where the main work is carried out


Similar usage to run() in multithreading applications


Provides the specialization of your servlet


Called by the Web server on your behalf


destroy()


Called once when the servlet is unloaded and destroyed

8


3.2 HTTP Servlet Classes


javax.servlet.http.HttpServlet


Extends GenericServlet class, adding support for
HTTP protocol


Currently HTTP 1.1


Often used to replace CGI processing


java.servlet.http.HttpServletRequest


Read CGI and form information


Data and variables accessed via input stream


javax.servlet.http.HttpServletResponse


Respond using the client’s output stream


Simply write HTTP protocol information

9

10


Information from the client is provided in the
request

argument


Can get details similar to using CGI on input
stream


Methods to return machine name and IP address


Method to find HTTP method used to send request


GEY


PUT


HEAD


POST


Then use standard
readLine()

to get content


HTTP servlet supplies additional methods for
retrieving data


These can be used instead of
service(…)

11


The methods are designed to handle specific
types of interaction


The following methods are available:


doGet(…)


Handles GET, conditional GET, and HEAD requests


doPost(…)


Handles POST requests


doPut(…)


Handles PUT requests


doDelete(…)


Handles DELETE requests


The parameters for these are identical to those for
service(…)


HTTPServletRequest and HTTPServletResponse

12

4.Requests and Responses in Servlets


Can also get the value of any form data


Use the HttpServletRequest.getParameter(…)
method


Simply pass the name of the data required


Possibly a form field name

13

14


Information to the client is sent via the
response argument


Can open an output stream


Then simply send standard HTTP


Possibly HTML text


All of the underlying plumbing handled for
you


The HttpServletResponse object

15

16

5.Servlets in the Enterprise


Servlets are perfect for use as middleware


They can easily be deployed


Anywhere there is a Web server


Large amount of processing wrapped in classes


HttpServletResponse, HttpServletRequest, etc.


Servlets are easily reusable


True classes that can be extended


Unlike cut
-
and
-
pasted with scripting


Easy to bulid middleware “web” or “lattice”

17


Interaction with data or agents is hidden


Can be changed without client knowledge


Can easily use RMI, CORBA, or JDBC

18


Outputting of HTML makes portable
interfaces


Usable on all browsers


Need to keep to W3C standard


User can change browser technology


No effect on use of your application


Separates presentation of data from rules


Rules are held in the servlet


Presentation handled by the browser

19

6.Web Server


Tomcat Configuration


C:
\
Apps
\
tomcat
\
webapps
\
LabServlet


images


execute.gif, return.gif


WEB
-
INF


Classes (* any class files that you create, including
Servlets and JavaBeans, will be placed in the
directory)


web.xml

(* mapping definition)

20


6.1 Servlet Examples

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class HelloWorldServlet1 extends HttpServlet {




public void doGet(HttpServletRequest request, HttpServletResponse response)



throws IOException, ServletException


{



/* set the content of the response page, which is an HTML page */



response.setContentType("text/html");






/* get the output of the HttpServletResponse */



PrintWriter out = response.getWriter();







21


Servlet Example(Cont’s)



/**




* Output the HTML page




* The page will be wrapped by the HttpServletResponse




* The entire response is then sent to the client who requests it




*/



out.println("<html>");



out.println("<head>");



out.println("<title>ESD &gt; Servlets &gt; Program Testing</title>");



out.println("</head>");



out.println("<body>");



out.println("<h1>ESD &gt; Servlets &gt; Program Testing</h1>");



out.println("<h2>Hello World!!!</h2>");

out.println("<h3>A Servlet is a java class that runs on the server.</h3>");



out.println("</body>");



out.println("</html>");


}

}


22


6.2 Servlet Mapping in web.xml

<!
--

servlet
-

the set up info of a servlet
--
>

<servlet>


<!
--

the name of the servlet
--
>


<servlet
-
name>HelloWorldServlet1</servlet
-
name>


<!
--

the name of the .class file of the servlet
--
>


<servlet
-
class>
HelloWorldServlet1
</servlet
-
class>

</servlet>


<servlet
-
mapping>


<!
--


the name of the servlet (must match with <servlet> above)


--
>


<servlet
-
name>
HelloWorldServlet1
</servlet
-
name>


<!
--


the url pattern for matching the HTTP Requests


--
>


<url
-
pattern>/
HelloWorldServlet1
</url
-
pattern
>

</servlet
-
mapping>


23


Servlet Mapping in web.xml (Cont’s)

<servlet
-
mapping>


<servlet
-
name>HelloWorldServlet1</servlet
-
name>


<url
-
pattern>
*.hello
</url
-
pattern>

</servlet
-
mapping>

<servlet
-
mapping>


<servlet
-
name>HelloWorldServlet1</servlet
-
name>


<url
-
pattern>
/servlet/ HelloWorldServlet1
</url
-
pattern>

</servlet
-
mapping>


The following URL access same servlet program:

http://localhost:8899/
LabServlet
/HelloWorldServlet1

http://localhost:8899/
LabServlet
/anyXXX.hello

http://localhost:8899/
LabServlet
/servlet/HelloWorldServlet

24


25


6.3 Servlet doGet and doPost Example


import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class HelloWorldServlet3 extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse
response)



throws ServletException, IOException {



doPost(request,response);


}

26


Servlet doGet and doPost Example(Cont’s)



protected void doPost(HttpServletRequest request, HttpServletResponse response)




throws ServletException, IOException {



response.setContentType("text/html");



PrintWriter out = response.getWriter();



out.println("<html>");



out.println("<head>");



out.println("<title>");



out.println("ESD &gt; Servlets &gt; Program");



out.println("</title>");



out.println("</head>");



out.println("<body>");



out.println("Hello World! (with doPost()) <br>");



out.println("<form method=
\
"post
\
" action=
\
"
hello3
\
">");



out.println("<input type=
\
"submit
\
" value=
\
"doPost()
\
">");



out.println("</form>");






out.println("</body>");



out.println("</html>");





}

}

27


Servlet Mapping in web.xml


Servlet Mapping in
web.xml


<servlet>


<servlet
-
name>HelloServlet3</servlet
-
name>


<servlet
-
class> HelloWorldServlet3</servlet
-
class>

</servlet>

<servlet
-
mapping>


<servlet
-
name>HelloServlet3</servlet
-
name>


<url
-
pattern>
/hello3
</url
-
pattern>

</servlet
-
mapping>

28


Example: ServletLogin.java

29

import javax.servlet.*;

import javax.servlet.http.*;

/**


* <p>This servlet creates an HTML form to gather a username and


* password, validates the user, then allows the user to access


* other pages.


*/

public class ServletLogin extends HttpServlet

{


public static String USER_KEY = "ServletLogin.user";


public static String FIELD_USER = "username";


public static String FIELD_PASSWORD = "password";


/**


* <p>Performs the HTTP GET operation


*


* @param req The request from the client


* @param resp The response from the servlet


*/

30


public void doGet(HttpServletRequest req,


HttpServletResponse resp)


throws ServletException, java.io.IOException


{


// Set the content type of the response


resp.setContentType("text/html");


// Get the PrintWriter to write the response


java.io.PrintWriter out = resp.getWriter();


// Set the response header to force the browser to


// load the HTML page from the server instead of


// from a cache


resp.setHeader("Expires", "Tues, 01 Jan 1980 00:00:00 GMT");


// Get the URI of this request


String uri = req.getRequestURI();


// Get the current user. If one does not exist, create


// a form to gather the user and password


HttpSession session = req.getSession(true);


String user = (String) session.getValue(USER_KEY);

31


if (user == null) {


// No user
-

create the form to prompt the user


login(out, uri);


return;


}


// Print a standard header


out.println("<html>");


out.println("<head>");


out.println("<title>Wecome</title>");


out.println("</head>");


out.println("<body>");


out.println("<center><h2>Welcome to our site!</h2>");


out.println("<br>");


out.println("More cool stuff coming soon...");


out.println("</center>");


// Wrap up


out.println("</body>");


out.println("</html>");


out.flush();


}

32


/**


* <p>Performs the HTTP POST operation


*


* @param req The request from the client


* @param resp The response from the servlet


*/


public void doPost(HttpServletRequest req,


HttpServletResponse resp)


throws ServletException, java.io.IOException


{


// Set the content type of the response


resp.setContentType("text/html");


// Get the PrintWriter to write the response


java.io.PrintWriter out = resp.getWriter();


// If the user is not yet logged in, validate


HttpSession session = req.getSession(true);


String user = (String) session.getValue(USER_KEY);

33


if (user == null) {


String username = req.getParameter(FIELD_USER);


String password = req.getParameter(FIELD_PASSWORD);


if (!validUser(username, password)) {


out.println("<html>");


out.println("<title>Invalid User</title>");


out.println("<body><center><h2>Invalid User!</h2><br>");


out.println("Press the 'Back' button to try again");


out.println("</center></body></html>");


out.flush();


return;


}


// We've got a valid user now, store the username in


// the session


session.putValue(USER_KEY, username);


}

34


// The current user has been validated.


// Redirect to our main site



resp.sendRedirect("http://localhost:8899" +


req.getRequestURI());

}


/**


* Formats the login page


* @param out The output stream to write the response to


* @param uri The requesting URI


*/

35


protected void login(java.io.PrintWriter out, String uri)


throws java.io.IOException


{


out.println("<html>");


out.println("<head>");


out.println("<title>Login</title>");


out.println("<center><h2>Welcome! Please login</h2>");


out.println("<br><form method=POST action=
\
"" +


uri + "
\
">");


out.println("<table>");


out.println("<tr><td>User ID:</td>");


out.println("<td><input type=text name=" +


FIELD_USER + " size=30></td></tr>");


out.println("<tr><td>Password:</td>");


out.println("<td><input type=password name=" +


FIELD_PASSWORD + " size=10></td></tr>");


out.println("</table><br>");


out.println("<input type=submit value=
\
"Login
\
">");


out.println("</form></center></body></html>");


}

36


/**


* Validates the username and password


* @param username The user name


* @param password The user password


* @return true if the username/password is valid


*/


protected boolean validUser(String username, String password)


{


boolean valid = false;


// Perform a simple check to make sure the user is valid.


if ((username != null) && (username.length() > 0)) {


valid = username.equals(password);


}


return valid;


}

37


/**


* <p>Initialize the servlet. This is called once when the


* servlet is loaded. It is guaranteed to complete before any


* requests are made to the servlet


*


* @param cfg Servlet configuration information


*/


public void init(ServletConfig cfg)


throws ServletException


{


super.init(cfg);


}


/**


* <p>Destroy the servlet. This is called once when the servlet


* is unloaded.


*/


public void destroy()


{


super.destroy();


}

}

38


<servlet>


<servlet
-
name>ServletLogin</servlet
-
name>


<servlet
-
class>ServletLogin</servlet
-
class>


</servlet>



<servlet
-
mapping>


<servlet
-
name>ServletLogin</servlet
-
name>


<url
-
pattern>/servlet/ServletLogin</url
-
pattern>


</servlet
-
mapping>