Está en la página 1de 14

JSF:

* JSF is a standard from Java community process for developring web UI server si
de components.
* Event driven framework built on top of Servlet API enables RAD approach.
* Events generated by user are handled on the server.
* Effectively handles UI management like input validation, component-state manag
ement, page navigation, and event handling
* Built on MVC design pattern.
View - JSP
Model - Managed beans
Controller - FacesServlet
* JavaServer Faces applications are just like any other Java web application. Th
ey run in a servlet container.
* JSF contains an API for representing UI components and managing their state; h
andling events, server-side validation, and data conversion; defining page navig
ation; supporting internationalization and accessibility -- 8.
* Offers a clean separation between behavior and presentation of components.
Life cycle:
==========
* Restore View: A request comes through the FacesServlet controller. The contro
ller examines the request and extracts the view ID, which is determined by the n
ame of the JSP page. (Components view restored or created.)
* Apply request values: The purpose of the apply request values phase is for
each component to retrieve its current state. The components must first be retr
ieved or created from the FacesContext object, followed by their values.(Submitt
ed form values are stored in component and also Component values are converted)I
f immediate=true JSF will process events.
* Process validations: In this phase, each component will have its values val
idated against the application's validation rules. if any validation/conversion
fails goes to Render Response phase.
* Update model values: In this phase JSF updates the actual values of the ser
ver-side model ,by updating the properties of your backing beans.
* Invoke application: In this phase the JSF controller invokes the applicatio
n to handle Form submissions. ( application level events hadled, application me
thods invoked,Navigation outcome calculated).
* Render response: In this phase JSF displays the view with all of its compon
ents in their current state.Component values populated from backing bean propert
ies.
* JSF supports three Bean Scopes: Request, Session, Application Scope,
* Example code for manged bean configuration in faces-config.xml
<managed-bean>
<managed-bean-name>login</managed-bean-name>
<managed-bean-class>com.developersBookJsf.loginBean</managed-bean-class
>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
* <f:loadBundle baseName = "com.developersBookJsf.messages" var="message"/>
* Navigation rules tells JSF implementation which page to send back to the br
owser after a form has been submitted. We can declare the page navigation as fol
lows:
<naviagation-rule>
<from-view-id>/index.jsp</from-view-id>
<navigation-case>
<from-outcome>login</from-outcome>
<to-view-id>/welcome.jsp</to-view-id>
</navigation-case>
</naviagation-rule>
** This declaration states that the login action navigates to /welcome.jsp, if
it occurred inside /index.jsp.
* Unlike traditional RQUEST based approch, JSF is Component based approch.
* Managed Beans are the beans created with Dependency Injection.
* JSF supports different rederers not only HTML rederer like other frameworks. R
enderers enables to display components in different ways.

FACES-CONFIG.XML
================
<faces-config>
<application>
<message-bundle>carstore.bundles.Messages</message-bundle>
<locale-config>
<default-locale>en</default-locale>
<supported-locale>de</supported-locale>
<supported-locale>es</supported-locale>
</locale-config>
</application>
<application>
<resource-bundle>
<base-name>com.corejsf.messages</base-name>
<var>msgs</var>
</resource-bundle>
</application>
<!-- Validator -->
<validator>
<description>
Registers the concrete Validator implementation,
carstore.FormatValidator with the validator
identifier, FormatValidator.
</description>
<validator-id>FormatValidator</validator-id>
<validator-class>carstore.FormatValidator</validator-class>
<attribute>
<description>
List of format patterns separated by '|'. The validator
compares these patterns against the data entered in a
component that has this validator registered on it.
</description>
<attribute-name>formatPatterns</attribute-name>
<attribute-class>java.lang.String</attribute-class>
</attribute>
</validator>
<!-- converter -->
<converter>
<description>
Registers the concrete Converter implementation,
carstore.CreditCardConverter using the ID,
creditCardConverter.
</description>
<converter-id>creditCardConverter</converter-id>
<converter-class>carstore.CreditCardConverter</converter-class>
</converter>
<!-- =================== Initialize Image Map Hotspot Data ============== -->
<managed-bean>
<description>
The "backing file" bean that backs up the guessNumber webapp
</description>
<managed-bean-name>UserNumberBean</managed-bean-name>
<managed-bean-class>guessNumber.UserNumberBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>minimum</property-name>
<property-class>int</property-class>
<value>0</value>
</managed-property>
<managed-property>
<property-name>maximum</property-name>
<property-class>int</property-class>
<value>10</value>
</managed-property>
</managed-bean>

