Managing Data on the World Wide-Web

Similar documents
Ch-03 Web Applications

Arjun V. Bala Page 20

JSP. Common patterns

Principles and Techniques of DBMS 5 Servlet

Java EE Introduction, Content. Component Architecture: Why and How Java EE: Enterprise Java

Servlet and JSP Filters

PA165 - Lab session - Web Presentation Layer

CHAPTER 9: SERVLET AND JSP FILTERS

Listeners se es. Filters and wrappers. Request dispatchers. Advanced Servlets and JSP

Java Servlet Tutorial. Java Servlet Tutorial

Servlet 3.0. Alexis Moussine-Pouchkine. mercredi 13 avril 2011

Java Servlet 3.0. Rajiv Mordani Spec Lead

chapter 3Chapter 3 Advanced Servlet Techniques Servlets and Web Sessions Store Information in a Session In This Chapter

2.8. Session management

SSC - Web applications and development Introduction and Java Servlet (II)

CONTROLLING WEB APPLICATION BEHAVIOR WITH

Piotr Nowicki's Homepage. Java EE 6 SCWCD Mock Exam. "Simplicity is the ultimate sophistication." Important!

Session Tracking Customized Java EE Training:

Creating Java EE Applications and Servlets with IntelliJ IDEA

ACM Crossroads Student Magazine The ACM's First Electronic Publication

Controlling Web Application Behavior

Please send your comments to:

Java EE 6 New features in practice Part 3

Web Container Components Servlet JSP Tag Libraries

Visa Checkout September 2015

Anders Møller & Michael I. Schwartzbach 2006 Addison-Wesley

CSc31800: Internet Programming, CS-CCNY, Spring 2004 Jinzhong Niu May 9, Java Servlets

Java 2 Web Developer Certification Study Guide Natalie Levi

INTRODUCTION TO WEB TECHNOLOGY

An introduction to web programming with Java

ANTAL Margit. Sapientia - EMTE, Pannon Forrás,,Egységes erdélyi felnőttképzés a

A detailed walk through a CAS authentication

Java Technologies. Lecture X. Valdas Rapševičius. Vilnius University Faculty of Mathematics and Informatics

Servlets. Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun

Web Development in Java Live Demonstrations (Live demonstrations done using Eclipse for Java EE 4.3 and WildFly 8)

Aspects of using Hibernate with CaptainCasa Enterprise Client

Liferay Enterprise ecommerce. Adding ecommerce functionality to Liferay Reading Time: 10 minutes

White Paper March 1, Integrating AR System with Single Sign-On (SSO) authentication systems

Introduction to J2EE Web Technologies

Tomcat Servlet/JSP Reference Implementation

Java Web Programming. Student Workbook

Database Applications Recitation 10. Project 3: CMUQFlix CMUQ s Movies Recommendation System

Application Security

Supporting Multi-tenancy Applications with Java EE

Creating A Walking Skeleton

Pure server-side Web Applications with Java, JSP. Application Servers: the Essential Tool of Server-Side Programming. Install and Check Tomcat

}w!"#$%&'()+,-./012345<ya

Complete Java Web Development

Get Success in Passing Your Certification Exam at first attempt!

Web Application Programmer's Guide

The Server.xml File. Containers APPENDIX A. The Server Container

COMP9321 Web Applications Engineering: Java Servlets

Developing an EJB3 Application. on WebSphere 6.1. using RAD 7.5

Java and Web. WebWork

You Are Hacked End-to-End Java EE Security in Practice. Karthik Shyamsunder, Principal Technologist Phani Pattapu, Engineer

Exam Prep. Sun Certified Web Component Developer (SCWCD) for J2EE Platform

Managed Beans II Advanced Features

Course Name: Course in JSP Course Code: P5

Web Applications. For live Java training, please see training courses at

INSIDE SERVLETS. Server-Side Programming for the Java Platform. An Imprint of Addison Wesley Longman, Inc.

DTS Web Developers Guide

Java Web Security Antipatterns

