COMP 321 Week 13. Overview Filters Scaling and Remote Models MVC and Struts.

Slides:



Advertisements
Similar presentations
Chapter 6 Server-side Programming: Java Servlets
Advertisements

Servlets & JSPs - Sharad Ballepu.
Internet i jego zastosowania 1 J2EE Servlets. Internet i jego zastosowania 2 Agenda Overview Servlet Interface Servlet Context Request Response Sample.
4 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: Servlets.
6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets.
3 Copyright © 2005, Oracle. All rights reserved. Designing J2EE Applications.
JSP and Servelets.
CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.
Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion.
Dispatching, monitoring, filtering
Web Development with Karsten Schulz Terp-Nielsen Master Principal Sales Consultant Oracle Denmark.
Java Server Pages (JSP)
Apache Struts Technology
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
COMP 321 Week 8. Overview MVC Example Servlet Lifecycle Servlet Mechanics MVC Lab 5-2 Solution Lab 8-1 Introduction.
An introduction to Java Servlet Programming
J2EE Servlets and JSP Advanced topics Presented by Bartosz Sakowicz.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
Introduction to Remote Method Invocation (RMI)
Servlet details Russell Beale. Servlet lifecycle The servlet container creates only one instance of each servlet Each use request handled with a separate.
Servlets Compiled by Dr. Billy B. L. Lim. Servlets Servlets are Java programs which are invoked to service client requests on a Web server. Servlets extend.
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
Introduction to Web App Development Allen Day. Notes This is a training NOT a presentation Please ask questions
UNIT-V The MVC architecture and Struts Framework.
Lecture 2 - Struts ENTERPRISE JAVA. 2 Contents  Servlet Deployment  Servlet Filters  Model View Controllers  Struts  Dependency Injection.
Java Server Pages B.Ramamurthy. Topics for Discussion 8/20/20152 Inheritance and Polymorphism Develop an example for inheritance and polymorphism JSP.
Objectives Java Servlet Web Components
Java support for WWW Babak Esfandiari (sources: Qusay Mahmoud, Roger Impey, textbook)
CSC 2720 Building Web Applications
Design Patterns Phil Smith 28 th November Design Patterns There are many ways to produce content via Servlets and JSPs Understanding the good, the.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
JSP Architecture Outline  Model 1 Architecture  Model 2 Architecture.
COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction.
Web Server Programming 1. Nuts and Bolts. Premises of Course Provides general introduction, no in-depth training Assumes some HTML knowledge Assumes some.
Struts J2EE web application framework “ Model 2 ” Model View Controller Controller Servlet Key features XML metadata Struts taglib Simplified form validation.
Chapter 3 Servlet Basics. 1.Recall the Servlet Role 2.Basic Servlet Structure 3.A simple servlet that generates plain text 4.A servlet that generates.
16-Oct-15 JSP Implicit Objects. 2 JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer.
JSP Filters 23-Oct-15. JSP - FILTERS A filter is an object that can transform a request or modify a response. Filters are not servlets; they don't actually.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 RMI.
CSC 2720 Building Web Applications Frameworks for Building Web Applications.
CS-4220 Dr. Mark L. Hornick 1 Java Server Pages. HTML/JSPs are intended to be used as the views in an MVC- based web application Model – represents an.
Introduction to Server-Side Web Development Introduction to Server-Side Web Development Session II: Introduction to Server-Side Web Development with Servlets.
® IBM Software Group © 2007 IBM Corporation Servlet Filtering
Servlet Filters import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class TimerFilter implements Filter { /* J2EE v1.3 Filter.
1 Java Servlets l Servlets : programs that run within the context of a server, analogous to applets that run within the context of a browser. l Used to.
Servlet Filters JAVA Enterprise Edition. Servlet Filters Servlet Filters are Java classes that can be used in Servlet Programming for the following purposes:
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, Responds oriented other.
1 Introduction to Servlets. Topics Web Applications and the Java Server. HTTP protocol. Servlets 2.
JS (Java Servlets). Internet evolution [1] The internet Internet started of as a static content dispersal and delivery mechanism, where files residing.
Advanced Java Session 6 New York University School of Continuing and Professional Studies.
Introduction to Servlets Allen Day. Notes This is a training NOT a presentation Please ask questions Prerequisites.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JSP Application Models.
©SoftMoore ConsultingSlide 1 Filters. Filters can be used in a web application to intercept, examine, and possibly transform requests or responses associated.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, written in Java code, that.
13 Copyright © 2004, Oracle. All rights reserved. Adding Validation and Error Handling.
Vakgroep Informatietechnologie – Onderzoeksgroep (naam) Web Centric Design of Distributed Software.
11 Copyright © 2004, Oracle. All rights reserved. Customizing Actions.
® IBM Software Group © 2007 IBM Corporation Servlet API (Part II)
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 21 Java Servlets Wed. 11/22/00 based on material.
Chapter 4 Request and Response. Servlets are controlled by the container.
The Chain of Responsibility Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
Bayu Priyambadha, S.Kom. Static content  Web Server delivers contents of a file (html) 1. Browser sends request to Web Server 3. Web Server sends HTML.
Securing Web Applications Lesson 4B / Slide 1 of 34 J2EE Web Components Pre-assessment Questions 1. Identify the correct return type returned by the doStartTag()
Introduction to Servlets
Pre assessment Questions
Pre-assessment Questions
Chapter 26 Servlets.
The Model Layer What is Model?
Servlet APIs Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet.
Introduction to Java Servlets
Presentation transcript:

COMP 321 Week 13

Overview Filters Scaling and Remote Models MVC and Struts

Problem We have a working web application with many Servlets. Now we decide we need to keep track of how many times each users accesses each Servlet How can we do this without modifying each Servlet?

Filters Can intercept requests before they are passed to the servlet, and intercept responses before they are returned to the client Can be chained together

Filters Request filters can: Perform security checks Perform security checks Reformat request headers or bodies Reformat request headers or bodies Audit or log requests Audit or log requests Response filters can: Compress the response stream Compress the response stream Append to or alter the response stream Append to or alter the response stream Create an entirely different response Create an entirely different response Difference between a request and response filter is only the programmers intention – there is no actual difference in implementation!

Logging Requests public class BeerRequestFilter implements Filter { private FilterConfig fc; public void init(FilterConfig config) throws ServletException { this.fc = config; } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpReq = (HttpServletRequest) req; String name = httpReq.getRemoteUser(); if (name != null) { fc.getServletContext().log("User " + name + " is updating"); } chain.doFilter(req, resp); }

Declaring and Ordering Filters BeerRequest com.example.web.BeerRequestFilter LogFileName UserLog.txt BeerRequest *.do BeerRequest AdviceServlet

Sharpen Your Pencil Filter1 /Recipes/* Filter2 /Recipes/HopsList.do Filter3 /Recipes/Add/* Filter4 /Recipes/Modify/ModRecipes.do Filter5 /* Request: /Recipes/HopsReport.do

Sharpen Your Pencil Filter1 /Recipes/* Filter2 /Recipes/HopsList.do Filter3 /Recipes/Add/* Filter4 /Recipes/Modify/ModRecipes.do Filter5 /* Request: /Recipes/HopsReport.doFilters: 1, 5

Sharpen Your Pencil Filter1 /Recipes/* Filter2 /Recipes/HopsList.do Filter3 /Recipes/Add/* Filter4 /Recipes/Modify/ModRecipes.do Filter5 /* Request: /Recipes/HopsList.do

Sharpen Your Pencil Filter1 /Recipes/* Filter2 /Recipes/HopsList.do Filter3 /Recipes/Add/* Filter4 /Recipes/Modify/ModRecipes.do Filter5 /* Request: /Recipes/HopsList.doFilters: 1, 5, 2

Sharpen Your Pencil Filter1 /Recipes/* Filter2 /Recipes/HopsList.do Filter3 /Recipes/Add/* Filter4 /Recipes/Modify/ModRecipes.do Filter5 /* Request: /Recipes/Modify/ModRecipes.do

Sharpen Your Pencil Filter1 /Recipes/* Filter2 /Recipes/HopsList.do Filter3 /Recipes/Add/* Filter4 /Recipes/Modify/ModRecipes.do Filter5 /* Request: /Recipes/Modify/ModRecipes.doFilters: 1, 5, 4

Sharpen Your Pencil Filter1 /Recipes/* Filter2 /Recipes/HopsList.do Filter3 /Recipes/Add/* Filter4 /Recipes/Modify/ModRecipes.do Filter5 /* Request: /HopsList.do

Sharpen Your Pencil Filter1 /Recipes/* Filter2 /Recipes/HopsList.do Filter3 /Recipes/Add/* Filter4 /Recipes/Modify/ModRecipes.do Filter5 /* Request: /HopsList.doFilters: 5

Sharpen Your Pencil Filter1 /Recipes/* Filter2 /Recipes/HopsList.do Filter3 /Recipes/Add/* Filter4 /Recipes/Modify/ModRecipes.do Filter5 /* Request: /Recipes/Add/AddRecipes.do

Sharpen Your Pencil Filter1 /Recipes/* Filter2 /Recipes/HopsList.do Filter3 /Recipes/Add/* Filter4 /Recipes/Modify/ModRecipes.do Filter5 /* Request: /Recipes/Add/AddRecipes.doFilters: 1, 3, 5

Response Filters What if we want to compress the response? How can we do this? Will this work? public void doFilter(…) { // request handling chain.doFilter(request, response); // do compression here }

Response Filters By the time the filter gets the response back, the servlet has already written to the output stream in the response, and the data has been sent back to the browser We need to intercept this data somehow

Response Filters public class CompressionResponseWrapper extends HttpServletResponseWrapper { public ServletOutputStream getOutputStream() throws IOException { return new GZIPOutputStream(getResponse().getOutputStream()); } public class MyCompressionFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { CompressionResponseWrapper wrappedResp = new CompressionResponseWrapper(response); chain.doFilter(request, wrappedResp); //Some compression logic here? }

Response Filters public class CompressionResponseWrapper extends HttpServletResponseWrapper { public ServletOutputStream getOutputStream() throws IOException { return new GZIPOutputStream(getResponse().getOutputStream()); } public class MyCompressionFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { CompressionResponseWrapper wrappedResp = new CompressionResponseWrapper(response); chain.doFilter(request, wrappedResp); //Some compression logic here? } Problems: getOutputStream() returns a new stream each time it's called GZIPOutputStream is not a ServletOutputStream GZIPOutputStream.finish() must be called

Response Filters public class MyCompressionFilter implements Filter { private FilterConfig cfg; private ServletContext public void init(FilterConfig cfg) throws ServletException { this.cfg = cfg; ctx = cfg.getServletContext(); ctx.log(cfg.getFilterName() + " initialized."); public void destroy() { cfg = null; ctx = null; }

Response Filters public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)req; HttpServletResponse response = (HttpServletResponse)resp; String validEncodings = request.getHeader("Accept-Encoding"); if(validEncodings.indexOf("gzip") > -1) { CompressionResponseWrapper wrappedResp = new CompressionResponseWrapper(response); wrappedResp.setHeader("Context-Encoding", "gzip"); chain.doFilter(request, wrappedResp); wrappedResp.finishGZIP(); ctx.log(cfg.getFilterName() + ": finished the request."); } else { ctx.log(cfg.getFilterName() + ": no encoding performed."); chain.doFilter(request, response); }

Response Filters public class CompressionResponseWrapper extends HttpServletResponseWrapper { private GZIPServletOutputStream gzos = null; private PrintWriter pw = null; private Object streamUsed = null; public CompressionResponseWrapper(HttpServletResponse response) { super(response); } public void finishGZIP() throws IOException { gzos.finish(); }

Response public ServletOutputStream getOutputStream() throws IOException { if(streamUsed != null && streamUsed != gzos) throw new IllegalStateException(); if(gzos == null) { gzos = new GZIPServletOutputStream(getResponse().getOutputStream()); streamUsed = gzos; } return gzos; }

Response public PrintWriter getWriter() throws IOException { if(streamUsed != null && streamUsed != pw) throw new IllegalStateException(); if(pw == null) { gzos = new GZIPServletOutputStream(getResponse().getOutputStream()); OutputStreamWriter osw = new OutputStreamWriter(gzos, getResponse().getCharacterEncoding()); pw = new PrintWriter(osw); streamUsed = pw; } return pw; }

Response Filters public class GZIPServletOutputStream extends ServletOutputStream { GZIPOutputStream os; public GZIPServletOutputStream(ServletOutputStream sos) throws IOException { this.os = new GZIPOutputStream(sos); } public void finish() throws IOException { os.finish(); } public void write(int param) throws IOException { os.write(param); }

Horizontal Scaling Enterprise web applications can get hundreds of thousands of hits per day To handle this volume, work must be distributed across many machines Hardware is normally configured in tiers, and increased load can be handled by adding machines to a tier

Horizontal Scaling

Two Classes of Requirements Functional: Application operates correctly Application operates correctlyNon-Functional: Performance Performance Modularity Modularity Flexibility Flexibility Maintainability Maintainability Extensibility Extensibility How do we make sure we can handle these?

To Meet Non-functional Requirements Code to interfaces Separation of Concerns Cohesion Hiding Complexity Loose Coupling Increase Declarative Control

Improving the Beer App Current Implementation: 1.Web request received, Controller calls ManageCustomer service, and gets a Customer bean back 2.Controller adds Customer bean to request object 3.Controller forwards to the View JSP 4.JSP uses EL to get properties and generate page

Local Model

Question How can we put the components on different servers and have them still talk to each other?

Solution JNDI – supplies centralized network service for finding things RMI – allows method calls to objects on different machines

JNDI Java Naming and Directory Interface Maintains a registry of objects Allows object lookup via locator string Allows objects to be relocated transparently - clients dont need to know

RMI Remote method invocation Allows methods on an object to be called from a client on a different machine Moving parameters and return values across the network requires only that they be Serializable

RMI (contd) – Server Side 1. Create a remote interface 2. Create implementation 3. Generate stub and skeleton 4. Register objects

RMI (contd) – Client Side 1. Look up object 2. Call methods normally

Design Issues We would like to use the same controller whether the model is local or remote –How do we handle RMI lookups? –How do we handle remote exceptions?

Solution We need a go-between to handle these things - the Business Delegate

Business Delegate Looks like a model object - implements same interface Connects to the real model object via RMI Delegates all calls to the real model object (possibly across the network)

Service Locator Helps avoid duplicating code in Business Delegates Responsible for locating objects via JNDI, and returning stubs to Business Delegates

Local Model (Take #2)

Remote Model 1. Register services with JNDI 2. Use Business Delegate and Service Locator to get ManageCustomer stub from JNDI 3. Use Business Delegate and stub to get Customer bean (another stub), and return to Controller 4. Add Customer stub to request 5. Forward to View JSP 6. View JSP uses EL to get properties from Customer bean, unaware that it isnt the actual bean

Remote Model

Remote Model - Downsides Fine-grained calls to get properties cause a large performance hit JSP shouldnt have to handle remote exceptions How can we solve these problems?

Solution – Transfer Objects! Remember Transfer Object? Serializable beans that can be returned across remote interfaces Serializable beans that can be returned across remote interfaces Prevent simple get/set calls from having to traverse network boundaries Prevent simple get/set calls from having to traverse network boundaries See Week 5 slides See Week 5 slides

Return to MVC Where we left off… Each view was a JSP Each view was a JSP Data was held in model classes Data was held in model classes Each URL had its own controller, and there was a lot of duplicated code between them Each URL had its own controller, and there was a lot of duplicated code between them

Controller protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Dealing with request... String c = request.getParameter("startDate"); // Do data conversion on date parameter // Validate that date is in range // If any errors happen, forward to hard-coded retry JSP // Dealing with model... // Invoke hard-coded model components // add model results to request object // Dealing with view... // dispatch to hard-coded view JSP }

Controller protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Dealing with request... String c = request.getParameter("startDate"); // Do data conversion on date parameter // Validate that date is in range // If any errors happen, forward to hard-coded retry JSP // Dealing with model... // Invoke hard-coded model components // add model results to request object // Dealing with view... // dispatch to hard-coded view JSP } The controller is tightly coupled to the model and views, and we also have issues with duplicate code. How can we split this up?

Controller 1. Handle request – give this task to a separate validation component 2. Invoke model – declaratively list models that should be used 3. Dispatch to the view – declaratively define views to be used based on controller results

Introducing Struts 1. Controller receives request, looks up Form Bean, sets attributes, and calls validate() 2. Controller looks up Action Object, calls execute() 3. Using result of action, Controller forwards request to correct view

Struts (contd)

Moving to Struts public class BeerSelectForm extends ActionForm { private String color; public void setColor(String color) { this.color = color; } public String getColor() { return color; } private static final String VALID_COLORS = "amber,dark,light,brown"; public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = new ActionErrors(); if(VALID_COLORS.indexOf(color) == -1) { errors.add("color", new ActionMessage("error.colorField.notValid"); } return errors; }

Moving to Struts public class BeerSelectAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { BeerSelectForm myForm = (BeerSelectForm)form; //Process the business logic BeerExpert be = new BeerExpert(); List result = be.getBrands(myForm.getColor()); //Forward to the results view request.setAttribute("styles", result); return mapping.findForward("show_results"); }

Moving to Struts <action path="/SelectBeer" type="com.example.web.BeerSelectAction" name="selectBeerForm" scope="request" validate="true" input="/form.jsp">...

Progress Check Due this week –Lab 12-1 Wrapper Design Problem Due next week –Lab 10-1 JSP User Interfaces –Lab 13-1 Web Frameworks