<!-- =================== Business Logic Beans ============== -->


<managed-bean>
<description>
The main backing file mean
</description>
<managed-bean-name> carstore </managed-bean-name>
<managed-bean-class> carstore.CarStore </managed-bean-class>
<managed-bean-scope> session </managed-bean-scope>
</managed-bean>
<navigation-rule>
<from-view-id>/chooseLocale.jsp</from-view-id>
<navigation-case>
<description>
Any action on chooseLocale should cause navigation to storeFront.jsp
</description>
<from-outcome>storeFront</from-outcome>
<to-view-id>/storeFront.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<from-view-id>/customerInfo.jsp</from-view-id>
<navigation-case>
<description>
Any action that returns "finish" on customerInfo.jsp should
cause navigation to finish.jsp
</description>
<from-outcome>finish</from-outcome>
<to-view-id>/finish.jsp</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>
* <h:commandButton value="#{bundle.buy}" action="customerInfo" title="#{bundle.b
uy}" />
Here if a user presses Buy button, the outcome is always "customerInfo" , need t
o check navigation-rule for next page. This is static way of defining from-outco
me.
* JSF concept review: Action handler method is called as page navigation handler
method and contains business logic for determining the next page to display. I
t returns an outcome string, which is used by JSF implementation to determine wh
ich page to display next by looking at the navigation rules defined in the JSF c
onfiguration file.
<h:commandButton action="#{carstore.storeFrontJalopyPressed}" value="#{bundle.mo
reButton}" >
public class CarStore extends Object {
...
//
// action handlers
//
public String storeFrontJalopyPressed() {
setCurrentModelName("Jalopy");
return "carDetail";
}
...
}

* <h:inputText id="firstName" value="#{customer.firstName}" required="true">


<f:valueChangeListener type="carstore.FirstNameChanged" />
</h:inputText>
* <h:selectOneMenu id="title" value="#{customer.currentTitle}">
<f:selectItems value="#{customer.titleOptions}" />
</h:selectOneMenu>
* <h:selectOneMenu value="#{customer.state}" >
<f:selectItem itemValue="AL" itemLabel="AL" />
<f:selectItem itemValue="AK" itemLabel="AK"/>
<f:selectItem itemValue="AZ" itemLabel="AZ"/>
</h:selectOneMenu>
* <h:selectOneRadio id="country" value="#{bb.country}">
<f:selectItem itemLabel="USA" itemValue="USA"/>
<f:selectItem itemLabel="Canada" itemValue="Canada"/>
</h:selectOneRadio>
* <h:selectBooleanCheckbox value="#{form.contactMe}"/>
* <h:selectManyMenu value="#{form.bestDaysToContact}">
<f:selectItems value="#{form.daysOfTheWeekItems}"/>
</h:selectManyMenu>
* <h:selectOneListbox size="5" value="#{form.yearOfBirth}">
<f:selectItems value="#{form.yearItems}"/>
</h:selectOneListbox>
* <h:selectManyCheckbox value="#{form.colors}">
<f:selectItems value="#{form.colorItems}"/>
</h:selectManyCheckbox>
* <h:selectManyListbox value="#{form.languages}">
<f:selectItems value="#{form.languageItems}"/>
</h:selectManyListbox>
* <h:selectOneRadio value="#{form.education}"
layout="pageDirection">
<f:selectItems value="#{form.educationItems}"/>
</h:selectOneRadio>

* <h:inputText id="ccno" size="16"


