Thursday, August 30, 2012
Creating a RACI Matrix (step-by-step)
Delegation is an essential part of a project manager's role, so identifying roles and responsibilities early in a project is important. Applying the RACI model can help
The acronym RACI stands for:
Responsible: The person who does the work to achieve the task. They have responsibility for getting the work done or decision made. As a rule this is one person; examples might be a business analyst, application developer or technical architect.
Accountable: The person who is accountable for the correct and thorough completion of the task. This must be one person and is often the project executive or project sponsor. This is the role that responsible is accountable to and approves their work.
Consulted: The people who provide information for the project and with whom there is two-way communication. This is usually several people, often subject matter experts.
Informed: The people who are kept informed about progress and with whom there is one-way communication. These are people that are affected by the outcome of the tasks so need to be kept up-to-date.
http://www.projectsmart.co.uk/raci-matrix.html
PMP exam preparation
- Perform Quality Control is when you are trying to find problems in your work products through inspection.
- Perform Quality Assurance is when you are looking at the way your process affects the quality of the work you are doing.
- The RACI matrix shows roles and responsibilities on your project RACI stands for Responsible,Accountable, Consulted, Informed.
- When a change has been approved you always need to update the baseline and then implement the change.
- The project scope management plan tells you exactly how you’ll create the project scope, define the WBS, verify that the work has been done, and make changes to the scope.Requirements documentation,The project scope statement,The scope baseline give information about project constraints and assumptions
Observer Pattern
Motivation
The cases when certain objects need to be informed about the changes occured in other objects are frequent.
To have a good design means to decouple as much as possible and to reduce the dependencies.
The Observer Design Pattern can be used whenever a subject has to be observed by one or more observers
Let's assume we have a stock system which provides data for several types of client.
We want to have a client implemented as a web based application but in near future we need to add clients for mobile devices, Palm or Pocket PC, or to have a system to notify the users with sms alerts.
Now it's simple to see what we need from the observer pattern:
we need to separate the subject(stocks server) from it's observers(client applications) in such a way that adding new observer will be transparent for the server.
Intent
Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
Applicability & Examples
The observer pattern is used when:
the change of a state in one object must be reflected in another object without keeping the objects tight coupled.
the framework we are writing needs to be enhanced in future with new observers with minimal changes.
Some Classical Examples:
Model View Controller Pattern - The observer pattern is used in the model view controller (MVC) architectural pattern. In MVC the this pattern is used to decouple the model from the view. View represents the Observer and the model is the Observable object.
Event management - This is one of the domains where the Observer patterns is extensively used. Swing and .Net are extensively using the Observer pattern for implementing the events mechanism.
http://www.oodesign.com/observer-pattern.html
http://sourcemaking.com/design_patterns
- Example with java.util.observer class
Typical use cases:
- a mailing list, where every time an event happens (a new product, a gathering, etc.) a message is sent to the people subscribed to the list.
- Model/View/Controller: where the view needs to fetch/data information about the model or the model needs to notify the view of a change.
Imagine an airport system, that needs to notify its passengers of potential delays due to a natural occurrence such as a Volcanic Ash or other reasons.
http://www.dreamincode.net/forums/topic/252769-design-patterns-observer-pattern/
- Observer design Pattern in Java with Real world code Example
You are free to choose java.util.Observable or java.util.Observer or writing your own Subject and Observer interface.
Advantage of Observer Design Pattern in Java:
Main advantage is loose coupling between objects called observer and observable.
The subject only know the list of observers it don’t care about how they have their implementations
All the observers are notified by subject in a single event call as Broadcast communication
Disadvantage of Observer Design Pattern in Java:
Another issue is Memory management because subject will hold all the reference of all the observers if we not unregister the object it can create the memory issue
The disadvantage is that the sometime if any problem comes, debugging becomes very difficult because flow of control is implicitly between observers and observable we can predict that now observer is going to fire and if there is chain between observers then debugging become more complex
http://javarevisited.blogspot.com/2011/12/observer-design-pattern-java-example.html
Wednesday, August 29, 2012
what's scanner class?
The Scanner class is a class in java.util, which allows the user to read values of various types
Class Constructors
There are two constructors that are particularly useful: one takes an InputStream object as a parameter and the other takes a FileReader object as a parameter.
Scanner in = new Scanner(System.in); // System.in is an InputStream
Scanner inFile = new Scanner(new FileReader("myFile"))
http://www.cs.utexas.edu/users/ndale/Scanner.html
Monday, August 20, 2012
What is the difference between procedural and object-oriented programs?
- What is the difference between procedural and object-oriented programs?
a) In procedural program, programming logic follows certain procedures and the instructions are executed one after another. In OOP program, unit of program is object, which is nothing but combination of data and code.
b) In procedural program, data is exposed to the whole program whereas in OOPs program, it is accessible with in the object and which in turn assures the security of the code.
http://www.techinterviews.com/master-list-of-java-interview-questions
Sunday, August 19, 2012
The Most Difficult Interview Questions (and Answers)
What is your biggest weakness?
He recommends responding with: “I have a tendency to say yes and get overcommitted.” Then follow that with an example of how you are working on prioritizing and setting personal limits. Never draw negative attention to yourself by stating a weakness that would lead an employer to think you are not the best person for the job
What salary do you think you deserve?
“The person who states the salary is the loser,” says Denham, explaining that if you are the first to throw out a number, the number you give could be less than what the employer was planning to pay.
http://jobstar.info/the-most-difficult-interview-questions-and-answers/?goback=.gde_1698247_member_127672072
Tuesday, August 14, 2012
hibernate interview questions
- What is ORM
?
ORM stands for object/relational mapping. ORM is the automated persistence of objects in a Java application to the tables in a relational database.
- What are the ORM levels
?
Pure relational (stored procedure.)
Light objects mapping (JDBC)
Medium object mapping
Full object Mapping (
- What is
Hibernate ?
Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java objects to relational database tables using (XML) configuration files
- Why do you need ORM tools like hibernate?
The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from this, ORM provides following benefits:
Improved productivity
High-level object-oriented API
Less Java code to write
No SQL to write
Improved performance
Sophisticated caching
Lazy loading
Eager loading
Improved maintainability
A lot less code to write
Improved portability
ORM framework generates database-specific SQL for you
- What is the need for Hibernate
xml mapping file?
Hibernate mapping file tells Hibernate which tables and columns to
- What are the most common methods of Hibernate configuration?
The most common methods of Hibernate configuration are:
Programmatic configuration
XML configuration hibernate.cfg.xml (or hibernate
- How do you configure Hibernate?
The configuration files hibernate.cfg.xml (or hibernate
• hibernate.cfg.xml (alternatively can use hibernate
• Mapping files (*
http://www.javalobby.org/java/forums/t104442.html
- hibernate optimistic vs pessimistic locking
How does one handle
1. Do Nothing
- User 1 reads a record
- User 2 reads the same record
- User 1 updates that record
- User 2 updates the same record
User 2 has now over-written the changes that User 1 made. They are completely gone, as if they never happened. This is called a 'lost update'.
2. Lock the record when it is read. Pessimistic locking
- User 1 reads a record *and locks it* by putting an exclusive lock on the record (FOR UPDATE clause)
- User 2 attempts to read *and lock* the same record, but must now wait behind User 1
- User 1 updates the record (and, of course, commits)
- User 2 can now read the record *with the changes that User 1 made*
- User 2 updates the record complete with the changes from User 1
The lost update problem is solved. The problem with this approach is concurrency. User 1 is locking a record that they might not ever update. User 2 cannot even read the record because they want an exclusive lock when reading as well.
3. Use Optimistic Locking. Optimistic locking does not use exclusive locks when reading. Instead, a check is made during the update to make sure that the record has not been changed since it was read. This can be done by checking every field in the table
*Most* people implement this, instead, through a single column, usually called timestamp. This column is used *for no other purpose* than implementing optimistic concurrency. It can be a number or a date. The idea is that it is given a value when the row is inserted. Whenever the record is read, the timestamp column is read as well. When an update is performed, the timestamp column is checked. If it has the same value at UPDATE time as it did when it was read, then all is well, the UPDATE is performed and *the timestamp is changed!*. If the timestamp value is different at UPDATE time, then an error is returned to the user - they must re-read the record, re-make their changes, and try to update the record again
http://www.dbasupport.com/forums/showthread.php?7282-What-is-Optimistic-Locking-vs.-Pessimistic-Locking
You add a version field to your table and a version element to your mapping file. When you update a Hibernate object Hibernate will check the version values match. If they do the update is successful, and the version is incremented, if they are not Hibernate throws a StaleObjectException and you know that something else has updated your data.
Pessimistic locking is provided by specifying a LockMode when you get an object from the database.
Hibernate will use database specific SQL to lock the record (if your database supports it) such as "select ... for update".
Now nothing can update that record till you are finished.
http://www.coderanch.com/t/216247/ORM/databases/Optimistic-Pesimistic-locking
"Optimistic locking" is more scalable than pessimistic locking when dealing with a
highly concurrent environment
pessimistic locking is a better solution for situations where the possibility of simultaneous updates to the same data by multiple sources
(for example, different applications use same database to update) is common, hence making the possibility of "data clobbering" , a
likely scenario.
Pessimistic locking is when you want to reserve a record for exclusive update by
locking the database record(entire table). Hibernate supports pessimistic locking
(using the underlying database, not in-memory) via one of the following methods:
1. Session.get
2. Session.load
3. Session.lock
4. Session.refresh
5. Query.setLockMode
Optimistic locking means that you will not lock a given database record or table and
instead check a property of some sort (for example, a timestamp column) to
ensure the data has not changed since you read it. Hibernate supports this using a
version property, which can either be checked manually by the application or automatically
by Hibernate for a given session
http://javacompleteexamples.blogspot.com/2009/07/how-db-locking-system-works-in.html
Hibernate vs EJB 3.0
- Hibernate
- Session–Cache or collection of loaded objects relating to a single unit of work
- XDoclet Annotations used to support Attribute Oriented Programming
- Defines HQL for expressing queries to the database
- Supports Entity Relationships through mapping files and annotations in JavaDoc
- Provides a Persistence Manager API exposed via the Session, Query, Criteria, and Transaction API
- Provides callback support through lifecycle, interceptor, and validatable interfaces
- Entity Relationships are unidirectional. Bidirectional relationships are implemented by two unidirectional relationships
- EJB 3.0
- Persistence Context-Set of entities that can be managed by a given EntityManager is defined by a persistence unit
- Java 5.0 Annotations used to support Attribute Oriented Programming
- Defines EJB QL for expressing queries
- Support Entity Relationships through Java 5.0 annotations
- Provides and Entity Manager Interface for managing CRUD operations for an Entity
- Provides callback support through Entity Listener and Callback methods
- Entity Relationships are bidirectional or unidirectional
http://javapassions.blogspot.com/2010/01/hibernate-interview-questions.html
Hibernate vs JDBC?
Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this.
http://javapassions.blogspot.com/2010/01/hibernate-interview-questions.html
- Why is Hibernate better than JDBC?
1) Relational Persistence for JAVA
Working with both Object-Oriented software and Relational Database is complicated task with JDBC because there is mismatch between how data is represented in objects versus relational database. So with JDBC, developer has to write code to map an object model's data representation to a relational data model and its corresponding database schema. Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this.
2) Transparent Persistence
The automatic mapping of Java objects with database tables and vice versa is called Transparent Persistence. Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS. With JDBC this conversion is to be taken care of by the developer manually with lines of code.
3) Support for Query Language
JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database, i.e to select effective query from a number of queries to perform same task. Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also supports native SQL statements. It also selects an effective way to perform a database manipulation task for an application.
4) Database Dependent Code
Application using JDBC to handle persistent data (database tables) having database specific code in large amount. The code written to map table data to application objects and vice versa is actually to map table fields to object properties. As table changed or database changed then it’s essential to change object structure as well as to change code written to map table-to-object/object-to-table. Hibernate provides this mapping itself. The actual mapping between tables and application objects is done in XML files. If there is change in Database or in any table then the only need to change XML file properties.
5) Maintenance Cost
With JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objects through code to use this persistent data in application. So with JDBC, mapping between Java objects and database tables is done manually. Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to application in form of Java objects. It relieves programmer from manual handling of persistent data, hence reducing the development time and maintenance cost.
6) Optimize Performance
Caching is retention of data, usually in application to reduce disk access. Hibernate, with Transparent Persistence, cache is set to application work space. Relational tuples are moved to this cache as a result of query. It improves performance if client application reads same data many times for same write. Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code. With JDBC, caching is maintained by hand-coding.
7) Automatic Versioning and Time Stamping
By database versioning one can be assured that the changes done by one person is not being roll backed by another one unintentionally. Hibernate enables developer to define version type field to application, due to this defined field Hibernate updates version field of database table every time relational tuple is updated in form of Java class object to that table. So if two users retrieve same tuple and then modify it and one user save this modified tuple to database, version is automatically updated for this tuple by Hibernate. When other user tries to save updated tuple to database then it does not allow to save it because this user does not has updated data. In JDBC there is no check that always every user has updated data. This check has to be added by the developer.
8) Open-Source, Zero-Cost Product License
Hibernate is an open source and free to use for both development and production deployments.
9) Enterprise-Class Reliability and Scalability
Hibernate scales well in any environment, no matter if use it in-house Intranet that serves hundreds of users or for mission-critical applications that serve hundreds of thousands. JDBC can not be scaled easily.
Disadvantages of Hibernate
1) Steep learning curve.
2) Use of Hibernate is an overhead for the applications which are :
• simple and use one database that never change
• need to put data to database tables, no further SQL queries
• there are no objects which are mapped to two different tables
Hibernate increases extra layers and complexity. So for these types of applications JDBC is the best choice.
3) Support for Hibernate on Internet is not sufficient.
4) Anybody wanting to maintain application using Hibernate will need to know Hibernate.
5) For complex data, mapping from Object-to-tables and vise versa reduces performance and increases time of conversion.
6) Hibernate does not allow some type of queries which are supported by JDBC. For example It does not allow to insert multiple objects (persistent data) to same table using single query. Developer has to write separate query to insert each object.
Dipti Phutela, Mindfire Solutions
www.mindfiresolutions.com
hibernate vs ibatis
Hibernate works very well if your data model is well in sync with object model, because ORM solutions like Hibernate map object to tables. However, let’s suppose data model is not in sync with object model, in this case you have do lot of additional coding and complexities are entering into your application, start coming the beyond the benefits of ORM
iBatis maps results sets to objects, so no need to care about table structures. This works very well for stored procedures, works very well for reporting applications
* Use iBatis if
o You want to create your own SQL's and are willing to maintain them
o your environment is driven by relational data model
o you have to work existing and complex schema's
* Use Hibernate if
o your environment is driven by object model and wants generates SQL automatically
What is iBatis ?
* A JDBC Framework
o Developers write SQL, iBATIS executes it using JDBC.
o No more try/catch/finally/try/catch.
* An SQL Mapper
o Automatically maps object properties to prepared statement parameters.
o Automatically maps result sets to objects.
o Support for getting rid of N+1 queries.
* A Transaction Manager
o iBATIS will provide transaction management for database operations if no other transaction manager is available.
o iBATIS will use external transaction management (Spring, EJB CMT, etc.) if available.
* Great integration with Spring, but can also be used without Spring (the Spring folks were early supporters of iBATIS).
What isn’t iBATIS ?
* An ORM
o Does not generate SQL
o Does not have a proprietary query language
o Does not know about object identity
o Does not transparently persist objects
o Does not build an object cache
iBatis is a very lightweight persistence solution that gives you most of the semantics of an O/R Mapping toolkit
iBATIS strives to ease the development of data-driven applications by abstracting the low-level details involved in database communication (loading a database driver, obtaining and managing connections, managing transaction semantics, etc.), as well as providing higher-level ORM capabilities (automated and configurable mapping of objects to SQL calls, data type conversion management, support for static queries as well as dynamic queries based upon an object's state, mapping of complex joins to complex object graphs, etc.).
iBATIS simply maps JavaBeans to SQL statements using a very simple XML descriptor
http://loianegroner.com/2011/02/introduction-to-ibatis-mybatis-an-alternative-to-hibernate-and-jdbc/
What is the difference between UML and RUP?
The unified modeling languege is a standardized specification language for object modeling. UML is a general-purpose modeling language that includes a graphical notation used to create an abstract model of a system, referred to as a UML model.
http://en.wikipedia.org/wiki/Unified_Modeling_Language
While RUP is The Rational Unified Process (RUP) is an iterative software development process framework created by the Rational Software Corporation, a division of IBM since 2003.
RUP is not a single concrete prescriptive process, but rather an adaptable process framework, intended to be tailored by the development organizations and software project teams that will select the elements of the process that are appropriate for their needs.
http://en.wikipedia.org/wiki/Rational_Unified_Process
oracle 11g new features
Pivot queries involve transposing rows into columns (pivot) or columns into rows (unpivot) to generate results in crosstab format
http://www.oracle-developer.net/display.php?id=506
WSUS DEPLOYMENT STRATEGIES
I have a Host Server running
virtual guests. These guests are Windows 2003 Server and Windows 2000 Server. I
also have another Server setup for WSUS. I first deploy the updates via the
WSUS server to the virtual guests and watch out for potential problems. If the
applications and services come backup up without any problems. I then schedule
downtime and apply them on production machines
Service Packs and Update rollups
should be tested thoroughly first in Dev and Post Production (PPE) and then
ported to live when you are ready.
ps:could not find reference sorry
struts interview questions
- What is MVC?
Model-View-Controller (MVC) is a design pattern put together to help control change. MVC decouples interface from business logic and data.
Model : The model contains the core of the application's functionality. The model encapsulates the state of the application. Sometimes the only functionality it contains is state. It knows nothing about the view or controller.
View: The view provides the presentation of the model. It is the look of the application. The view can access the model getters, but it has no knowledge of the setters. In addition, it knows nothing about the controller. The view should be notified when changes to the model occur.
Controller:The controller reacts to the user input. It creates and sets the model.
- What is a framework?
A framework is made up of the set of classes which allow us to use a library in a best possible way for a specific requirement.
- What is Struts framework?
Struts framework is an open-source framework for developing the web applications in Java EE, based on MVC-2 architecture.
- What are the components of Struts?
Struts components can be categorize into Model, View and Controller:
Model: Components like business logic /business processes and data are the part of model.
View: HTML, JSP are the view components.
Controller: Action Servlet of Struts is part of Controller components which works as front controller to handle all the requests.
- What is ActionServlet?
ActionServlet is a simple servlet which is the backbone of all Struts applications. It is the main Controller component that handles client requests and determines which Action will process each received request
- What is role of ActionServlet?
ActionServlet performs the role of Controller:
Process user requests
Determine what the user is trying to achieve according to the request
Pull data from the model (if necessary) to be given to the appropriate view,
Select the proper view to respond to the user
Delegates most of this grunt work to Action classes
Is responsible for initialization and clean-up of resources
- What design patterns are used in Struts?
Struts is based on model 2 MVC (Model-View-Controller) architecture.
Struts controller uses the command design pattern and the action classes use the adapter design pattern.
The process() method of the RequestProcessor uses the template method design pattern.
Struts also implement the following J2EE design patterns.
Service to Worker
Dispatcher View
Composite View (Struts Tiles)
Front Controller
View Helper
Synchronizer Token
http://www.developersbook.com/struts/interview-questions/struts-interview-questions-faqs.php
JSF interview questions
- What is JSF (or JavaServer Faces
A server side user interface component framework for Java technology-based web applications
JSF contains an API for representing UI components and managing their state; handling events, server-side validation, and data conversion; defining page navigation; supporting internationalization and accessibility; and providing extensibility for all these features.
- What are the advantages of JSF?
user interfaces can be created easily with its built-in UI component library, which handles most of the complexities of user interface management.
* Offers a clean separation between behavior and presentation.
* Provides a rich architecture for managing component state, processing component data, validating user input, and handling events.
* Robust event handling mechanism.
* Events easily tied to server-side code.
* Render kit support for different clients
* Component-level control over statefulness
* Highly ‘pluggable’ - components, view handler, etc
* JSF also supports internationalization and accessibility
* Offers multiple, standardized vendor implementations
- What are the available implementations of JavaServer Faces?
The main implementations of JavaServer Faces are:
* Reference Implementation (RI) by Sun Microsystems.
* Apache MyFaces is an open source JavaServer Faces (JSF) implementation or run-time.
* ADF Faces is Oracle’s implementation for the JSF standard.
- What typical JSF application consists of?
A typical JSF application consists of the following parts:
* JavaBeans components for managing application state and behavior.
* Event-driven development (via listeners as in traditional GUI development).
* Pages that represent MVC-style views; pages reference view roots via the JSF component tree.
- What is Managed Bean?
JavaBean objects managed by a JSF implementation are called managed beans. A managed bean describes how a bean is created and managed
- What is Backing Bean?
Backing beans are JavaBeans components associated with UI components used in a page. Backing-bean management separates the definition of UI component objects from objects that perform application-specific processing and hold data
- What advantages does struts have over jsf?
Because Struts is a web application framework, it has a more sophisticated controller architecture than does JavaServer Faces technology
Application developer can access the controller by creating an Action object that can integrate with the controller, whereas JavaServer Faces technology does not allow access to the controller.
the Struts controller can do things like access control on each Action based on user roles. This functionality is not provided by JavaServer Faces
Struts includes a powerful layout management framework, called Tiles, which allows you to create templates that you can reuse across multiple pages, thus enabling you to establish an overall look-and-feel for an application
The Struts validation framework includes a larger set of standard validators, which automatically generate both server-side and client-side validation code based on a set of rules in a configuration file.
- What advantages does jsf have over struts?
* Eliminated the need for a Form Bean
* Eliminated the need for a DTO Class
* Allows the use of the same POJO on all Tiers because of the Backing Bean
The greatest advantage that JavaServer Faces technology has over Struts is its flexible, extensible UI component model, which includes:
–> A standard component API for specifying the state and behavior of a wide range of components, including simple components, such as input fields, and more complex components, such as scrollable data tables. Developers can also create their own components based on these APIs, and many third parties have already done so and have made their component libraries publicly available.
–> A separate rendering model that defines how to render the components in various ways. For example, a component used for selecting an item from a list can be rendered as a menu or a set of radio buttons.
An event and listener model that defines how to handle events generated by activating a component, such as what to do when a user clicks a button.
–> Conversion and validation models for converting and validating component data.
http://www.developersbook.com/jsf/interview-questions/jsf-interview-questions-faqs.php
- Learn JSF 2.0 — Presentation on the JSF 2.0
http://www.techartifact.com/blogs/2013/02/learn-jsf-2-0-a-ppt-on-the-jsf-2-0.html?goback=.gde_70526_member_210728763
- What Is Facelets?
Facelets is a powerful but lightweight page declaration language that is used to build JavaServer Faces views using HTML style templates and to build component trees. Facelets features include the following:
Use of XHTML for creating web pages
Support for Facelets tag libraries in addition to JavaServer Faces and JSTL tag libraries
Support for the Expression Language (EL)
Templating for components and pages
Advantages of Facelets for large-scale development projects include the following:
Support for code reuse through templating and composite components
Functional extensibility of components and other server-side objects through customization
Faster compilation time
Compile-time EL validation
High-performance rendering
http://docs.oracle.com/javaee/6/tutorial/doc/gijtu.html
The SpringBeanFacesELResolver is the glue that allows JSF pages to use Spring beans is if they were @ManagedBeans.
http://papweb.wordpress.com/2011/07/29/spring-mvc-3-jsf-2-with-maven-2-and-tomcat/
- The SpringBeanFacesELResolver is the glue that allows JSF pages to use Spring beans is if they were @ManagedBeans.
- JSF2-Overview
A set of Web-based GUI controls and handlers?
– JSF provides many prebuilt HTML-oriented GUI controls, along
with code to handle their events.
• A device-independent GUI control framework?
– JSF can be used to generate graphics in formats other than HTML,
using protocols other than HTTP.
• An MVC-based Web app framework?
– Like Apache Struts, JSF can be viewed as an MVC framework for
building HTML forms, validating their values, invoking business
logic, and displaying results.
• An Ajax library?
– JSF 2.0 provides very easy-to-use Ajax support. So, JSF 2.0 can be
viewed as an alternative to jQuery or GWT.
• But which is the proper way to view JSF?
– The answer depends on what you are going to use it for, but 1 & 3
are the most common ways of looking at JSF
Integrated Ajax support
– You can use jQuery, Dojo, or Ext-JS with servlets and JSP. However, JSF
lets you use Ajax without explicit JavaScript programming and with very
simple tags. Also, the Ajax calls know about the server-side business logic
Page templating
– Although JSP has jsp:include for reuse of content, JSF has a full-fledged
page templating system that lets you build pages that share layout or
content
JSF 2 vs. Struts 2
You decide that for your application, the benefits (power)
of using a Web application framework [vs. servlets/JSP
with MVC] outweigh the disadvantages (complexity)
• Problem
– JSF is not the only game in town
• Alternatives
– Struts is the most popular alternative to JSF
– But there are many more
• Spring MVC
• Apache Wicket
• Apache Tapestry
• jMaki
Advantages of JSF
(vs. Struts)
• Custom components
JSF makes it relatively easy to combine complex GUIs into a single
manageable component; Struts does not
There are many existing third-party component libraries for JSF,
virtually none for Struts
• PrimeFaces, JBoss RichFaces, Oracle ADF, IceFaces, Apache
Tomahawk, Woodstock, Web Galileo, …
Official part of Java EE
– JSF is part of the Java EE spec, and all servers that support Java EE
include JSF (JSF 2.0 is part of Java EE 6)
Simpler controller and bean definitions
– JSF does not require your controller and bean classes to extend
any particular parent class (e.g., Action) or use any particular
method (e.g., execute). Struts does.
Disadvantages of JSF (vs. Struts)
Confusion vs. file names
– The actual pages used in JSF end in .xhtml. But the URLs used
end in .faces or .jsf. This causes many problems.
• You cannot browse directories and click on links
• It is hard to protect raw XHTML pages from access
• It is hard to refer to non-faces pages in faces-config.xml
Self-submit approach
– With Struts, the form (blah.jsp) and the handler (blah.do)have
different URLs; with JSF they are the same (blah.jsf).
Much weaker automatic validation
– Struts comes with form-field validators for email address,
credit card numbers, regular expressions, and more. JSF
only comes with validators for missing values, length of
input, and numbers in a given range.
• You can use third-party validation libraries with JSF (e.g.,
MyFaces/Tomahawk built on the Struts/Commons
validation library), but still not as powerful as Struts
Lack of client-side validation
– Struts supports JavaScript-based form-field validation;
JSF does not
• You can use Ajax-based validation in JSF, but still not as
good as the true client-side validation in Struts
JSF 2.0 vs. JSF 1.x
New features vs. JSF 1.x
– Smart defaults
– Annotations to replace many faces-config.xml entries
– Ajax support
– Integrated support for facelets
– Simpler custom components
– More components and validators
– Support for Groovy
– Ability to bookmark results pages
– Lots more
Main JSF 2.0 Implementations
un/Oracle Mojarra
– Main page: http://javaserverfaces.java.net/
– Runs in any server supporting servlets 2.5 or later
– Also integrated into Glassfish 3
• Apache MyFaces
– Main page: http://myfaces.apache.org/core20/
– Runs in any server supporting servlets 2.5 or later
– Also integrated into Apache Geronimo 3
• Any Java EE 6 server
– JSF 2.0 is an official part of Java EE 6
• JBoss 6, Glassfish 3, WebLogic 11, WebSphere 8,
Geronimo 3, etc.
JSF2-Overview.pdf
http://www.coreservlets.com/JSF-Tutorial/jsf2/
- Getting required software
– Installing Java SE 6 or 7
– Installing Eclipse (Java EE version)
– Installing a server for JSF 2.0
• Tomcat 6 or 7 (also needs javax.faces-2.1.x .jar) or
• Any Java EE 6 server (e.g., Glassfish 3)
Requirements for Running JSF 2
server
– Servers that just support servlets 2.5 or later (e.g., Tomcat 6 or 7) need JSF
JAR file (javax.faces-2.1.7.jar in Mojarra, but could have other name)
• In addition, JSTL 1.2 JAR files needed if you use ui:repeat tag
• JSF 2.0 also runs on the Google cloud server (which uses Jetty)
– Servers that support Java EE 6 (e.g., Glassfish 3, JBoss 6, WebLogic 11g)
have built-in support for JSF 2.0 & JSTL 1.2
• All tutorial examples run on Tomcat 6, Tomcat 7, & Glassfish 3
o run on Tomcat
– Install Java
• Java 5 or later
– Install an IDE
• I use Eclipse 3.8 (Juno)
– Download Tomcat 6 or 7
• Or any server supporting
servlets 2.5
– Get JSF 2.x JAR files
• javax.faces-2.1.x .jar
• (JSTL 1.2 JAR files)
• Download from Oracle
Mojarra or Apache
MyFaces
– web.xml, faces-config.xml
• Required entries shown
later in tutorial
To run on Glassfish
– Install Java
• Java 6 or later
– Install an IDE
• I use Eclipse 3.8 (Juno)
– Download Glassfish 3
• Or any server supporting
Java EE 6
– No extra JAR files needed
• Java EE 6 has built-in
support for JSF 2.0
– web.xml, faces-config.xml
• Required entries shown
later in tuto
Tell Eclipse about Java version
– Window ?Preferences ?Java ?
Installed JREs ?Press “Add”, choose
“Standard VM”, navigate to JDK folder
(not “bin” subdirectory)
• E.g., C:\Program Files\Java\jdk1.6.0_35
SF 2.0 support
– Eclipse 3.8 has support for JSF 2.
• R-click and add Project Facet for JSF 2
• R-click .xhtml files and
Open With, Web Page Editor
• Double-click faces-config.xml
Downloading JSF 2.0 From Scratch (Mojarra)
Required JAR files: javax.faces-2.1.x.jar
– Goes in the WEB-INF/lib folder of your projects.
– Download
• http://javaserverfaces.java.net/download.html
• Click on latest 2.x .y binary bundle
• Download and grab the JAR file from lib folder
• Suggested: jstl-1.2-api.jar, jstl-1.2-impl.jar
– Although the Mojarra Web site states that only the
javax.faces…jar file is needed, the standard ui:repeat tags
use JSTL 1.2 internally. So, the JSTL JARs are highly
recommended.
– Download
• http://jstl.java.net/download.html
• Click on both “API” and “Implementation” links
@ManagedBean
Declares this as managed bean, without requiring entry in faces-config.xml
Since no scope given, it is request scope.
HealthPlanBean.java
Since no name given, name is the class name with the first letter changed to lower case (i.e., healthPlanBean).
return("accepted");
Since there are no explicit navigation rules in faces-config,
these return values correspond to accepted.xhtml and rejected.xhtml (in same folder as page that has the form).
http://courses.coreservlets.com/Course-Materials/pdf/jsf/jsf2/JSF2-Getting-Started.pdf
- the most important features that are new in JSF 2.0
Facelets, not JSP, is the standard technology for all your JSF pages. Name the pages blah.xhtml, but use the URL blah.jsf (assuming a url-pattern of *.jsf in web.xml). Use xhtml format for the pages themselves. Don't use @taglib, but instead use xmlns:h="http://java.sun.com/jsf/html". Then, use h:head, h:body, and h:form (but not usually f:view) in the page
You can use default bean names. Instead of declaring beans with managed-bean in faces-config.xml, you can put @ManagedBean above the class definition. Then, take the bean classname, change the first letter to lower case, and use that as the managed bean name. For example, if the class is package1.package2.MyBean, you would use #{myBean.whatever} in your code. You can also do @ManagedBean(name="someName"). Beans are request scoped by default, but there are annotations like @SessionScoped to change the default
You can use default mappings of outcomes to results pages. In the absence of explicit navigation rules, the return values of the action controller method correspond to the file names that should be used. Suppose that your form (file form.xhtml, URL form.jsf) says <h:commandButton ... action="#{someBean.someMethod}"/>. When the button is pressed, the bean named someBean is instantiated (assuming request scope), setter methods corresponding to the h:inputBlah elements are run, validation occurs, and then someMethod is executed. This is the same as in JSF 1.x, except that the managed bean name (someBean) can be derived from the bean class name (SomeBean). But now, if someMethod returns "foo" and "bar", and there are no explicit navigation rules in faces-config.xml for those outcomes, then JSF will assume that they correspond to foo.xhtml and bar.xhtml (from the same folder as form.xhtml), respectively. For example, in the this sample bean, the outcomes correspond to accepted.xhtml and rejected.xhtml. In a later section on page navigation, I will argue that explicit navigation rules are probably what you will use in real projects, but the implicit navigation lets you get your app up and running more quickly, and is particularly convenient for test apps where you just want to experiment with some particular JSF 2 feature.
Mere mortals can build custom components. In JSF 1.x, the existence of an API for custom components was a real boon. Because of it, a whole market for third-party component libraries developed, with PrimeFaces, RichFaces, IceFaces, Tomahawk, ADF, and Web Galileo being notable libraries. However, the API was so complex that it was more trouble than it was worth for most ordinary JSF programmers. Now, there is a very easy-to-use facelets-based (rather than Java-based) method for building simple and medium-complex components. This is somewhat analogous to the tag-file way of building JSP custom tag libraries, but even simpler and even more powerful. A later section covers composite components in detail.
There is a powerful and relatively easy to use page templating library (better than Tiles!). JSP always had jsp:include, but it lacked a serious library for building page templates, sub-templates, and concrete pages built upon templates. However, most modern Web apps have many similar-looking pages, so templating is a must. JSF 2 has a well-thought-out, extensible, and moderately easy-to-use templating framework that is arguably even better than Apache Tiles on which it was loosely based
http://www.coreservlets.com/JSF-Tutorial/jsf2/#New-Features
- faces-config.xml
There will be no content inside the tags for any of the examples in this section. All examples in this section use
default bean names (derived from the bean’s class name with the first letter changed to lower case) and default
results pages (derived from the action controller’s return values)
web.xml
You must have a url-pattern for the FacesServlet, just as
in JSF 1.x. You can optionally set the PROJECT_STAGE,
which is recommended during development and testing
Eclipse Support: Issues
Poor web.xml file created when facet added
• Creates a web.xml file with spurious entries, and without the very
valuable Development PROJECT_STAGE entry
– Editing .xhtml files
• By default, they open in normal HTML editor, not smart editor that
understands and previews the h: tags
Managed beans are Java classes that are declared with
@ManagedBean or listed in faces-config.xml. More detai
will be given in the next tutorial sections, but for now the
main points are:
• They are usually POJOs (they implement no special
interfaces, and most methods have no JSF-specific
argument or return types).
• They have pairs of getter and setter methods
corresponding to each input element in the form.
• They have an action controller method that takes no
arguments and returns a String. This is the method listed
the action of the h:commandButton in the input form.
• (They also typically have placeholders for derived
properties – information that will be computed based on th
input data. More on this in the next lecture on managed
beans.)
@ManagedBean annotation
You refer to bean with #{someName.blah}, where bean
name is class name (minus packages) with first letter
changed to lower case. Request scoped by default.
• And “blah” is either an exact method name (as with action
of h:commandButton), or a shortcut for a getter and setter
method (as with value of h:inputText).
Return values of action controller method
– If action controller method returns "foo" and "bar" and
there are no explicit mappings in faces-config.xml, then
results pages are foo.xhtml and bar.xhtml
http://courses.coreservlets.com/Course-Materials/pdf/jsf/jsf2/JSF2-Programming-Basics.pdf
- Three parts of beans in JSF
– Getter/setter methods to represent input elements
– Action controller method
– Placeholder for results (properties derived from input)
Basic Beans
Java classes that follow certain conventions
– Must have a zero-argument (empty) constructor
• You can satisfy this requirement either by explicitly
defining such a constructor or by omitting all constructors
Should have no public instance variables (fields)
• You should already follow this practice and use accessor
methods instead of allowing direct access to fields
Persistent values should be accessed through methods
called getBlah and setBlah
• If class has method getTitle that returns a String, class is
said to have a String property named title
– JSF uses #{book.title} to mean “call getTitle on ‘book’ ”.
• Boolean properties may use isBlah instead of getBlah
• What matters is method name, not instance variable name
Bean Properties
Usual rule to turn method into property
– Drop the word “get” or “set” and change the next letter to
lowercase. Again, instance var name is irrelevant.
• Method name: getFirstName
• Property name: firstName
• Example: #{customer.firstName}
• Exception 1: boolean properties
– If getter returns boolean or Boolean
• Method name: getPrime or isPrime
• Property name: prime
• Example: #{myNumber.prime}
• Exception 2: consecutive uppercase letters
– If two uppercase letters in a row after “get” or “set”
• Method name: getURL
• Property name: URL (not uRL)
• Example: #{webSite.URL}
Why You Should Use Accessors, Not Public Fields
private double speed; // Var name need not match method name
public double getSpeed() {
return(speed);
}
public void setSpeed(double speed) {
this.speed = speed;
}
You are probably following most of the conventions
already anyhow
• Zero arg constructor
• No public instance variables
• Use getBlah/setBlah or isBlah/setBlah naming conventions
JSF often refers to “bean properties”
– Which are shortcuts for getter/setter methods
• getFirstName method: refer to “firstName”
– #{customer.firstName}
• isVeryCool method (boolean): refer to “veryCool”
– #{invention.veryCool}
• getHTMLString method: refer to “HTMLString”
– #{message.HTMLString}
JSF automatically “manages” the bean
– Instantiates it
• Thus the need for a zero-arg constructor
– Controls its lifecycle
• Scope (request, session, application) determines lifetime
– Calls setter methods
• I.e., for <h:inputText value="#{customer.firstName"/>, when form
submitted, the value is passed to setFirstName
– Calls getter methods
• #{customer.firstName} results in calling getFirstName
Simplest: @ManagedBean before class
• Results in request scope. See next lecture for other scopes.
– Most powerful: <managed-bean> in faces-config.xml
Managed beans typically have three parts
– Bean properties (i.e, pairs of getter and setter methods)
• One pair for each input element
• Setter methods called automatically by JSF when form
submitted. Called before action controller method.
– Action controller methods
• Often only one, but could be several if the same form has
multiple buttons
• Action controller method (corresponding to the button that
was pressed) called automatically by JSF
– Placeholders for results data
• Not automatically called by JSF: to be filled in by action
controller method based on results of business logic.
• Needs a getter method so value can be output in results
page, but not required to have a setter method
Performance Principle: Make Getter Methods Fast
Problem
– Getter methods of managed beans called several times.
• E.g., at a minimum, once when form is displayed
(<h:inputText value="#{user.customerId}"/>) and again
when result is shown (#{user.customerId}).
– But often extra times.
– So, if getter method talks to database or does other
expensive operation, performance can be unexpectedly
bad.
• Solution
– Store data in instance variables, have getter methods
merely return the existing values
http://courses.coreservlets.com/Course-Materials/pdf/jsf/jsf2/JSF2-Managed-Beans-1.pdf
- JSF 2 performance issue
A getter method will be called everytime when ValueExpression#getValue() is been invoked on the given EL expression. This will normally be invoked one or two times per JSF request-response cycle, depending on whether the component is an input or output component (learn it here). However, this count can get up (much) higher when used in iterating JSF components (such as <h:dataTable> and <ui:repeat>), or here and there in a boolean expression like the rendered attribute. JSF (specifically, EL) won't cache the evaluated result of the EL expression at all as it may return different values on each call (for example, when it's dependent on the currently iterated datatable row).
Evaluating an EL expression and invoking a getter method is a very cheap operation, so you should generally not worry about this at all. However, the story changes when you're performing expensive DB/business logic in the getter method for some reason. This would be re-executed everytime!
Getter methods in JSF backing beans should be designed that way that they solely return the property and nothing more, exactly as per the Javabeans specification. They should not do any expensive DB/business logic at all. For that the bean's (post)constructor, initialization blocks and/or (action)listener methods should be used. They are executed only once during bean's life and that's exactly what you want.
Here is a summary of all different right ways to preset/load a property.
public class Bean {
// Direct initialization.
private SomeObject someProperty = loadSomeProperty();
{
// Or in init block (applies to all constructors, not so relevant in javabeans).
someProperty = loadSomeProperty();
}
public Bean() {
// Or in constructor.
someProperty = loadSomeProperty();
}
@PostConstruct
public void init() {
// Or in @PostConstruct (Will be invoked AFTER construction and dependency/property injection).
someProperty = loadSomeProperty();
}
public void change(ValueChangeEvent event) {
// Or in some FacesEvent method.
someProperty = loadSomeProperty();
}
public void listener(AjaxBehaviorEvent event) {
// Or in some BehaviorEvent method.
someProperty = loadSomeProperty();
}
public String submit() {
// Or in Action method.
someProperty = loadSomeProperty();
return "outcome";
}
public SomeObject getSomeProperty() {
// Just keep getter untouched. It isn't intented to do business logic!
return someProperty;
}
}
If there are for you really no other ways, due to some restrictive design requirements, then you should introduce lazy loading inside the getter method. I.e. if the property is null, then load and assign it to the property, else return it.
public SomeObject getSomeProperty() {
// If there are really no other ways, introduce lazy loading.
if (someProperty == null) {
someProperty = loadSomeProperty();
}
return someProperty;
}
This way the expensive DB/business logic won't unnecessarily be executed on every single getter call.
http://stackoverflow.com/questions/2090033/why-jsf-calls-getters-multiple-times/2090062#2090062
The getter, as its name already self-describes, is just there with the pure purpose to retrieve the data. JSF doesn't cache this data. It will call it whenever needed. The cost of calling a getter is in practice nihil --unless you do something more than returning the data, e.g. hitting the DB everytime, this logic should then be moved out of the getter or be turned into lazy loading.
http://stackoverflow.com/questions/2786834/between-a-jsf-page-and-a-managed-bean-why-the-getter-method-is-called-twice
session-scoped solution?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
…
<h:body>
…
<fieldset>
<legend>Bank Customer Lookup (Request Scope)</legend>
<h:form>
Customer ID:
<h:inputText value="#{bankingBean.customerId}"/><br/>
Password:
<h:inputSecret value="#{bankingBean.password}"/><br/>
<h:commandButton value="Show Current Balance"
action="#{bankingBean.showBalance}"/>
</h:form>
</fieldset>
…
</h:body></html>
http://courses.coreservlets.com/Course-Materials/pdf/jsf/jsf2/JSF2-Managed-Beans-1.pdf
- Giving Custom Names to Beans
The name attribute of @ManagedBean
@ManagedBean(name="anyName")
public class BeanName { … }
– You refer to bean with #{anyName.blah}, where bean
name is exact value of name attribute.
• Still request scoped by default.
• Still no entries in faces-config.xml
Bean Scopes
dea
– Designates how long managed beans will stay “alive”,
and which users and requests can access previous bean
instances.
• JSF 1.x scopes
– Request, session, application
– Specified in faces-config.xml
– Request scope is the default
• JSF 2.0 scopes
– request, session, application, view, none, custom
– Specified either in faces-config.xml or by one of the new
annotations (e.g., @SessionScoped)
– Request scope is still the default
Annotations to Specify Bean Scope
@RequestScoped
– Default. Make a new instance for every HTTP request.
Since beans are also used for initial values in input form,
this means bean is generally instantiated twice (once
when form is displayed, once when form is submitted).
• @SessionScoped
– Put bean in session scope. If same user with same cookie
(JSESSIONID) returns before session timeout, same bean
instance is used. You should make bean Serializable.
• @ApplicationScoped
– Put bean in application scope. Shared by all users. Bean
either should have no mutable state or you must carefully
synchronize access. Usually immutable
@ViewScoped
– Same bean instance is used as long as same user is on
same page (e.g., with event handlers or Ajax).
• New scope in JSF 2.0.
• Bean should implement Serializable
• @CustomScoped(value="#{someMap}")
– Bean is stored in the Map, and programmer can control
lifecycle.
• New scope in JSF 2.0
• @NoneScoped
– Bean is not placed in a scope. Useful for beans that are
referenced by other beans that are in scopes.
• New scope in JSF 2.0
No automatic access to request & response
– JSF action controller methods do not have direct access
• Unlike in Struts, where action controller method (execute)
gets request and response automatically
@ManagedProperty:
JSF supports simple dependency injection
– That is, you can assign values to a managed bean
property (i.e., a value the main bean depends on) without
hardcoding it into the class definition
• Not as powerful as with Spring, but still useful
– @ManagedProperty lets you do this with annotations
• @ManagedProperty(value="#{someBean}")
private SomeType someField;
– <managed-property> lets you do it in faces-config.xml
• This is same as in JSF 1.x
faces-config better than annotations (?)
– One of the points of dependency injection is to let you change the concrete
class without changing Java code
• Using annotations in the Java code partially violates that principle
– faces-config.xml lets you specify Map elements
• The annotation does not
Spring is best of all (?)
– For situations that warrant the extra complexity, Spring has nice JSF
integration, so you can directly use Spring configuration files (e.g.,
applicationContext.xml)
http://courses.coreservlets.com/Course-Materials/pdf/jsf/jsf2/JSF2-Managed-Beans-2.pdf
- Pros and Cons of Explicit Bean Declarations
@ManagedBean
– Simpler/faster to start with
– Java developer knows the bean name
• Explicit declarations in faces-config.xml
– Easier for facelets developer to find bean
• If you have a large project with many packages, even knowing the
bean class name (as with @ManagedBean) requires you to search
many packages to find the class
– Can use multiple instances of the same bean class in the same page.
See temperature converter in first PrimeFaces lecture for example.
– Can use same class in different pages with different scopes
– Better understanding of beans used in project
• One central file lists all managed beans
Debugging strategies
– Set PROJECT_STAGE to Development in web.xml
• This is already set in jsf-blank
– Many of the errors cause the process to abort at certain
points. Knowing how far things got is very helpful.
• Use print statements or IDE breakpoints
• Put a print statement in the action controller method
• Put a print statement in the empty constructor
– public MyBean() { System.out.println("MyBean built"); }
– Bean should be instantiated twice for request scope
• Put print statements in the bean setter methods
JSF2-Page-Navigation.pdf
http://www.coreservlets.com/JSF-Tutorial/jsf2/
- The Expression Language
JSP scripting not supported in facelets
– So, you need a way to indirectly invoke Java
Passing arguments
– Version 2.1 of the EL lets you pass arbitrary arguments to
methods. Works only in Java EE 6 or other servers that
support EL 2.1. Not part of JSF 2 itself.
• E.g, works in Tomcat 7 but not Tomcat 6, even though
JSF 2 works in both
Outputting Simple Bean Properties
Format
– #{varName.propertyName}
– <h:outputText value="#{varName.propertyName}" …/>
• For new JSF 2 code, top version is usually used unless
you need some other attribute of h:outputText (e.g. “id”,
“rendered”, or “escape”)
• Interpretation
– First, find varName
• Search for “varName” in all defined scopes, from most
specific to most general (request, session, application, in
that order for standard Web app scopes). Then look in
managed bean defs and instantiate if found.
– Call getPropertyName and output the result
• This must be a normal zero-arg accessor method. If
boolean, name of method could be is PropertyName
Understanding Getter vs. Setter Method Correspondence
Example
– <h:inputText value="#{myBean.a.b.c.d}"/>
• When displaying form
– Find or instantiate myBean. Call getA. Call getB on
result. Call getC on that result. Call getD on that result. If
non-empty use as initial value of textfield.
• When submitting form
– Find myBean (instantiate new version if in request
scope). Call getA. Call getB on result. Call getC on that
result. Then pass submitted value to the setD method of
that result.
• Point: only final one becomes setter on submission.
• This assumes value passes validation. Discussed later
Equivalent forms
– #{name.property}
• Only legal if “property” would be legal Java variable name
– #{name["property"]}
• Reasons for using bracket notation
– To access arrays, lists, and other collections
• See upcoming slides
– To calculate the property name at request time.
• #{name1[name2]} (no quotes around name2)
– To use names that are illegal as Java variable names
• #{foo["bar-baz"]}
• #{foo["bar.baz"]}
Works for
– Array. Equivalent to
• theArray[index] (getting and setting)
– List. Equivalent to
• theList.get(index) or theList.set(index, submittedVal )
– Map. Equivalent to
• theMap.get(key) or theMap.put(key, submittedVal )
• Equivalent forms (for Maps)
– #{stateCapitals["maryland"]}
– #{stateCapitals.maryland}
– But you can’t use this for lists (numbers are not legal Java
variables names, so #{listVar.2} is illegal). And not all
hash table keys are legal variable names. So, use brackets
EL version 2.2 lets you call regular methods
– Rather than only zero-arg accessor methods
• Syntax
– Basic syntax is straightforward
• #{someBean.someMethod(arg1, arg2)}
– The arguments can also be EL expressions
• Cautions
– Use sparingly: put complexity in Java, not facelets
– Works only in EL 2.2. Not part of JSF 2.0 itself.
• Server must support servlets 3.0
– All Java EE 6 servers automatically do
• So, works in Glassfish 3, JBoss 6, and Tomcat 7.
Fails in Tomcat 6, JBoss 5, and other servlet 2.5 engines
JSF2-Expression-Language.pdf
http://www.coreservlets.com/JSF-Tutorial/jsf2/
- Simple Messages
Idea
– Store some fixed strings in a simple plain-text file. Load
that file and refer to the strings by the names given in the
file.
• Purpose
– Reuse same strings in multiple pages.
– Update in one fell swoop.
• Notes
– Bean properties are for values that change at runtime.
– Entries in properties files are much simpler strings that
are constant for the life of the application, but either
appear multiple places or might change some time in the
future.
Create a .properties file
• Contains simple keyName=value pairs
• Must be deployed to WEB-INF/classes
• In Eclipse, this means you put it in “src” folder
Declare with resource-bundle in faces-config
– base-name gives base file name relative to “src” (classes)
– var gives scoped variable (Map) that will hold results
• E.g., for WEB-INF/classes/messages.properties
<application>
<resource-bundle>
<base-name>messages</base-name>
<var>msgs</var>
</resource-bundle>
</application>
Output messages using normal EL
– #{msgs.keyName}
firstNamePrompt=Enter first name
lastNamePrompt=Enter last name
emailAddressPrompt=Enter email address
This is a single line in actual file. You can break long lines
into multiple lines by putting \ at the end of a line.
• At runtime, this will be
…/WEB-INF/classes/messages1.properties
• faces-config.xml will load this with (inside “application” element)
<resource-bundle>
<base-name>messages1</base-name>
<var>msgs1</var>
</resource-bundle>
• Facelets page will output messages with
– #{msgs1.firstNamePrompt}
Parameterized Messages
Idea
– Store some strings in a simple plain-text file. Load that
file and refer to the strings by the names given in the file.
Allow portions of the strings to be replaced.
• Purpose
– Make strings more flexible by having one string refer to
another.
– Allow runtime values to be inserted into strings.
• Particularly useful for prompts and error messages
• Notes
– These are no longer purely static strings. However, the
basic outline of the string is still fixed, so they are
different from bean properties, which are very dynamic
Create a .properties file in src
– Values contain {0}, {1}, {2}, etc.
– E.g., someName=blah {0} blah {1}
• Reminder: “src” in Eclipse becomes WEB-INF/classes when deployed
Output messages using h:outputFormat
– value gives base message
– Nested f:param gives substitution values. These can be literal
strings or runtime values
– E.g.:
<h:outputFormat value="#{msgs.someName}">
<f:param value="Literal value for 0th entry"/>
<f:param value="#{someBean.calculatedValForEnty1}"/>
</h:outputFormat>
You must define f: namespace
– Since the tag uses a different prefix (f:), you must define
the f: namespace in the <html…> tag at the top
– We did this in some earlier sections when we used
f:selectItems inside of h:selectOneMenu
Example
<!DOCTYPE …>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>…</h:head>
<h:body>…</h:body>
</html>
Internationalization and Messages
Store some multiple versions of properties file
(msg.properties, msg_es.properties,
msg_es_mx.properties, etc.)
• Base properties file gets loaded (e.g., msg.properties) .
Then one most loosely matching current Locale, if any
(e.g., msg_es.properties), then one more specifically
matching, if any (e.g., msg_es_mx.properties). If same
name occurs in more than one file, later file wins.
Purpose
– Let page be displayed in multiple languages
Use f:view and locale attribute
<f:view locale="#{facesContext.externalContext.requestLocale}">
– Determines locale from browser language settings
– Note: can also set the Locale based on user input
Getting Properties from
Database
• Idea
– Instead of using properties file, it is also possible to use
Java code to get properties (often from a database)
• faces-config.xml
– <message-bundle>
somepackage.SomeCustomBundle
</message-bundle>
• Java
– Extend ResourceBundle
– Override handleGetObject and getKeys
• Details
– http://stackoverflow.com/questions/9080474/
messages-properties-taken-from-db
Deploy one or more .properties files
– In Eclipse, you put .properties file in “src” folder, and it gets deployed to WEB-INF/classes automatically
• Declare with resource-bundle in faces-config
<application>
<resource-bundle>
<base-name>someFile</base-name>
<var>someVar</var>
</resource-bundle> …
</application>
• Output values using normal EL
– #{someVar.someNameFromFile} for simple values
– h:outputFormat for parameterized values
• Set view’s locale if I18N needed
– Extract it from browser setting or user setting
• We’ll cover user settings in section on event handling
– Automatically loads locale-specific resource bundle
JSF2-Properties-Files.pdf
http://www.coreservlets.com/JSF-Tutorial/jsf2/
- For option 2 Mastering JavaServer Faces says a JSF implementation will next "look for a context initialization parameter named javax.faces.application.CONFIG_FILES in the web.xml file for one or more JSF configurations that should be loaded. The value of this parameter is a comma delimited list of context relative resource paths (each starting with /). This particular method is useful when you wish to split up a large JSF application into manageable pieces."
Bingo! Exactly what we're looking for. The text then goes onto suggest on how to do this in your web.xml file with the following example:
<context-param>
<param-name>javax.faces.application.CONFIG_FILES</param-name>
<param-value>
/WEB-INF/faces-config1.xml,
/WEB-INF/faces-config2.xml
</param-value>
</context-param>
http://one-size-doesnt-fit-all.blogspot.com/2007/01/using-multiple-faces-configxml-files-in.html
- There are 2 varieties of user interface events
– Events that start back-end processing
– Events that affect only the format of the user interface
JSF categorizes code that handles these as
action controllers and event listeners
– Action controllers handle main form submission
• Fire after bean has been populated (see previous section)
• Fire after validation logic (see upcoming section)
• Return strings that directly affect page navigation
– Event listeners handle UI events
• Often fire before bean has been populated
• Often bypass validation logic
• Never directly affect page navigation
Event Handlers vs. Ajax
However, Ajax is sometimes even better
– Some of the situations where event handlers apply
result in only a small number of elements changing
– In that case, Ajax often yields a more interactive user
experience
• If you need to update the entire page, use event listeners.
If you need to update only part of the page, use Ajax.
JSF2-Event-Handling.pdf
http://www.coreservlets.com/JSF-Tutorial/jsf2/
- td>Keyword:
<h:inputText value="#{bidBean2.keyword}"
required="true"
requiredMessage="You must enter a keyword"
id="keyword"/></td>
<td><h:message for="keyword" styleClass="error"/></td></tr>
Value of requiredMessage can be an EL expression, so you can use properties files for localized error messages. See tutorial section on properties and I18N.
Writing Your Own Validator
Methods
• Facelets
– For input component, specify method name explicitly
• <h:inputText id="someID"
validator="#{someBean.someMethod}"/>
– Use h:message as before
• <h:message for="someID"/>
Summary
• Validation in action controller
– When validation linked to business logic, or when you are
comparing values of multiple fields
• But, the lowest-level and most tedious of the 4 approaches
• Type conversion (and “required”)
– When it is enough to simply enforce types
(counting non-empty as a type)
• Explicit f:validateBlah tags
– When you are checking one field at a time, and want to
enforce values are in certain ranges or satisfy a regex
• Making your own validator methods
– When you are checking one field at a time, but want to
perform complex tests not built into any of the tags
JSF2-Validation.pdf
http://www.coreservlets.com/JSF-Tutorial/jsf2/
- Violating the MVC Model
– Java code that builds HTML is always bad
@ManagedBean(eager=true)
Since we are not reading any form data and this
dummy data never changes, we might as well make
it application-scoped and pre-instantiated. That is
what “eager=true” does.
JSF2-Looping.pdf
http://www.coreservlets.com/JSF-Tutorial/jsf2/
- Need for Page Templating
Avoiding repetition in facelets pages
– OOP provides good reuse for Java code.
– But what about facelets code?
• Also want to avoid repeating nearly-identical code there
• Very common to have multiple pages that share the same
basic layout and same general look
Inadequacies of jsp:include
– JSF pages normally eschew JSP tags
– Even if you use jsp:include, it has problems
• No real templates or named sections (ala Struts Tiles)
• Can’t easily pass data to included pages
Template file
– Directly insert content that will be used by all clients
– Mark replaceable regions with ui:insert
• Client file
– Use ui:composition to designate template that is used
– Override replaceable regions with ui:define
– Insert snippets with ui:include
• Relative URLs in templates
– Hypertext links: <a href="#{request.contextPath}/…"/>
– Images: <h:graphicImage name="…" library="…"/>
– CSS: <h:outputStylesheet name="…" library="…"/>
– Scripts: <h:outputScript name="…" library="…"/>
JSF2-Facelets-Templating
http://www.coreservlets.com/JSF-Tutorial/jsf2/
- JSF 2.0 added “composite components”
– Reusable, named chunks of facelets code
– Can pass arguments
JSF2-Composite-Components-1
http://www.coreservlets.com/JSF-Tutorial/jsf2/
- Wrapping Up JavaScript GUI Elements: Idea
Motivation
– If you need a rich GUI element (slider, popup calendar,
etc.) that is not already part of your JSF library
Options
– Look at existing component libraries
• PrimeFaces, RichFaces, IceFaces, OpenFaces,
Tomahawk, Trinidad, etc.
– Use an element from jQuery UI, Ext/JS, Dojo, YUI etc.
• But wrap it up so that it can be used like a normal JSF
component.
JSF2-Composite-Components-4
http://www.coreservlets.com/JSF-Tutorial/jsf2/
- f:viewParam lets you associate bean
properties with request parameters
– This introduces several new capabilities
• New tags that navigate via GET instead of POST, and
send parameters along with the address
• Sending data from non-JSF forms to JSF pages
• Make results pages bookmarkable
– This is a new feature in JSF 2.0
Motivation
f:viewParam lets you:
– Make links or buttons that pass parameters to pages
• E.g., you could make different links to the same JSF
but specify colors, languages, or simple variables
Make JSF pages accessible from forms in non-JSF apps
• But the forms would normally need to send simple values,
since you lose the strong association with bean properties
in the forms, and you lose JSF’s validation capabilities
– Bookmark results pages
• Use POST-redirect-GET to expose data needed in results
pages as GET parameters. Can save page in favorites.
• f:viewParam does not let you:
– Make h:form use GET instead of POST
– Access any random JSF page with GET
JSF2-View-Params
http://www.coreservlets.com/JSF-Tutorial/jsf2/
- Defining beans in two places
– JSF backing beans in faces-config.xml
– Spring beans in applicationContext.xml
• Defining beans in one place only• Defining beans in one place only
– All beans in applicationContext.xml
What is Spring?
Core module: dependency injection
Lets you define an XML file that specifies which beans– Lets you define an XML file that specifies which beans
are created and what their properties are
• Simplifies OOP by promoting loose coupling between
classes Also called “Inversion of Control” (IoC)
You are Using JSF Already: Why Use Spring?
JSF already supports dependency injection via the
managed-property element of faces-config.xml
• So why use Spring to do what JSF already does?
You might already have beans set up with Spring from gy ppg
other applications
• And you would like to use them without adding new code
Spring is more powerful– Spring is more powerful
• Spring supports more and better dependency injection
features than does faces-config.xml
You are Using Spring Already:
Why Use New Approach?
Issue
– Normal Spring already supports ways to access beans.
• So why add a new way for JSF?
Reasons• Reasons
– You need to access bean definitions from many places
• With desktop Java apps, you can have a single piece of ppp,y gp
code that instantiates the container and gets beans
– I.e., driver class that instantiates ClassPathXmlApplicationContext
and calls getBean
• With JSF apps, each controller wants access to beans
– But you want to instantiate container once only
– You need additional bean scopesYou need additional bean scopes
• Standard Spring supports singleton and prototype
• JSF apps also want request, session, and application
JSF2-Using-Spring
http://www.coreservlets.com/JSF-Tutorial/jsf2/
- If you using myfaces then you need myfaces-api.jar and myfaces-impl.jar in your classpath, which you can download from http://myfaces.apache.org/download.html
Just use the JAR files which are provided/required by the JSF implementation you choose to use. Just download the implementation and read their own installation/users guide if you don't actually need more JAR files (as dependencies).
As of now there are only two major JSF implementations: Mojarra and MyFaces. The number of JAR files may vary per implementation and even version. Ultimately you need to make sure that you have both the JSF API and JSF implementation (which may exist of 2 or even 1 JAR file, depending on impl/version). MyFaces requires more commons-*.jar dependencies while Mojarra doesn't require any additional dependencies.
Since JSF 2.0, Facelets is bundled with the JSF implementation and has replaced JSP as default view technology.
The jsf-api-xxx.jar contains classes that are under packages java package javax.faces
The classes in this jar are implementation of standard API defined by JSF specification
The jsf-impl-xxx.jar contains classes that are under java package com.sun.faces,
which as the java package indicates, is Sun's own class for JSF implementation.
The javax.faces-xxx.jar actually merges the previous two jar files together.
In the Maven repository, it is under org.glassfish groupId.
You will find both javax.faces and com.sun.faces java package inside.
http://stackoverflow.com/questions/15561352/what-is-the-difference-between-javax-faces-2-1-14-jar-from-jsf-api-2-2-0-m05-jar