четверг, 26 апреля 2012 г.

JSF HTML tag library - OutputText


h:outputText

The outputText tag renders basic text on your JSF page. You can customize it using standard attributes of h:outputText tag. You can add styles to it. Define the logic when it will be rendered. Also, if your output text will render some HTML code from the database, in order to render it appropriately you would set escape attribute to false.


Example


<h:outputText value="#{yourbean.hello}" />

HTML Output


Hello message of your bean!

Tag Attributes

bindingExpression
 
The value-binding expression linking this component tag to a backing bean property.
converterText
 
The converter attribute sets the converter instance to be registered for this component. It must match the converter-id value of a converter element defined in your Faces configuration file.
escapeBoolean
 
The escape attribute is a boolean flag that determines if sensitive HTML and XML characters should be escaped in the ourput generated by this component. The default value for this attribute is "true".
idText
 
The unique identifier value for this component. The value must be unique within the closest naming container.
renderedBoolean
 
A value-binding expression that evaluates to a Boolean condition indicating if this component should be rendered.
styleCSS Style
 
The style attribute sets the CSS style definition to be applied to this component when it is rendered.
styleClassCSS Class
 
The styleClass attribute sets the CSS class to apply to this component when it is rendered.
titleText
 
The title attribute is a standard HTML attribute that sets the tooltip text to display for the rendered component.
valueText
 
The value attribute sets the current value for this component.

JSF Tutorials: JSF 2 Lifecycle

JSF 2 Lifecycle


JSF 2 lifecycle


Restore view

RestoreView is the first phase in the JSF lifecycle. Restore view phase is constructing view for the front end. Every view has it's own view id and it is stored in the FacesContext's session object. JSF View is collection of components associated with its current state. In JSF 2 you have two types of saving methods:
  1. Server (default)
  2. Client
Server method is set by the default. You can configure it in web.xml as context param using javax.faces.STATE_SAVING_METHOD parameter name:
<context-param>
            <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
            <param-value>client</param-value>
</context-param>

Apply Requests

After restoring the component tree, each component in the tree extracts its new value from the request parameters by using its decode method. After that the value is locally stored in the component. If the conversion of the value fails, an error message associated with the component is generated and queued on FacesContext. This message will be displayed during the render response phase, along with any validation errors resulting from the process validations phase.

Process Validations

In Process Validations phase JavaServer Faces implementation processes all validators registered on the components in the component tree. It examines the component attributes that specify the rules for the validation and compares these rules to the local value stored for the component.

Update Model Values 

After JSF validates the data, it can set component tree corresponding server-side object properties to the components' local values. The JavaServer Faces implementation will update only the bean properties pointed at by an input component's value attribute.
If it is impossible to covert the local data  to the types specified by the bean properties, the life cycle advances directly to the render response phase so that the page is rerendered with errors. Same happens to the validation errors.

Invoke Applications

During Invoke Application phase, the JSF handles any application-level events, such as submitting a form or linking to another page.
At this point, if the application needs to redirect to a different web application resource or generate a response that does not contain any JavaServer Faces components, it can call FacesContext.responseComplete.

Render Response 

During Render Response phase, JavaServer Faces gives authority for rendering the page to the JSP container if the application is using JSP pages. If this is an initial request, the components represented on the page will be added to the component tree as the JSP container executes the page. If this is not an initial request, the components are already added to the tree so they needn't be added again.

понедельник, 23 апреля 2012 г.

JSF Примеры - создание шаблонов

При разработке веб приложения большинство страниц выглядят одинаково. Вместо того что-бы не создавать кучу ненужного кода, используются шаблоны. В JSF 2 предусмотрена гибкая система шаблонов. В основном мы будем использовать Facelet теги, такие как:

1. ui:composition - при добавлении аттрибута "template" ваша страница будет использовать шаблон указанный в значении аттрибута.
2. ui:insert - определяет область в которую будет вставлена информация в шаблон из страницы (аттрибут "name" тегов ui:insert и ui:define должны совпадать).
3. ui:define - Определяет область страницы, которая будет вставлена в шаблон.
4. ui:include - вставляет код отдельной страницы.