converter="creditCardConverter" required="true">
<cs:format_validator
formatPatterns="9999999999999999|9999 9999 9999 9999|9999-9999-9999-99
99"/>
<h:inputText id="userNo" value="#{UserNumberBean.userNumber}"
validator="#{UserNumberBean.validate}"
valueChangeListener="#{UserNumberBean.userNoChanged}"/>
</h:inputText>
* <h:inputText value="#{payment.amount}">
<f:convertNumber type="currency"/>
</h:inputText>
* <h:inputText value="#{payment.date}">
<f:convertDateTime pattern="MM/yyyy"/>
</h:inputText>
* <h:selectBooleanCheckbox title="#{bundle.gpsLabel}"
binding="#{carstore.currentModel.components.gps}" >
</h:selectBooleanCheckbox>
<h:panelGrid columns="1"
summary="#{bundle.carDetails}"
title="#{bundle.carDetails}">
* WHAT UIComponents you have used?
<f:view> <f:form> h:panelGrid (for table format), h:inputText, h:outputTex
t, h:commandButton,

* public class CreditCardConverter implements javax.faces.convert.Converter {


public Object getAsObject(FacesContext context, UIComponent component,
String newValue) throws ConverterException {
public Object getAsString(FacesContext context, UIComponent component,
Object newValue) throws ConverterException {
WHILE CONVERSION ANY THING FAILS NEED TO DO
javax.faces.application.FacesMessage errMsg = MessageFactory.getMessage(
CONVERSION_ERROR_MESSAGE_ID,
(new Object[]{value, inputVal}));
throw new javax.faces.convert.ConverterException(errMsg.getSummary()
);
* public class FirstNameChangedextends java.lang.Objectimplements javax.faces.ev
ent.ValueChangeListener{
public void processValueChange(javax.faces.event.ValueChangeEvent event)
throws javax.faces.event.AbortProcessingException

* public class FormatValidatorextends java.lang.Objectimplements javax.faces.val


idator.Validator, javax.faces.component.StateHolder{
public void validate(FacesContext context, UIComponent component,
Object toValidate) {

* A backing bean can also contain methods that perform various functions for the
component.
ex:
* Input validator method
o Handles input validation
o If there is an input validation error, this method queues an error m
essage (to the JSF context object) which is then displayed where <h:message ..>
tag is specified
* Event handler method
o Handles events fired by components (for example, a button component
fires an event when it is pressed)
* Page selection method
o Handles page selection
o Sometimes called Action handler since it is specified as the value o
f "action" attribute
* Data type converter method
o Handles converting the types of the data

* public class PhaseTracker implements PhaseListener {


<lifecycle>
<phase-listener>tracker.PhaseTracker</phase-listener>
</lifecycle>
* <f:convertNumber minFractionDigits="2"/>
* <f:convertDateTime pattern="MM/yyyy"/>

CORE:
* four basic interfaces of the Collections framework.
The Collection interface with duplicates allowed
Set extends Collection but forbids duplicates
List extends Collection also, allows duplicates and introduces positional inde
xing
Map extends neither Set nor Collection
* Set set = aMap.keySet();

* class B extends A implements java.io.Serializable.


In this example, if B is persisted, will A also persist with values preserved?
No, in an object hierarchy if any of the class implements java.io.Serializable,
then all subclass to this class in object
graph persist. It is not required that all the subclass to implement Serializabl
e, but mandatory for the supe class (like A)
to implement Serializable.

XML:
* XML was designed to transport and store data
* XML namespaces can be used to avoid element name conflicts.
* XML CDATA hlps to store invalid XML data inside a valid XML document.
*

WEB.XML
=======
<web-app>
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
<security-constraint>
<!-- This security constraint illustrates how JSP pages
with JavaServer Faces components can be protected from
being accessed without going through the Faces Servlet.
The security constraint ensures that the Faces Servlet will
be used or the pages will not be processed. -->
<web-resource-collection>
<url-pattern>/bottomMatter.jsp</url-pattern>
<url-pattern>/storeFront.jsp</url-pattern>
</web-resource-collection>
<auth-constraint>
<description>
With no roles defined, no access granted
</description>
</auth-constraint>
</security-constraint>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>
index.jsp
</welcome-file>
</welcome-file-list>
</web-app>

HIBERNATE:
==========
* org.hibernate.Session is the main runtime interface between a Java application
and Hibernate. The main function of the Session is to offer create, read and de
lete operations for instances of mapped entity classes. Instances may exist in o
ne of three states:
transient: never persistent, not associated with any Session
persistent: associated with a unique Session
detached: previously persistent, not associated with any Session.
* Transaction tx = session.beginTransaction();
* session.cancelQuery(); -> Cancel execution of current query.
* session.clear(); -> completely clear the session.
* boolean b = session.contains(Object o); Checks if the object
is associated with the session object.
* Connection con = session.close()
End the Session by disconnecting from the JDBC connection and cleaning
up.
* org.hibernate.Criteria : Criteria is a simplified API for retrieving entities
by composing Criterion objects. This is a very convenient approach for functiona
lity like "search" screens where there is a variable number of conditions to be
placed upon the result set.
* List cats = session.createCriteria(Cat.class)
.add( Restrictions.like("name", "Iz%") )
.add( Restrictions.gt( "weight", new Float(minWeight) ) )
.addOrder( Order.asc("age") )
.list();
* List cats = session.createCriteria(Cat.class)
.setProjection( Projections.projectionList()
.add( Projections.rowCount() )
.add( Projections.avg("weight") )
.add( Projections.max("weight") )
.add( Projections.min("weight") )
.add( Projections.groupProperty("color") )
)
.addOrder( Order.asc("color") )
.list();
* SQLQuery session.createSQLQuery(String queryString)
Create a new instance of SQLQuery for the given SQL query string.
* session.evict(Object object) : Remove this instance from the session cac
he.
* void session.refresh(Object object)
Re-read the state of the given instance from the underlying database.
* SESSION: save(), saveOrUpdate(),get(),load(),delete(),
get() return null if nothing.
find() does not return null.

* TablePerClassHierarchy
======================
SpecialEditionBook extends Book
InternationalBook extends Book
book.hbm.xml
------------
<hibernate-mapping>
<class name="Book" table="Book" discriminator-value="Book">
<id name="id" type="integer" unsaved-value="0">
<generator class="increment"/>
</id>
<discriminator column="Book_type" type= "string"/>
<property name="title"/>
<property name="artist"/>
<property name="purchasedate" type="date"/>
<property name="cost" type="double"/>
</class>
</hibernate-mapping>

InternationalBook.hbm.xml
--------------------------
<hibernate-mapping>
<subclass name="InternationalBook"
extends="Book"
discriminator-value="InternationalBook">
<property name="languages" />
<property name="region" />
</subclass>
</hibernate-mapping>

TablePerSubclass
================
<hibernate-mapping>
<class name="Book" table="Book">
<id name="id" type="integer" unsaved-value="0">
<generator class="increment" />
</id>
<property name="title" />
<property name="artist" />
<property name="purchasedate" type="date" />
<property name="cost" type="double" />
</class>
</hibernate-mapping>
<hibernate-mapping>
<joined-subclass name="InternationalBook"
extends="Book" table="InternationalBook">
<key column="id" />
<property name="languages" />
<property name="region" />
</joined-subclass>

</hibernate-mapping>
* Table per Concreat class
========================
<hibernate-mapping>
<class name="Book" table="Book" discriminator-value="Book">
<id name="id" type="integer" unsaved-value="0">
<generator class="increment"/>
</id>
<property name="title"/>
<property name="artist"/>
<property name="purchasedate" type="date"/>
<property name="cost" type="double"/>
</class>
</hibernate-mapping>
<hibernate-mapping>

<class name="InternationalBook" table="InternationalBook">


<id name="id" type="integer" unsaved-value="0">
<generator class="increment"/>
</id>
<property name="title"/>
<property name="artist"/>
<property name="purchasedate" type="date"/>
<property name="cost" type="double"/>
<property name="languages"/>
<property name="region"/>
</class>
</hibernate-mapping>
MAP:
===
HibernateUtil.setup("create table supportproperty (id int,name varchar(2
0))");
HibernateUtil.setup("create table properties (id int,property_name VARCH
AR(20),property_value varchar(20))");
public class SupportProperty {
private int id;
private String name;
private Map properties;

<hibernate-mapping>
<class name="SupportProperty" table="supportproperty">
<id name="id">
<generator class="increment"/>
</id>
<property name="name" type="string"/>
<map name="properties">
<key column="id"/>
<index column="property_name" type="string"/>
<element column="property_value" type="string"/>
</map>
</class>
</hibernate-mapping>

SET:
===
setup("create table EVENTS ( uid int, name VARCHAR(20), start_Date date, dur
ation int, location_id int)");
setup("create table speakers ( uid int, event_id int, firstname VARCHAR(20),
lastName VARCHAR(20))");

public class Event {


private Long id;
private String name;
private Date startDate;
private int duration;
// Event has one-to-many relationship with Speaker
private Set speakers;
// Event has one-to-many relationship with Attendee
private Set attendees;
// Event has one-to-one relationship with Location
private Location location;

<hibernate-mapping>
<class name="Event" table="events">
<id name="id" column="uid" type="long" unsaved-value="null">
<generator class="increment"/>
</id>
<property name="name" type="string" length="100"/>
<property name="startDate" column="start_date" type="date"/>
<property name="duration" type="integer"/>
<many-to-one name="location" column="location_id" class="Locatio
n"/>
<set name="speakers" cascade="all">
<key column="event_id"/>
<one-to-many class="Speaker"/>
</set>
<set name="attendees" cascade="all">
<key column="event_id"/>
<one-to-many class="Attendee"/>
</set>
</class>
</hibernate-mapping>

<hibernate-mapping>
<class name="Speaker" table="speakers">
<id name="id" column="uid" type="long">
<generator class="increment"/>
</id>
<property name="firstName" type="string" length="20"/>
<property name="lastName" type="string" length="20"/>
</class>
</hibernate-mapping>
public class Attendee {
private Long id;
private String firstName;
private String lastName;
<hibernate-mapping>
<class name="Attendee" table="attendees">
<id name="id" column="uid" type="long">
<generator class="native"/>
</id>
<property name="firstName" type="string" length="20"/>
<property name="lastName" type="string" length="20"/>
</class>
</hibernate-mapping>

* <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCachePro
vider</property>

* Hibernate features:
1. It allows mapping classes with tables i.e. java datatypes to SQL type
s.
2. It fecilitates better data query and data retrivals i.e. generates qu
eries and relieves developer from manual resultset handling.
3. keeps application portable to all dbs.
4. It fecilitates dirty checking i.e. updates only modified fileds of th
e persistent object.

STRUTS:
=======
* <bean:message key="welcome.heading"/>
* <html:form action="/AddressJavascriptValidation" method="post" onsubmit="retur
n validateAddressForm(this);">
* built in tab libs: html, bean, tiles,
* <a href=\"javascript:history.back()\">Go to back</a>
* public void reset(ActionMapping mapping, HttpServletRequest request) {
* public ActionErrors validate(ActionMapping mapping, HttpServletRequest request
) {
ActionErrors errors = new ActionErrors();
if(----------) {
errors.add("name",new ActionMessage("error.name.required"));
}

SPRING:
=======
* ApplicationContext implementations : ClassPathXmlApplicationContext , FileSyst
emXmlApplicationContext , XmlWebApplicationContext
* BeanFactory factory = new XmlBeanFactory(new FileInputStream("beans.xml"));
* An aspect is the cross-cutting functionality
* org.springframework.web.servlet.view.InternalResourceViewResolver
* org.springframework.web.servlet.handler.SimpleUrlHandlerMapping
* public class LogonController extends SimpleFormController{
public ModelAndView onSubmit(Object command) throws ServletException {
* ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("conte
xt.xml");
* org.springframework.orm.hibernate3.support.HibernateDaoSupport

LOGGING:
=======
* Applications make logging calls on Logger objects.
* The Logger object create LogRecord object which are then passed to Handler obj
ects for publication.
* Both Logger and Handler objects optionally use Filter(To filter certain logs r
ecords) and Formatters(for localization).
*

Servlet:
========
A "web application is a collection of servlets and content installed under a spe
cific subset of the server's URL
namespace and possibly installed via a *.war file
ex: All servlets in BookStore web application share same ServletContext object
* There is one ServletContext object per "web application" per Java Virtual Mach
ine
You can also get request dispatcher object from the ServletContext object. And
you use a request dispatcher object in order to forward a HTTP request to
another web component or include the output of another web component.
* http://[host]:[port]/[requestpath]?[querystring]

También podría gustarte