JavaServer Faces Anti-Patterns Dennis Byrne - ThoughtWorks

Slides:



Advertisements
Similar presentations
JSP and Servelets.
Advertisements

CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.
Services. Application component No user interface Two main uses Performing background processing Supporting remote method execution.
JSF Portlet Backing Beans and UI Components Copyright © Liferay, Inc. All Rights Reserved. No material may be reproduced electronically or in.
Apache Struts Technology
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
@mnriem#DV14 #MVC MVC 1.0 in JavaEE 8 A long time coming, or like some would say “finally!” Why are we doing it now? Survey input Customer input JavaEE.
METHOD OVERRIDING Sub class can override the methods defined by the super class. Overridden Methods in the sub classes should have same name, same signature.
Creative Commons Attribution- NonCommercial-ShareAlike 2.5 License Sakai Programmer's Café Introduction to Java Server Faces Aaron Zeckoski
Java Exception Very slightly modified from K.P. Chow University of Hong Kong (some slides from S.M. Yiu)
Java Exceptions. Types of exceptions  Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot.
Dictionaries Chapter Chapter Contents Specifications for the ADT Dictionary Entries and methods Using the ADT Dictionary English Dictionary Telephone.
Internet Technologies 1 Master of Information System Management Java Server Faces Model/View/Controller Design Pattern for Web Development Slides.
What Is a Collection?  A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit.  Collections.
Georgia Institute of Technology Making Text for the Web part 4 Barb Ericson Georgia Institute of Technology March 2006.
Dictionaries Chapter Chapter Contents Specifications for the ADT Dictionary A Java Interface Iterators Using the ADT Dictionary A Directory of Telephone.
Java Enterprise Edition Java Web Development Structure of a web project Introduction to Web Applications The first project Introduction to Java Web Development.
Spring-Batch Tutorial Guide for Application Developers.
Web Proxy Server. Proxy Server Introduction Returns status and error messages. Handles http CGI requests. –For more information about CGI please refer.
Struts 2.0 an Overview ( )
Lecture 2 - Struts ENTERPRISE JAVA. 2 Contents  Servlet Deployment  Servlet Filters  Model View Controllers  Struts  Dependency Injection.
Sets and Maps Part of the Collections Framework. The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Encapsulation CMSC 202. Types of Programmers Class programmers – Developers of new classes – Goal: Expose the minimum interface necessary to use a new.
Java Server Faces Çağatay Çivici Apache MyFaces Team Member
1 Identifiers  Identifiers are the words a programmer uses in a program  An identifier can be made up of letters, digits, the underscore character (
JavaServer Faces Jeff Schmitt October 5, Introduction to JSF Presents a standard framework for building presentation tiers for web applications.
Recitation 1 CS0445 Data Structures Mehmud Abliz.
CSE446 S OFTWARE Q UALITY M ANAGEMENT Spring 2014 Yazılım ve Uyguluma Geliştirme Yöneticisi Orhan Başar Evren.
CSCI 6962: Server-side Design and Programming Introduction to Java Server Faces.
Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.
1 Sets and Maps Starring: keySet Co-Starring: Collections.
1 TCSS 143, Autumn 2004 Lecture Notes Java Collection Framework: Maps and Sets.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Sets and Maps Chris Nevison. Set Interface Models collection with no repetitions subinterface of Collection –has all collection methods has a subinterface.
1 Trees, Trees, and More Trees. 2 By looking at forests of terms, awesome animations, and complete examples, we hope to get at the root of trees. Hopefully,
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Dynamic Architectures (Component Reconfiguration) with Fractal.
JSF Framework Java Server Faces Presented by Songkran Totiya (6/10/2014)
Java Server Pages An introduction to JSP. Containers and Components Several clients – one system.
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
1 Collections Framework A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain:
Presentation & Business Tier Design Patterns Pearce.
Chính phủ điện tử TS. Phạm Văn Tính Khoa CNTT, ĐH Nông Lâm TP.HCM
® IBM Software Group © 2007 IBM Corporation Servlet Filtering
Creative Commons Attribution- NonCommercial-ShareAlike 2.5 License Sakai Programmer's Café Sakai Montreal CRIM Workshop Sakai code exercises Aaron Zeckoski.
Subsystems: Improved exception handling for Java (DRAFT) Bart Jacobs, Frank Piessens.
Sets and Maps Computer Science 4 Mr. Gerb Reference: Objective: Understand the two basic applications of searching.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Spring MVC Essentials Getting started.
Mark Dixon 1 11 – Java Servlets. Mark Dixon 2 Session Aims & Objectives Aims –To cover a range of web-application design techniques Objectives, by end.
CreatingClasses-SlideShow-part31 Creating Classes part 3 Barb Ericson Georgia Institute of Technology Dec 2009.
©SoftMoore ConsultingSlide 1 Filters. Filters can be used in a web application to intercept, examine, and possibly transform requests or responses associated.
13 Copyright © 2004, Oracle. All rights reserved. Adding Validation and Error Handling.
Set and Map IS 313, Skeletons  Useful coding patterns  Should understand how and why they work how to use  possible quiz material.
Expect the Unexpected Kito D. Mann Principal Consultant.
Library Example February 2010 – August 2010
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
1 Maps, Stacks and Queues Maps Reading:  2 nd Ed: 20.4, 21.2, 21.7  3 rd Ed: 15.4, 16.2, 16.7 Additional references: Online Java Tutorial at
©SoftMoore ConsultingSlide 1 Lexical Analysis (a.k.a. Scanning)
COP 3330 Notes 3/7. Today’s Topics Exceptions Abstract Classes.
Introduction to Java Server Faces (covered topics) ● Reasons to use „Java Server Faces“ ● JSF application structure ● JSF component model ● JSF managed.
Efficiency of in Binary Trees
Exceptions, Interfaces & Generics
J2EE Lecture 4: Advanced Concepts in JSF
JSF Portlet Navigation and Event Listeners
Containers ב Java אליהו חלסצ'י תכנות מתקדם תרגול מספר 3
null, true, and false are also reserved.
Part of the Collections Framework
L5. Necessary Java Programming Techniques
Hashing in java.util
Set and Map IS 313,
Presentation transcript:

JavaServer Faces Anti-Patterns Dennis Byrne - ThoughtWorks

Validating Setter iterationBean com.thoughtworks.Iteration request start #{sprintBean.currentStart} end #{sprintBean.currentEnd} last hack

Validating Setter public class Iteration { private Calendar start, end; // injected // sans setters and getters for start, end public void setLast(String last) { if(start == null) throw new NullPointerException("start"); if(end == null) throw new NullPointerException("end"); if(start.after(end)) throw new IllegalStateException("start > end"); }

Validating Setter Solutions org.springframework.web.jsf.DelegatingVariableResolver org.apache.myfaces.el.unified.resolver.GuiceResolver public class Iteration { private Calendar start, end; // public void initialize() { // domain validation logic here... }

The Map Trick #{requestScopedMap.key} // calls get(‘key’) #{requestScopedMap[‘key’]} public class MapTrick implements java.util.Map { public Object get(Object key) { return new BusinessLogic().doSomething(key); } public void clear() { } public boolean containsKey(Object arg) { return false; } public boolean isEmpty() { return false; } public Set keySet() { return null; } public Object put(Object key, Object value) { return null; } public void putAll(Map arg) { } public Object remove(Object arg) { return null; } public int size() { return 0; } }

déjà vu PhaseListener comma separated list of JSF conf files javax.faces.CONFIG_FILES /WEB-INF/faces-config.xml com.thoughtworks.PhaseListenerImpl

XML Hell /home.xhtml contact_us /contact.xhtml /site_map.xhtml contact_us /contact.xhtml * contact_us /contact.xhtml

Thread Safety javax.faces.event.PhaseListener javax.faces.render.Renderer Managed Beans javax.faces.convert.Converter javax.faces.validator.Validator javax.faces.FacesContext JSF Tags

Thread Safety threadUnsafe org.apache.myfaces.book.ThreadUnsafeConverter session threadUnsafe org.apache.myfaces.book.ThreadUnsafeConverter

Facelets Migration public class WidgetTag extends UIComponentELTag{ private String title, styleClass = "default_class"; protected void setProperties(UIComponent component) { super.setProperties(component); Widget span = (Widget) component; span.setStyleClass(styleClass); span.setTitle(title == null ? "no title" : title); FacesContext ctx = FacesContext.getCurrentInstance(); Map session = ctx.getExternalContext().getSessionMap(); span.setStyle((String) session.get("style")); }

Law of Demeter A “Train Wreck” - sensitive to changes in domain model employee.getDepartment().getManager().getOffice().getAddress().getZip(); An EL “Train Wreck” - sensitive to changes in domain model #{employee.department.manager.office.address.zip} Encapsulated, insensitive to changes in domain model #{employee.officeManagersZipCode}

Vendor Lock-in import org.apache.myfaces.component.html.ext.HtmlInputHidden; import org.apache.myfaces.component.html.ext.HtmlInputText; import org.apache.myfaces.component.html.ext.HtmlOutputText; public class ImplementationDependentManagedBean { private HtmlInputText input ; private HtmlInputHidden hidden ; private HtmlOutputText output ; /* getters and setters omitted */ public boolean recordTotal(ActionEvent event) { long total = ((Long)input.getValue()).longValue(); total += ((Long)hidden.getValue()).longValue(); total += ((Long)output.getValue()).longValue(); return new JmsUtil().broadcastTotal(total); }

Vendor Lock-in Solution import javax.faces.component.ValueHolder; public class RefactoredManagedBean { private ValueHolder input ; private ValueHolder hidden ; private ValueHolder output ; /* getters & setters ommitted */ public boolean recordTotal(ActionEvent event) { long total = 0; ValueHolder[] vh = new ValueHolder[] {input, hidden, output}; for(ValueHolder valued : vh) total += ((Long)valued.getValue()).longValue(); return new JmsUtil().broadcastTotal(total); }

Portlet ClassCastException FacesContext ctx = FacesContext.getCurrentInstance(); ExternalContext ectx = ctx.getExternalContext(); ServletRequest request = (ServletRequest)ectx.getRequest(); String id = request.getParameter("id"); FacesContext ctx = FacesContext.getCurrentInstance(); ExternalContext ectx = ctx.getExternalContext(); String id = ectx.getRequestParameterMap().get("id");

OpenTransactionInViewFilter public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain){ try { ObjectRelationalUtility.startTransaction(); chain.doFilter(request, response); ObjectRelationalUtility.commitTransaction(); } catch (Throwable throwable) { try { ObjectRelationalUtility.rollbackTransaction(); } catch (Throwable _throwable) { /* sans error handling */ }

N + 1 <h:commandLink action="#{projectBean.viewProject}" value="view project"/> Project Manager #{project.manager.name} Project Name #{project.name}

N + 1- N public class OpenTransactionInApplicationPhaseListener implements PhaseListener { public void afterPhase(PhaseEvent event) { try { ObjectRelationalUtility.startTransaction(); } catch (Throwable throwable) { /* sans error handling */ } } public void beforePhase(PhaseEvent event) { try { ObjectRelationalUtility.commitTransaction(); } catch (Throwable throwable) { ObjectRelationalUtility.rollbackTransaction(); } public PhaseId getPhaseId(){return PhaseId.INVOKE_APPLICATION;} }