JSF

JSF построен в на паттерне MVC.
JSF Architecture
Жизненный цикл JSF
В жизненном цикле JSF выделяют следующие фазы:
• Restore View(восстановление Вида) — восстанавливает или создает дерево компонентов в памяти на стороне сервера, которое будет представлять пользовательский интерфейс клиента и информацию в нем;
• Apply Request Values (Применение значений запроса) — обновляет компоненты UIна стороне сервера, записывая в них свежие данные, пришедшие со стороны клиента;
• Process Validations (Выполнение проверок) — проводит проверки и преобразует данные и их типы к требуемым на стороне сервера;
• Update Model Values(Обновление значений Модели) — обновляет объекты Модели на стороне сервера, передавая им новые данные (проверенные и преобразованные);
• Invoke Application (Выполнение приложения) — выполняет логику приложения, необходимую для исполнения запроса и перехода на какую-нибудь страницу (если это необходимо, конечно);
• Render Response (Формирование ответа) — сохраняет состояние и формирует ответ клиенту, который послал запрос.
<dependencies>
  <dependency>
  <groupId>com.sun.faces</groupId>
  <artifactId>jsf-api</artifactId>
  <version>2.1.7</version>
  </dependency>
  <dependency>
  <groupId>com.sun.faces</groupId>
  <artifactId>jsf-impl</artifactId>
  <version>2.1.7</version>
  </dependency>
</dependencies>  <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns="http://java.sun.com/xml/ns/javaee" 
   xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
   http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   id="WebApp_ID" version="2.5">
   <welcome-file-list>
      <welcome-file>faces/home.xhtml</welcome-file>
   </welcome-file-list>
   <!-- 
      FacesServlet is main servlet responsible to handle all request. 
      It acts as central controller.
      This servlet initializes the JSF components before the JSP is displayed.
   -->
   <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>*.jsf</url-pattern>
   </servlet-mapping>
   <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>*.xhtml</url-pattern>
   </servlet-mapping>
</web-app>
Простой ПРИМЕР!
package com.tutorialspoint.test;

import javax.faces.bean.ManagedBean;

@ManagedBean(name = "helloWorld", eager = true)
public class HelloWorld {
   public HelloWorld() {
      System.out.println("HelloWorld started!");
   }
   public String getMessage() {
      return "Hello World!";
   }
}
<!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">
<head>
   <title>JSF Tutorial!</title>
</head>
<body>
   #{helloWorld.message}
</body>
</html>
ScopeDescription
@RequestScopedBean lives as long as the HTTP request-response lives. It get created upon a HTTP request and get destroyed when the HTTP response associated with the HTTP request is finished.
@NoneScopedBean lives as long as a single EL evaluation. It get created upon an EL evaluation and get destroyed immediately after the EL evaluation.
@ViewScopedBean lives as long as user is interacting with the same JSF view in the browser window/tab. It get created upon a HTTP request and get destroyed once user postback to a different view.
@SessionScopedBean lives as long as the HTTP session lives. It get created upon the first HTTP request involving this bean in the session and get destroyed when the HTTP session is invalidated.
@ApplicationScopedBean lives as long as the web application lives. It get created upon the first HTTP request involving this bean in the application (or when the web application starts up and the eager=true attribute is set in @ManagedBean) and get destroyed when the web application shuts down.
@CustomScopedBean lives as long as the bean's entry in the custom Map which is created for this scope lives.
@ManagedBean(name = "helloWorld", eager = true) - eager =true - не ленивая загрузка. Управляющией бин загружается еще до первого вызова.
@RequestScoped
public class HelloWorld {

   @ManagedProperty(value="#{message}")  // внедрение друго менеджд бина. (по принцыge как аннотация @EJB)
   private Message messageBean;
@ManagedBean(name = "navigationController", eager = true)
@RequestScoped
public class NavigationController implements Serializable {

   //this managed property will read value from request parameter pageId
   @ManagedProperty(value="#{param.pageId}")
   private String pageId;

   //condional navigation based on pageId
   //if pageId is 1 show page1.xhtml,
   //if pageId is 2 show page2.xhtml
   //else show home.xhtml
   public String showPage(){
      if(pageId == null){
         return "home";
      }
      if(pageId.equals("1")){
         return "page1";
      }else if(pageId.equals("2")){
         return "page2";
      }else{
         return "home";
      }
   }
}
<h:form>
   <h:commandLink action="#{navigationController.showPage}" value="Page1">
      <f:param name="pageId" value="1" />
   </h:commandLink>
   <h:commandLink action="#{navigationController.showPage}" value="Page2">
      <f:param name="pageId" value="2" />
   </h:commandLink>
   <h:commandLink action="#{navigationController.showPage}" value="Home">
      <f:param name="pageId" value="3" />
   </h:commandLink>
</h:form>
Look at following code in a managed bean.
public String processPage1(){
   return "page";
}
public String processPage2(){
   return "page";
}
To resolve views, define following navigation rule in faces-config.xml
<navigation-rule>
   <from-view-id>home.xhtml</from-view-id>
   <navigation-case>
      <from-action>#{navigationController.processPage1}</from-action>
      <from-outcome>page</from-outcome>
      <to-view-id>page1.jsf</to-view-id>
   </navigation-case>
   <navigation-case>
      <from-action>#{navigationController.processPage2}</from-action>
      <from-outcome>page</from-outcome>
      <to-view-id>page2.jsf</to-view-id>
   </navigation-case>
</navigation-rule>
<h:form>
   <h3>Forward</h3>
   <h:commandButton action="page1" value="Page1" />   url в браузер не изменяется.
   <h3>Redirect</h3>
   <h:commandButton action="page1?faces-redirect=true" value="Page1" /> url меняется
</h:form>
<html 
   xmlns="http://www.w3.org/1999/xhtml" 
   xmlns:h="http://java.sun.com/jsf/html" 
> подключение тего JSF в XHTML файле.

Комментариев нет:

Отправить комментарий