1 Servlets Part 2 Representation and Management of Data on the Web.

56
1 Servlets Servlets Part 2 Part 2 Representation and Management of Data on the Web
  • date post

    20-Dec-2015
  • Category

    Documents

  • view

    219
  • download

    4

Transcript of 1 Servlets Part 2 Representation and Management of Data on the Web.

Page 1: 1 Servlets Part 2 Representation and Management of Data on the Web.

1

ServletsServletsPart 2Part 2

Representation and Management of Data on the Web

Page 2: 1 Servlets Part 2 Representation and Management of Data on the Web.

2

Servlets and CookiesServlets and Cookies

Cookie Example

Page 3: 1 Servlets Part 2 Representation and Management of Data on the Web.

3

Servlets and CookiesServlets and Cookies

• Java Servlet API provides comfortable mechanisms to handle cookies

• The class javax.servlet.http.Cookie represents a cookie

- Getter methods:

• getName(), getValue(), getPath(), getDomain(), getMaxAge(), getSecure()…

- Setter methods:

• setValue(), setPath(), setDomain(), setMaxAge()…

Page 4: 1 Servlets Part 2 Representation and Management of Data on the Web.

4

Servlets and Cookies (cont)Servlets and Cookies (cont)

• Get the cookies from the service request:

Cookie[] HttpServletRequest.getCookies()

• Add a cookie to the service response:

HttpServletResponse.addCookie(Cookie cookie)

Page 5: 1 Servlets Part 2 Representation and Management of Data on the Web.

5

An ExampleAn Example

<html>

<head><title>Insert your Name</title></head>

<body> <h1>What is your name?</h1>

<form action="welcomeback" method="get">

<p>

<input type="text" name="username" />

<input type="submit" />

</p>

</form>

</body>

</html>

getname.html

Page 6: 1 Servlets Part 2 Representation and Management of Data on the Web.

6

An Example (cont)An Example (cont)

public class WelcomeBack extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException {

String user = req.getParameter("username");

if (user == null) { // Find the "username" cookie

Cookie[] cookies = req.getCookies();

for (int i = 0; cookies != null && i < cookies.length; ++i) {

if (cookies[i].getName().equals("username"))

user = cookies[i].getValue();

}

} else res.addCookie(new Cookie("username", user));

WelcomeBack.java

Page 7: 1 Servlets Part 2 Representation and Management of Data on the Web.

7

An Example (cont)An Example (cont)

if (user == null) // No parameter and no cookie

res.sendRedirect("getname.html");

res.setContentType("text/html");

PrintWriter out = res.getWriter();

out.println("<html><body><h1>Welcome Back " + user

+ "</h1></body></html>");

}

} WelcomeBack.java

Page 8: 1 Servlets Part 2 Representation and Management of Data on the Web.

8

Session Management with Session Management with ServletsServlets

Page 9: 1 Servlets Part 2 Representation and Management of Data on the Web.

9

Session CookiesSession Cookies

Web browser 1

Web server

request request

ServletServlet

id1

response

put cookie id1

response

Create Session

id1

Page 10: 1 Servlets Part 2 Representation and Management of Data on the Web.

10

Session CookiesSession Cookies

Web browser 2

Web server

request request

ServletServlet

id1

response

put cookie id2

response

Create Session

id2id2

Page 11: 1 Servlets Part 2 Representation and Management of Data on the Web.

11

Session CookiesSession Cookies

Web server

request

ServletServlet

id1

response response

request

Cookie: id1

id2

Session read/write

Web browser 1

id1

Page 12: 1 Servlets Part 2 Representation and Management of Data on the Web.

12

Session CookiesSession Cookies

Web server

request

ServletServlet

id1

response response

request

Cookie: id2

id2

Session read/write

Web browser 2

id2

Page 13: 1 Servlets Part 2 Representation and Management of Data on the Web.

13

sessionId list

Page 14: 1 Servlets Part 2 Representation and Management of Data on the Web.

14

Accessing the Session DataAccessing the Session Data

• The session object is represented by the class HttpSession

• Use the methods getSesssion() or getSession(true) of the doXXX request to get the current HttpSession object, or to create one if it doesn’t exist- When a new session is created, the server automatically add a

session cookie to the response

• Use getSession(false) if you do not want to create a new session when no session exists

Page 15: 1 Servlets Part 2 Representation and Management of Data on the Web.