CIS 455/555: Internet and Web Systems

2. Follow the installation directions and install the server on ccc

11.1 Web Server Operation

Ehcache Web Cache User Guide. Version 2.9

Pierce County IT Department GIS Division Xuejin Ruan Dan King

Java Server Pages combined with servlets in action. Generals. Java Servlets

Java Servlet Specification Version 2.3

Tableau Server Trusted Authentication

Web Server Manual. Mike Burns Greg Pettyjohn Jay McCarthy November 20, 2006

Implementing the Shop with EJB

Class Focus: Web Applications that provide Dynamic Content

Web Applications and Struts 2

How To Understand The Architecture Of Java 2Ee, J2Ee, And J2E (Java) In A Wordpress Blog Post

Configure a SOAScheduler for a composite in SOA Suite 11g. By Robert Baumgartner, Senior Solution Architect ORACLE

Multiple vulnerabilities in Apache Foundation Struts 2 framework. Csaba Barta and László Tóth

Semantic based Web Application Firewall (SWAF V 1.6) Operations and User Manual. Document Version 1.0

Outline. Lecture 9: Java Servlet and JSP. Servlet API. HTTP Servlet Basics

Manual. Programmer's Guide for Java API

How to use JavaMail to send

Keycloak SAML Client Adapter Reference Guide

Intellicus Single Sign-on

Web Applications. Originals of Slides and Source Code for Examples:

Overview of Web Services API

Web Application Development

WebSphere and Message Driven Beans

Secure Testing Service

Model-View-Controller. and. Struts 2

IBM WebSphere Application Server

Transcription:

Managing Data on the World Wide-Web Sessions, Listeners, Filters, Shopping Cart Elad Kravi 1

Web Applications In the Java EE platform, web components provide the dynamic extension capabilities for a web server Web components for example: Java servlets, JSP pages 2

Scope Objects Web components share information by means of objects that are maintained as attributes of four scope objects We can access these attributes by using the getattribute and setattribute methods of the class representing the scope 3

Scope Objects Scope Object Class Accessible From Web context javax.servlet.servletcontext Web components within a web context Session javax.servlet.http.httpsession Web components handling a request that belongs to the session Request Subtype of javax.servlet.servletrequest Web components handling the request Page javax.servlet.jsp.jspcontext The JSP page that creates the object 4

Overview 1 2 3 4 Sessions Listeners Filters Shopping Cart 5

Sessions - Introduction Many applications require that a series of requests from a client be associated with one another For example, a web application can save the state of a user's shopping cart across requests Because HTTP is stateless, web-based applications are responsible for maintaining such state, called a session 6

Maintaining Sessions with Cookies 1. The client sends a request to the server 2. The server generates a new session id Client 3. The response from the server contains a directive to the browser to store a cookie saying the session id is 3 3 Does the server keep the session object forever? The following requests from the client will include session id 3 and then can be associated with one another by the server Server Session table 7

Servlets and Sessions Java s servlets provide an API for managing sessions Sessions are represented by an HttpSession object The getsession() method returns the current session associated with a request object if the request does not have a session, it creates one 8

Example protected void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getsession(); List<String> shoppingcart = List<String>) session.getattribute("cart"); if (shoppingcart == null) { shoppingcart = new ArrayList<String>(); session.setattribute("cart", shoppingcart); } shoppingcart.add(request.getparameter("item")); } response.getwriter().append("my cart: ").append(shoppingcart.tostring()); 9

HttpSession - Methods getattribute(string name) Returns the object bound with the specified name in this session setattribute(string name, Object value) Binds an object to this session, using the name specified removeattribute(string name) Removes the object bound with the specified name from this session invalidate() Invalidates this session 10

Controlling Session Timeouts Due to inactivity, sessions can be invalidated by the server Programmatically: session.setmaxinactiveinterval(int seconds) Declaratively (web.xml) <session-config> <session-timeout>180</session-timeout><!--minutes--> </session-config> Negative value means the session will never expire 11

Overview 1 2 3 4 Sessions Listeners Filters Shopping Cart 12