Базовая структура шаблона

<!DOCTYPE composition 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:ui="http://java.sun.com/jsf/facelets" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:p="http://primefaces.org/ui" xmlns:pretty="http://ocpsoft.com/prettyfaces">


<h:head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <h:outputStylesheet library="css" name="layout.css"></h:outputStylesheet> <ui:insert name="pageHeader" /></h:head><h:body>
<ui:insert name="headerBlock" />
                                <ui:include src="/pages/includes/defaultHeader.xhtml" /> 

        
</ui:insert>

<div id="content"> <ui:insert name="contentBlock">
                                                    <ui:include src="/pages/includes/defaultContent.xhtml" />

                                          </ui:insert> 
</div></h:body></html>

Это структура шаблона, которую я обычно использую. В head мы будем вставлять css для определенных страниц. Тэг ui:insert определяет область куда будет вставляться контент. Если для тэга ui:insert не указан соответствующий тэг ui:define, то по стандарту будет использоваться код находящийся внутри ui:insert. К примеру, в данном случае если мы не укажем <ui:define name="headerBlock">, то по стандарту будет использоваться  <ui:include src="/pages/includes/defaultHeader.xhtml" />.


Пример страницы с использованием шаблона



<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
template="/layout/template.xhtml">
        
<ui:define name="pageHeader">

          


<h:outputStylesheet library="css" name="page1.css"></h:outputStylesheet>
</ui:define>
        <ui:define name="headerBlock">

          This is the content of headerBlock.
</ui:define>
<ui:define name="contentBlock">
          This is the content of contentBlock.
</ui:define>

</ui:composition>
Для того что-бы ваша страница использовала шаблон необходимо добавить аттрибут template в тело тэга ui:composition.

Зная выше перечисленное вы сможете еффективно создавать шаблоны с помощью JSF 2 Facelets.

С уважением,
Netlink community member

Understanding JSF - Part 4 - Templating

When developing a web application your pages will usually look a same. In this JSF 2 tutorial you will see how to create templates in JSF. In JSF we do this with a set of Facelet tags:

1. ui:composition - by adding an attribute "template" your page will use a template you have created.
2. ui:insert - defines the area where the code will be inserted into the template from a specific page.
3. ui:define - defines the area which will be included into the template.
4. ui:include - inserts a code from the separate file.

Basic structure of the template

<!DOCTYPE composition 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:ui="http://java.sun.com/jsf/facelets" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:p="http://primefaces.org/ui" xmlns:pretty="http://ocpsoft.com/prettyfaces">


<h:head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <h:outputStylesheet library="css" name="layout.css"></h:outputStylesheet> <ui:insert name="pageHeader" /></h:head><h:body>
<ui:insert name="headerBlock" />
                                <ui:include src="/pages/includes/defaultHeader.xhtml" /> 

        
</ui:insert>

<div id="content"> <ui:insert name="contentBlock">
                                                    <ui:include src="/pages/includes/defaultContent.xhtml" />

                                          </ui:insert> 
</div></h:body></html>

This is a basic template structure I usually use. In the head we would include a page specific CSS.
Tag ui:insert defines where a content will be inserted. If no ui:define tag have been defined for the ui:insert, the content which lies inside the ui:insert tag will be used as a default. So in this case if in our page we do not define "headerBlock", defaultHeader.xhtml will be used as a default.

Example of page which uses template


<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
template="/layout/template.xhtml">
       
<ui:define name="pageHeader">

          

<h:outputStylesheet library="css" name="page1.css"></h:outputStylesheet>
</ui:define>
        <ui:define name="headerBlock">
          This is the content of headerBlock.
</ui:define>
<ui:define name="contentBlock">
          This is the content of contentBlock.
</ui:define>

</ui:composition>
In order for your page to use a template you have to add a template attribute to your ui:composition tag.