15

HttpSession MethodsHttpSession Methods

• Session data is accessed in a hash-table fashion:

- setAttribute(String name,Object value) - Where is this value stored?

- Object getAttribute(String name)

• More methods:

- removeAttribute, getAttributeNames

- isNew, invalidate, getId

- getCreationTime, getLastAccessedTime

- getMaxInactiveInterval, setMaxInactiveInterval

Page 16: 1 Servlets Part 2 Representation and Management of Data on the Web.

16

Example: A Basic Shopping CartExample: A Basic Shopping Cart

• In the following example a basic shopping cart for an online store is implemented

• The application consists of two Servlets:- Store.java: the main store site

- ShoppingCart.java: handles cart manipulation

Page 17: 1 Servlets Part 2 Representation and Management of Data on the Web.

17

Online-Store ExampleOnline-Store Example

public class Store extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

res.setContentType("text/html");

PrintWriter out = res.getWriter();

out.println("<html><head>"

+ "<link rel=\"stylesheet\" type=\"text/css\""

+ " href=\"cartstyle.css\"/></head><body>");

HttpSession session = req.getSession();

if (session.getAttribute("item-list") == null) {

out.println("<h1>Hello new visitor!</h1>");

session.setAttribute("item-list", new LinkedList());

}

List itemList = (List) session.getAttribute("item-list");

Store.java

Page 18: 1 Servlets Part 2 Representation and Management of Data on the Web.

18

Online-Store Example (cont)Online-Store Example (cont)

out.println("<h2>Your Shopping Cart:</h2><ol>");

for (Iterator it = itemList.iterator(); it.hasNext();)

out.println("<li>" + it.next() + "</li>");

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

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

out.println("<p>Add item:<input name=\"item\" type=\"text\"/>"

+ "<input type=\"submit\" value=\"send\"/></p>"

+ "<p><input type=\"submit\" value=\"empty cart\" "

+ "name=\"clear\"/></p></form>");

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

}

} Store.java

Page 19: 1 Servlets Part 2 Representation and Management of Data on the Web.

19

Online-Store Example (cont)Online-Store Example (cont)

public class ShoppingCart extends HttpServlet {

public void doPost(HttpServletRequest req, HttpServletResponse

res) throws ServletException, IOException {

res.setContentType("text/html");

PrintWriter out = res.getWriter();

List items = (List) req.getSession().getAttribute("item-list");

out.println("<html><head><link rel=\"stylesheet\""

+ " type=\"text/css\" href=\"cartstyle.css\"/>"

+ "</head><body>");

ShoppingCart.java

Page 20: 1 Servlets Part 2 Representation and Management of Data on the Web.

20

Online-Store Example (cont)Online-Store Example (cont)

if (req.getParameter("clear") != null) {

items.clear();

out.println("<h2>Your Shopping Cart is Empty!</h2>");

} else {

String item = req.getParameter("item");

items.add(item);

out.println("<h2>The item <i>" + item +

"</i> was added to your cart.</h2>");

}

out.println("<h2><a href=\"store\">Return to the store</a></h2>");

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

}} ShoppingCart.java

Page 21: 1 Servlets Part 2 Representation and Management of Data on the Web.

21

URL RewritingURL Rewriting

Web browser

Web server

request request

ServletServlet

id1

response response

Create Session

<HTML…>

< A HREF=“servletURL;sessID=id1>”

/<…HTML>

Page 22: 1 Servlets Part 2 Representation and Management of Data on the Web.

22

URL RewritingURL Rewriting

Web server

request

ServletServlet

id1

response response