Listeners Servlet API provides a way to track key events in your Web applications through event listeners Examples of such events: initialization/shutdown of the application, creation of a session This functionality allows more efficient resource management and automated processing based on event status 13

Event Levels and Types There are two levels of servlet events: Servlet context / application - level event Session-level event Each of these two levels has two event categories: Lifecycle changes (e.g., session invalidation) Attribute changes (e.g., addition of servlet context attributes) 14

Common Listener Types For each type of a listener there is a corresponding Java interface ServletContextListener web application initialized / shut down ServletRequestListener request handler starting / finishing HttpSessionListener session created / invalidated ServletContextAttributeListener context attribute added / removed / replaced HttpSessionAttributeListener session attribute added / removed / replaced 15

Managing DB Connection with Listeners We can create a listener to manage database connections When the application is initialized, the listener logs in to the database and stores the connection object in the servlet context Prior to application shutdown, the listener closes the database connection 16

Using Listeners Listeners can be registered in web.xml or by using the @WebListener annotation (Servlet 3.0) Registration in web.xml: <listener> <listener-class>sessionmonitor</listener-class> <listener> 17

Example In the next slides we will see an example of a listener that monitors the current and maximum number of active sessions Our class implements both HttpSessionListener and ServletContextListener That is, the listener is notified when the application is initialized and when a session is created or invalidated 18

@WebListener public class SessionMonitor implements HttpSessionListener, ServletContextListener { public void contextinitialized(servletcontextevent ctxevent) { ServletContext ctx = ctxevent.getservletcontext(); ctx.setattribute("sessions_active", 0); ctx.setattribute("sessions_max", 0); } public void contextdestroyed(servletcontextevent ctxevent) {}... (next slide) 19

public void sessioncreated(httpsessionevent sessionevent) { ServletContext ctx = sessionevent.getsession().getservletcontext(); int active = (int) ctx.getattribute("sessions_active"); int max = (int) ctx.getattribute("sessions_max"); active++; if (active > max) { max = active; ctx.setattribute("sessions_max", max); } } ctx.setattribute("sessions_active", active); public void sessiondestroyed(httpsessionevent sessionevent) { ServletContext ctx = sessionevent.getsession().getservletcontext(); int active = (int) ctx.getattribute("sessions_active"); } } active--; ctx.setattribute("sessions_active", active); 20

Overview 1 2 3 4 Sessions Listeners Filters Shopping Cart 21

Filters A filter is an object that performs filtering tasks on either the request to a resource (a servlet or static content), or on the response from a resource (or both) The main tasks of filters: Query the request and act accordingly Block the request/response from passing any further Modify the request/response headers and data Interact with external resources 22

Filters - Examples Authentication Filters Logging and Auditing Filters Image conversion Filters Data compression Filters Encryption Filters Tokenizing Filters Filters that trigger resource access events XSL/T filters Mime-type chain Filter 23

Filters The @WebFilter annotation is used to define a filter in a web application Classes annotated with this annotation must implement the javax.servlet.filter interface Filters perform filtering in the dofilter method dofilter(servletrequest request, ServletResponse response, FilterChain chain) The FilterChain object allows the Filter to pass on the request and response to the next filter in the chain 24