Knowing only this concepts you will be able to effectively use JSF 2 Templating system.

Best regards,
Netlink community member

четверг, 19 апреля 2012 г.

Введение в JSF - Часть 3 - Область видимости бина

Этот пост является продолжением уроков по JSF. Если вы только присоеденились, советую прочитать предидущие уроки. В этом уроке мы разберем область видимости бинов. При разработке приложения у каждого компонента есть свое предназначение и оно не вечно. Контейнер JSF предоставляет 3 области видимости бинов:

1. Область видимости действия
2. Область видимости сессии
3. Область видимости приложения

Так же существуют такие области видимости как область видимости страница и область видимости диалого. Их мы расмотрим позже в отдельности.

Для того что-бы определить область видимости бина используются следующие аннотации:
@RequestScope
@SessionScope
@ApplicationScope

Session scope


Обозначает то ваш бин будет хранится до окончания сеанса. Такой тип обычно используется для хранения информации о пользователе лил если у вас интернет магазин, для тележки покупок. Вы можете наглядно посмотреть как используется данная область видимости в предидущем уроке.

Request scope


Самы распростроненная область видимости. Используется почти при каждом действии. К примеру, добавление информации в базу данных, извлечении и удалении.

Application scope


Область видимости приложения используется в том случае если вы хотите хранить какую-либо информацию на протяжении жизни приложения. 


Best regards,
Netlink community member

Understanding JSF - Part 3 - Bean scope

This post is a continuation of JSF tutorials series. If you are new to jsf I would recommend you to read the previous jsf tutorials. In this session I will explain bean scopes in jsf. When you are developing an application you have a variety of components, each for a different task. In order to make those components work as they have to we have scopes. We can define 3 scopes for JSF and CDI beans:

1. Request scope
2. Session scope
3. Application scope

In JSF 2 we also have View scope and Conversation scope. 

In order to assign a scope for your bean you would use the following annotations during declaration:
@RequestScope
@SessionScope
@ApplicationScope

Session scope


If the Session scope is declared your bean will be held until the session is over. This type of scope is usually used in order to store user data during the session, or for example in a web store you would use session scope in order to store the items in the shopping cart.

Request scope


Request scope is the most common scope. You would use it practically in every action like saving information to the database, retrieving it, deleting it and so on. 

Application scope


Application scope indicates that the information of the bean will be stored starting from the moment the application has been launched and until it is stopped. 

Best regards,
Netlink community member

вторник, 17 апреля 2012 г.

Sending mail from JSF - Seam mail

In this tutorial I would like to describe how to send mail from your jsf contact form.

There are a lot of solutions to this problem. But on my practice I really liked SEAM Mail.






There are a few things you have to do.

1. Download Seam libraries
2. Add seam-beans.xml to your WEB-INF folder of your project with the following content:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:s="urn:java:ee" xmlns:mail="urn:java:org.jboss.seam.mail.core"
xmlns:ss="urn:java:org.jboss.seam.security" xmlns:ee="urn:java:ee"
xsi:schemaLocation="
      http://java.sun.com/xml/ns/javaee
      http://docs.jboss.org/cdi/beans_1_0.xsd">


<mail:MailConfig serverHost="yoursmtpserveripaddress" serverPort="25">
</beans> 

3. Use the following to send mail:

package org.netlink.view.registration;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.enterprise.inject.Instance;
import javax.inject.*;
import org.jboss.seam.mail.api.*;
import org.jboss.seam.mail.core.enumerations.MessagePriority;
public class MailAction implements Serializable {
@Inject
private Instance<MailMessage> mailMessage;
     
public void sendMail() {

   MailMessage m = mailMessage.get();
   m.from("John Doe<customer@mysite.com>")
      .to("Jane Doe<admin@ mysite.com >")
      .subject(subject)
      .bodyHtml(body)
      .importance(MessagePriority.HIGH)
      .send();
}
}
Now use sendMail() method where ever you want.

Best regards,
Netlink community member