request

)no cookie(

id2

Session read/write

Web browser 1

GET servletURL;sessID=id1 HTTP/1.0

<HTML…>

<A HREF=“servletURL;sessID=id1>”

/<…HTML>

Page 23: 1 Servlets Part 2 Representation and Management of Data on the Web.

23

Servlet URL RewritingServlet URL Rewriting

• Use the following methods of the doXXX response object to rewrite URLs:- String encodeURL(String url)

• Use for HTML hyperlinks

- String encodeRedirectURL(String url)• Use for HTTP redirections

• These methods contain the logic to determine whether the session ID needs to be encoded in the URL

• For example, if the request has a cookie, then url is returned unchanged

• Some servers implement the two methods identically

Page 24: 1 Servlets Part 2 Representation and Management of Data on the Web.

24

Back to our StoreBack to our Store

• The Store example assumes that the client supports cookies

• To fix the program, we should encode the links we supply:

• Store.java:

"<form method=\"post\" action=\"" +

res.encodeURL("cart") + "\">"

• ShoppingCart.java:

“<a href=\"" + res.encodeURL("store") + "\">"

Page 25: 1 Servlets Part 2 Representation and Management of Data on the Web.

25

The Session ListenerThe Session Listener

• The session listener reacts to the following events:- A new session has been created

- A session is being destroyed

• To obtain a session listener, implement the interface javax.servlet.http.HttpSessionListener

Page 26: 1 Servlets Part 2 Representation and Management of Data on the Web.

26

Session-Listener Example (cont)Session-Listener Example (cont)

public class CartInitializer implements HttpSessionListener {

public void sessionCreated(HttpSessionEvent se) {

List itemList = new LinkedList();

se.getSession().setAttribute("item-list",itemList);

itemList.add("A Free Apple");

}

public void sessionDestroyed(HttpSessionEvent se) {}

} CartInitializer.java

<listener>

<listener-class>CartInitializer</listener-class>

</listener> web.xml

Page 27: 1 Servlets Part 2 Representation and Management of Data on the Web.

27

The Servlet ContextThe Servlet Context

Page 28: 1 Servlets Part 2 Representation and Management of Data on the Web.

28

Uses of ServletContextUses of ServletContext

• For communicating with the Servlet container (e.g., Tomcat server), we use the ServletContext object

• One context is shared among all Web-application Servlets

• Can store Web application initialization parameters

• Can store and manipulate application-shared attributes

• Can be used to access the logger

• Can be used to dispatch requests to other resources

Page 29: 1 Servlets Part 2 Representation and Management of Data on the Web.

29

ServletContext MethodsServletContext Methods

• Access initialization parameters:getInitParameter(String name), getInitParameterNames()

• Read Web-application attributes:getAttribute(String name), getAttributeNames()

• Manipulate Web-application attributes:setAttribute(String, Object), removeAttribute(String)

• Transform context-relative paths to absolute paths:getRealPath(String path), URL getResource(String path)

Page 30: 1 Servlets Part 2 Representation and Management of Data on the Web.

30

ServletContext MethodsServletContext Methods

• Write to the application log:log(String msg), log(String message, Throwable exception)

• Get a resource dispatcher (discussed later): RequestDispatcher getRequestDispatcher(String path)

• Name and version of the Servlet container: String getServerInfo()

Page 31: 1 Servlets Part 2 Representation and Management of Data on the Web.

31

Note about ServletContextNote about ServletContext

• There is a single ServletContext per Web application

• Different Sevlets will get the same ServletContext

object, when calling getServletContext during different sessions

• You can lock the context to protect a critical section from all Web-application accesses

Page 32: 1 Servlets Part 2 Representation and Management of Data on the Web.

32

The Request DispatcherThe Request Dispatcher

Page 33: 1 Servlets Part 2 Representation and Management of Data on the Web.

33

The Request DispatherThe Request Dispather

• The RequestDispatcher object is used to send a a client request to any resource on the server

• Such a resource may be dynamic (e.g. a Servlet or a JSP file) or static (e.g. a HTML document)

• To send a request to a resource x, use:getServletContext().getRequestDispatcher("x")

Page 34: 1 Servlets Part 2 Representation and Management of Data on the Web.

34

Request Dispatcher MethodsRequest Dispatcher Methods

• void forward(ServletRequest request,

ServletResponse response)

- Forwards a request from a Servlet to another resource

• void include(ServletRequest request,

ServletResponse response)

- Includes the content of a resource in the response

Page 35: 1 Servlets Part 2 Representation and Management of Data on the Web.

35

Passing on DataPassing on Data

• 3 different ways to pass parameters for the forwarded Servlet or JSP

- Data that will be used only for this request:

request.setAttribute("key", value);

- Data will be used for this client (also for future requests):

session.setAttribute("key", value);

- Data that will be used in the future for every client

context.setAttribute("key", value);

Page 36: 1 Servlets Part 2 Representation and Management of Data on the Web.

36

An ExampleAn Example

• The Servlet JokesAndImages enables a user to choose a random joke or a random image

• The server has 5 images in the directory images/ and five jokes (txt files) in the directory jokes/

• Empty requests are forwarded to a HTML file that enables the user to choose a joke or an image

• Requests to a joke are forwarded to the servlet Jokes

• Requests to an image are forwarded to a random image from the directory images/

Page 37: 1 Servlets Part 2 Representation and Management of Data on the Web.

37

Jokes and ImagesJokes and Images

<html>

<head><title>Images and Jokes</title></head>

<body>

<h1>Please Select:</h1>

<form method="post" action="JokesAndImages">

<h2>

<input type="submit" name="joke"

value="A Joke" />

<input type="submit" name="image"

value="An Image" />

</h2>

</form>

</body></html> imagesJokesOptions.html

Page 38: 1 Servlets Part 2 Representation and Management of Data on the Web.

38

Jokes and Images (cont)Jokes and Images (cont)

public class JokesAndImages extends HttpServlet {

public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

int randomNum = 1 + Math.abs((new Random()).nextInt() % 5);

if (req.getParameter("joke") != null) {

req.setAttribute("jokeNumber", new Integer(randomNum));

getServletContext().getRequestDispatcher("/Jokes").forward(req,res);

} else if (req.getParameter("image") != null) {

getServletContext().getRequestDispatcher("/images/image" +

randomNum + ".gif").forward(req, res);

} else getServletContext().getRequestDispatcher

("/imagesJokesOptions.html"). forward(req,res);

}

public void doGet ... }} JokesAndImages.java