@WebFilter( filtername = "LogFilter", urlpatterns = {"/*"}, initparams = { @WebInitParam(name = "param1", value = "some value") } ) public class LogFilter implements Filter { public void init(filterconfig config) throws ServletException { // Get init parameter and log it String param1 = config.getinitparameter("param1"); System.out.println("Test Param: " + param1); } public void destroy() { //add code to release any resource }... (next slide) 25

... public void dofilter(servletrequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; // Get the IP address of client machine and log it. String ipaddress = request.getremoteaddr(); System.out.println("IP " + ipaddress + ", Time " + new Date().toString()); } } // Continue calling the rest of the filters and // eventually the servlet chain.dofilter(req, res); 26

Filter Chain A web resource can be filtered by a chain of zero, one, or more filters in a specific order To define execution order of filters, the filters must by declared by using web.xml (not possible with annotations only) A FilterChain is an object provided by the servlet container to the developer The developer is then provided with a view into the invocation chain which he can utilize for his needs 27

Filter Chain public void dofilter(servletrequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // do pre-servlet work here // Continue calling the rest of the filters and eventually the servlet chain.dofilter(request, response); } // do post servlet work here 28

Filter Configuration in web.xml <filter> <filter-name>logfilter</filter-name> <filter-class>mypackage.logfilter</filter-class> <init-param> <!-- optional --> <param-name>param1</param-name> <param-value>some value</param-value> </init-param> </filter> <filter-mapping> <filter-name>logfilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> The execution order of filters is determined by the order of the filter-mapping elements in web.xml 29

Filters or Listeners? Filters are used for monitoring/modifying requests/responses Use a Filter if you want to intercept on HTTP requests matching a specific URL pattern Listeners are used for listening to events in a web containers Use a Listener if you want to intercept changes in the lifecycle of objects 30

Overview 1 2 3 4 Sessions Listeners Filters Shopping Cart 31

Shopping Cart example We will now analyze a web application implementing shopping cart Requirements: add/remove single product to/from the cart remove all the products from the cart view cart state future: start with some initial products (think about weekly shopping list in the grocery store) 32

Implementation with Sessions Server creates new session for each new client The client can call add/remove/remove all on server in each request the client attaches his id in a cookie Server identifies the client by the cookie and updates his cart how can the cart be saved? The client can view the cart s content at anytime In this solution cart is attached to session and not to an account 33

@WebServlet("/ShoppingCart") public class ShoppingCart extends HttpServlet { private static final long serialversionuid = 1L; @SuppressWarnings("unchecked") private Collection<String> getitems(httpsession session) { Collection<String> items = (Collection<String>)session.getAttribute("items"); return items!= null? items : new ArrayList<String>(); } private String createhtmlitemstable(iterable<string> items) { StringBuilder builder = new StringBuilder("<table>"); for (String item : items) { builder.append("<tr><td>"); builder.append(item); builder.append("</td></tr>"); } } builder.append("</table>"); return builder.tostring();... (next page) 34

protected void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { String item = request.getparameter("item"); HttpSession session = request.getsession(); Collection<String> items = getitems(session); items.add(item); session.setattribute("items", items); response.getoutputstream().println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/tr/html4/loose.dtd\">" + "<html>" + "<head>" + "<meta http-equiv=\"content-type\" content=\"text/html; charset=windows- 1255\">" + "<title>shopping Cart</title>" + "</head>" + "<body>" + "<h1>your Shopping Cart Constains:</h1>" + createhtmlitemstable(items) + } ); "</body>" + "</html>" 35

Pros. & Cons. of Session approach Pros. easy to implement widely supported Cons. how many sessions can we save? does that limit number of clients we can serve? does sessions have timeout? what happens if a user doesn t use his browser for an hour? a week? what happens if the client s browser crashes? reset the cookie after login can we start with half full cart? 36

Saving the Cart Where should the cart be saved? in memory? how many clients we can serve? what if we want to distribute the server? what about same client connecting from different browsers simultaneously? in DB? latency handling scale is complex 37

Implementation with REST After authentication phase, the server can identify the user by a cookie sent with a request Cart state is represented by URL only /cart/item/5/item/12 adding/removing item, simply by changing url /cart/item/5 removing all items: /cart/ browsing while saving the state /shop/dairy/cart/item/5/item/12 /cart/item/5/item/12/item/13 starting with half full cart just by changing the url 38

Pros. & Cons. of REST approach Pros. client can start from scratch in new browser just copy the url easy and flexible change cart state Cons. does /cart/item/5/item/12 and /cart/item/12/item/5 refers to the same cart? we can sort the items by id complex URLs think about cart with 100 products 39

References The Java EE Tutorial: https://docs.oracle.com/javaee/7/tutorial/partwebti er.htm 40