Page 39: 1 Servlets Part 2 Representation and Management of Data on the Web.

39

Jokes and Images (cont)Jokes and Images (cont)

public class Jokes extends HttpServlet {

public void doPost(HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException {

res.setContentType("text/html");

PrintWriter out = res.getWriter();

out.println("<html><body><h1>A Joke</h1><pre>");

int jokeNum = ((Integer) req.getAttribute("jokeNumber")).intValue();

getServletContext().getRequestDispatcher

("/jokes/joke" + jokeNum + ".txt").include(req, res);

out.println("\n</pre>");

out.println("<a href=\"" + req.getRequestURL() + "\">Back</a>");

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

}} Jokes.java

Page 40: 1 Servlets Part 2 Representation and Management of Data on the Web.

40

Forwarding versus RedirectionForwarding versus Redirection

• SendRedirect requires extra communication on part of the client: Why?

• By default, SendRedirect does not preserve parameters of the request

• SendRedirect ends up with a different URL on the client

• Which image will be loaded in the following scenario? Servlet /a forwards to /jokes/joke1.html and joke1.html includes <img src="image1.gif".../>

Page 41: 1 Servlets Part 2 Representation and Management of Data on the Web.

41

Programmatic Security Programmatic Security with Servletswith Servlets

Page 42: 1 Servlets Part 2 Representation and Management of Data on the Web.

42

Programmatic-Security MethodsProgrammatic-Security Methods

• Servlet API contains several accessories for handling

programmatic security:

- getRemoteUser()

- isUserInRole(String role)

- getAuthType()

• These are all methods of HttpServletRequest

• To enable user authentication (even for public URLs),

provide a link to some protected page

Page 43: 1 Servlets Part 2 Representation and Management of Data on the Web.

43

An Example: Security Constraints An Example: Security Constraints in web.xmlin web.xml

<security-constraint>

<web-resource-collection>

<web-resource-name>Firm People</web-resource-name>

<url-pattern>/login.html</url-pattern>

</web-resource-collection>

<auth-constraint>

<role-name>employees</role-name>

<role-name>managers</role-name>

</auth-constraint>

</security-constraint> web.xml

Page 44: 1 Servlets Part 2 Representation and Management of Data on the Web.

44

<login-config>

<auth-method>FORM</auth-method>

<form-login-config>

<form-login-page>/login</form-login-page>

<form-error-page>/login?fail=fail</form-error-page>

</form-login-config>

</login-config>

<security-role>

<role-name>managers</role-name>

</security-role>

<security-role>

<role-name>employees</role-name>

</security-role> web.xml

An Example: Security Constraints An Example: Security Constraints in web.xmlin web.xml

Page 45: 1 Servlets Part 2 Representation and Management of Data on the Web.

45

public class FirmServlet extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

res.setContentType("text/html");

PrintWriter out = res.getWriter();

out.println("<html><head><title>Firm</head><body>");

out.println("<h1>Hello.</h1>");

String username = req.getRemoteUser();

if(username==null) {

out.println("<p><img src=\"images/visitor.gif\"/></p>");

out.println("<h3><a href=\"login.html\">Login</a></h3>");

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

return; } FirmServlet

Page 46: 1 Servlets Part 2 Representation and Management of Data on the Web.

46

if(req.isUserInRole("employees")) {

out.println("<p><img src=\"images/employee.gif\"/></p>");

out.print("<h2>Welcome Employee " + username + "!</h2>");

}

if(req.isUserInRole("managers")) {

out.println("<p><img src=\"images/manager.gif\"/></p>");

out.print("<h2>Executive average salary: 42764NIS!</h2>");

}

out.print("<h3><a href=\"endsession\">Log Out</a></h3>");

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

}

} FirmServlet

Page 47: 1 Servlets Part 2 Representation and Management of Data on the Web.

47

public class LoginServlet extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

PrintWriter out = res.getWriter();

res.setContentType("text/html");

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

if(req.getParameter("fail")!=null)

out.print("<h2>Login Failed. Try Again.</h2>");

out.println("<form action=\"j_security_check\" method=\"post\">" +

"<p>Login: <input type=\"text\" name=\"j_username\"/></p>" +

"<p>Password: <input type=\"password\" name=\"j_password\"/></p>" +

"<p><input type=\"submit\" value=\"Log In\"/></p>" +

"</form></body></html>");

} LoginServlet.java

Page 48: 1 Servlets Part 2 Representation and Management of Data on the Web.

48

public void doPost(HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException {

this.doGet(req,res);

}

} LoginServlet.java

<servlet>

<servlet-name>Login</servlet-name>

<servlet-class>LoginServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>Login</servlet-name>

<url-pattern>/login</url-pattern>

</servlet-mapping> web.xml

Page 49: 1 Servlets Part 2 Representation and Management of Data on the Web.

49

public class EndSession extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException {

HttpSession session = req.getSession(false);

if(session!=null)

session.invalidate();

res.sendRedirect("firm");

}

} EndSession.java <servlet>

<servlet-name>EndSession</servlet-name>

<servlet-class>EndSession</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>EndSession</servlet-name>

<url-pattern>/endsession</url-pattern>

</servlet-mapping> web.xml

Page 50: 1 Servlets Part 2 Representation and Management of Data on the Web.

50

FiltersFilters

Page 51: 1 Servlets Part 2 Representation and Management of Data on the Web.

51

Filters in Servlet APIFilters in Servlet API

• Filters are used to dynamically intercept requests and responses

• A filter that applies to a URL u typically acts as follows given a request for u- performs some actions before the processing of u

- passes the request handling to the next filter

- performs some actions after the processing of u

Page 52: 1 Servlets Part 2 Representation and Management of Data on the Web.

52

Filter 1

Request Response

Filter 2

Filter 3

Servlet/JSP/HTML

Client

Container

Page 53: 1 Servlets Part 2 Representation and Management of Data on the Web.

53

public final class FilterExample implements Filter {

public void init(FilterConfig filterConfig) throws ServletException {

... }

public void destroy() {

... }

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

... chain.doFilter(request, response);

... }} FilterExample.java

Page 54: 1 Servlets Part 2 Representation and Management of Data on the Web.

54

<filter>

<filter-name>Example Filter</filter-name>

<filter-class>FilterExample</filter-class>

</filter>

<filter-mapping>

<filter-name>Example Filter</filter-name>

<url-pattern>/images/*</url-pattern>

</filter-mapping>

Registering a FilterRegistering a Filter

web.xml

Page 55: 1 Servlets Part 2 Representation and Management of Data on the Web.

55

What Can we Do with Filters?What Can we Do with Filters?

• Examine and log requests

• Modify request headers and properties

• Modify the response headers and response data - E.g., by replacing the response with a wrapper

- Content compression

- Image conversion

• Block requests

• And more...

Page 56: 1 Servlets Part 2 Representation and Management of Data on the Web.

56

Notes About FiltersNotes About Filters

• The order of the filters in the chain is the same as the order that filter mappings appear web.xml

• The life cycle of filters is similar to that of Servlets

• Filters typically do not themselves create responses, although they can

• The request and response arguments of doFilter are actually of type HttpServletRequest and HttpServletResponse

• The filterConfig is used to read initialization parameters- Those are set in web.xml