JSF 2 Notes with coding examples topics include introduction , managed bean, jsf tags, navigation, jsf life cycle and phase listners,jsf validation and converters, i18n
AngularJS Introduction (Talk given on Aug 5 2013)Abhishek Anand
This document provides an introduction and overview of AngularJS, including:
- The main components of Angular apps like modules, models, controllers, templates, directives, services, filters and routes.
- How Angular handles data binding, dependency injection and promises.
- Testing Angular apps with tools like Karma, Jasmine and Batarang.
- Best practices for Angular development and organizing code.
Angular is a development platform for building mobile and desktop web applications using TypeScript/JavaScript. It is an update to AngularJS with a focus on mobile and typesafety. Major versions include Angular 1.x, 2.x, 4.x and 5.x. Angular uses components, services and modules to build applications with templates and styles. It is compiled to JavaScript using transpilation and supports AOT and JIT compilation. Common tools used with Angular include the Angular CLI, Webpack and Zone.js.
This is a presentation on Angular 5 getting started. Angular is the one framework for mobile, desktop and web applications. Checkout the demo application:
https://stackblitz.com/edit/http-service-demo
This document provides an overview of Angular, including:
- Angular is a JavaScript framework used to build client-side applications with HTML. Code is written in TypeScript which compiles to JavaScript.
- Angular enhances HTML with directives, data binding, and dependency injection. It follows an MVC architecture internally.
- Components are the basic building blocks of Angular applications. Modules contain components and services. Services contain reusable business logic.
- The document discusses Angular concepts like modules, components, data binding, services, routing and forms. It provides examples of creating a sample login/welcome application in Angular.
This document provides an introduction to Angular, including its history and architecture. Angular is a TypeScript-based front-end framework for building client-side dynamic web applications. It discusses when to use Angular, such as for large complex projects or apps with dynamic content. The document also covers Angular's modules, components, data binding, directives, services and dependency injection.
Dependency Injection pattern in AngularAlexe Bogdan
The document discusses dependency injection (DI) in Angular and how it is used to configure services. It provides examples of different service types - constant, value, factory, service, and provider - and how they are registered and injected. The ngRoute module is also summarized as the core routing module in Angular that uses directives to render templates based on routes.
An Open-Source JavaScript Framework
It’s used to build Single Page based Web Application (SPA)
Developed by Google,
Release date March 2017,
Current version 4.4.6 (stable).
This document provides an overview of the Struts framework and its key components. It covers the model-view-controller design pattern used in Struts, the model components including JavaBeans and ActionForm beans, view components like JSP tags and internationalization, controller components like Action classes and the configuration file, and finally the tag libraries used in Struts. The document is part of a training course on Struts and introduces each major concept across 9 units.
Angular Routing Tutorial | AngularJS vs Angular Router | Angular Training | E...Edureka!
This Edureka "Angular Routing" tutorial will help you to understand how Angular Router evolved over a period of time and will help you in understanding how to work with Angular Routers. Below are the topics covered in this tutorial:
1) Why Routers
2) What is Router?
3) AngularJS Routers
4) Angular Router
5) Diff b/w AngularJS and Angular Routers
6) Demo Project using Angular Router
Subscribe to our channel to get more updates.
Check our complete Angular playlist here: https://goo.gl/15McX5
The document discusses enhancing JSF 2.0 components. It explores the JSF 2.0 component model and how Facelets is optimized for component development. It describes how to create composite components and enhance them with JSF 2.0 features like Ajax and behaviors. The demo shows how to add interactivity to components using these new JSF 2.0 capabilities.
The document provides an overview of AngularJS and how to build single page applications with it. It discusses key AngularJS concepts like directives, filters, data binding and MVC architecture. It also presents steps to create a basic AngularJS application and build a responsive user management application as a project example. The document promotes an AngularJS course by Edureka that teaches these concepts over 21 hours of live online classes along with assignments and a project.
This document provides a summary of the major new features in JavaServer Faces (JSF) 2.0, including Facelets as the preferred view declaration language, composite components, Ajax support, partial state saving, view parameters, system events, resources, behaviors, view traversal, annotations, navigation, exceptions, validation, EL improvements, and new scopes. It highlights contributions from the JSF expert group and community and provides resources for learning more about JSF 2.0.
The document discusses adding user management functionality to a Node.js application called QAVideos. It involves the following steps:
1. Creating the application using StrongLoop's Loopback framework.
2. Adding Angular support to handle data binding between the client and server.
3. Adding signup and login functionality including signup and success pages, a signup controller, and an authentication service to register new users.
Angular Kickstart document provides an overview of Angular including:
- Angular is a client side JavaScript framework that allows building of single page applications.
- A single page application loads initial content via the first page load and subsequent content without reloading the page.
- The document discusses Angular features such as modularity, performance, TypeScript support, and building blocks like modules, components and directives. It also provides instructions on setting up the development environment for Angular applications.
1> IMPORTANT PARTS OF ANGULARJS
2> Angular Js FEATURES
3> ADVANTAGES / DISADVANTAGES OF ANGULARJS
4> THE ANGULARJS COMPONENTS
5> MVC
6> STEPS TO CREATE ANGULARJS APP
AngularJS, a MVW framework from Google is based on JavaScript, a language globally known to millions of developers worldwide - thus giving it a much lower learning curve even for complete beginners. Integrating AngularJS is simple as it evaluates page once HTML is in the DOM and make easier to bind Angular on top of existing applications. It can run along with Node.js, an asynchronous development platform with lightning speed execution, which makes building Mean Stack applications easier and faster. AngularJS comes with a very good documentation and also have wide range of third party modules making it user-friendly for developers.
Maximilian Berghoff presented an overview of Angular and AngularJS. He discussed the differences between the two frameworks and how Angular focuses more on components while removing two-way data binding. He then demonstrated how to build an app in Angular including bootstrapping, templating, dependency injection, events, and forms. Finally, he proposed an app for managing code conference talks and accepting talk proposals.
JSF 2 life cycle consists of 6 phases: restore view, apply request values, process validations, update model values, invoke application, and render response. Managed beans are JavaBeans that can be accessed from JSF pages and are used to store data. Facelets is the templating language used by JSF 2 that replaced JSP. Navigation between pages can be done through configuration, implicit navigation based on action outcomes, or redirection. New features in JSF 2.2 include faces flows for page flows, HTML5 support, and a file upload component.
Firebase. Предмет и область применения — Тимур АхметгареевPeri Innovations
Firebase provides tools to improve mobile app development and user experience. It offers analytics, notifications, remote config and other services to help developers better understand users, roll out changes, and run A/B tests. While the documentation and capabilities continue expanding, some limitations include historical audience data and lack of audience comparison tools. Overall, Firebase is a full-featured platform that simplifies the development process and allows extensive analysis of user behavior.
This document discusses Angular Material, an UI component library for building attractive and consistent Angular applications. It provides modern components that work across devices and are optimized for Angular. To use Angular Material, install it via the Angular CLI and add Material components to templates. It includes features like typography, themes, and schematics to generate common components.
Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIsAkhil Mittal
We have already learnt a lot on WebAPI. I have already explained how to create WebAPI, connect it with database using Entity Framework, resolving dependencies using Unity Container as well as using MEF. In all our sample applications we were using default route that MVC provides us for CRUD operations. In this article I’ll explain how to write your own custom routes using Attribute Routing. We’ll deal with Action level routing as well as Controller level routing. I’ll explain this in detail with the help of a sample application. My new readers can use any Web API sample they have, else you can also use the sample applications we developed in my previous articles.
Angular JS - Develop Responsive Single Page ApplicationEdureka!
AngularJS, a MVW framework from Google is based on JavaScript, a language globally known to millions of developers worldwide - thus giving it a much lower learning curve even for complete beginners. Integrating AngularJS is simple as it evaluates page once HTML is in the DOM and make easier to bind Angular on top of existing applications. It can run along with Node.js, an asynchronous development platform with lightning speed execution, which makes building Mean Stack applications easier and faster. AngularJS comes with a very good documentation and also have wide range of third party modules making it user-friendly for developers.
This document provides a user manual for an interactive development environment called Hog that allows for the creation of Apache Pig scripts. It describes Hog's installation, design including simple and complex interfaces, available node functions, output display options, and FAQs. The manual was developed in 2016 by KEYW Corp to guide users in leveraging Hog's various features.
Introduction to React for Frontend DevelopersSergio Nakamura
The document provides an introduction to React for frontend developers. It discusses why React is useful, including its declarative style, automatic updates, use of a virtual DOM, and modular component structure. It then covers React basics like building functional components, what JSX is, and how to use JavaScript code within JSX.
DNS windows server(2008R2) & linux(SLES 11)Tola LENG
In this practice you will be able:
-Configure Primary DNS and Secondary DNS
-Configure DNS zone transter
-DNS Delegation
-DNS Security zone transfer
-Configure also Linux(Sles 11) and Windows Server 2008R2
Configure Webserver & SSL secure & redirect in SuSE Linux EnterpriseTola LENG
In this chapter you will be able:
-How to install webserver in suse linux server
-How to configure webserver
-How to hosting website and web application
-How to configure secure connection (SSL, Redirect)
This document provides an overview of the Struts framework and its key components. It covers the model-view-controller design pattern used in Struts, the model components including JavaBeans and ActionForm beans, view components like JSP tags and internationalization, controller components like Action classes and the configuration file, and finally the tag libraries used in Struts. The document is part of a training course on Struts and introduces each major concept across 9 units.
Angular Routing Tutorial | AngularJS vs Angular Router | Angular Training | E...Edureka!
This Edureka "Angular Routing" tutorial will help you to understand how Angular Router evolved over a period of time and will help you in understanding how to work with Angular Routers. Below are the topics covered in this tutorial:
1) Why Routers
2) What is Router?
3) AngularJS Routers
4) Angular Router
5) Diff b/w AngularJS and Angular Routers
6) Demo Project using Angular Router
Subscribe to our channel to get more updates.
Check our complete Angular playlist here: https://goo.gl/15McX5
The document discusses enhancing JSF 2.0 components. It explores the JSF 2.0 component model and how Facelets is optimized for component development. It describes how to create composite components and enhance them with JSF 2.0 features like Ajax and behaviors. The demo shows how to add interactivity to components using these new JSF 2.0 capabilities.
The document provides an overview of AngularJS and how to build single page applications with it. It discusses key AngularJS concepts like directives, filters, data binding and MVC architecture. It also presents steps to create a basic AngularJS application and build a responsive user management application as a project example. The document promotes an AngularJS course by Edureka that teaches these concepts over 21 hours of live online classes along with assignments and a project.
This document provides a summary of the major new features in JavaServer Faces (JSF) 2.0, including Facelets as the preferred view declaration language, composite components, Ajax support, partial state saving, view parameters, system events, resources, behaviors, view traversal, annotations, navigation, exceptions, validation, EL improvements, and new scopes. It highlights contributions from the JSF expert group and community and provides resources for learning more about JSF 2.0.
The document discusses adding user management functionality to a Node.js application called QAVideos. It involves the following steps:
1. Creating the application using StrongLoop's Loopback framework.
2. Adding Angular support to handle data binding between the client and server.
3. Adding signup and login functionality including signup and success pages, a signup controller, and an authentication service to register new users.
Angular Kickstart document provides an overview of Angular including:
- Angular is a client side JavaScript framework that allows building of single page applications.
- A single page application loads initial content via the first page load and subsequent content without reloading the page.
- The document discusses Angular features such as modularity, performance, TypeScript support, and building blocks like modules, components and directives. It also provides instructions on setting up the development environment for Angular applications.
1> IMPORTANT PARTS OF ANGULARJS
2> Angular Js FEATURES
3> ADVANTAGES / DISADVANTAGES OF ANGULARJS
4> THE ANGULARJS COMPONENTS
5> MVC
6> STEPS TO CREATE ANGULARJS APP
AngularJS, a MVW framework from Google is based on JavaScript, a language globally known to millions of developers worldwide - thus giving it a much lower learning curve even for complete beginners. Integrating AngularJS is simple as it evaluates page once HTML is in the DOM and make easier to bind Angular on top of existing applications. It can run along with Node.js, an asynchronous development platform with lightning speed execution, which makes building Mean Stack applications easier and faster. AngularJS comes with a very good documentation and also have wide range of third party modules making it user-friendly for developers.
Maximilian Berghoff presented an overview of Angular and AngularJS. He discussed the differences between the two frameworks and how Angular focuses more on components while removing two-way data binding. He then demonstrated how to build an app in Angular including bootstrapping, templating, dependency injection, events, and forms. Finally, he proposed an app for managing code conference talks and accepting talk proposals.
JSF 2 life cycle consists of 6 phases: restore view, apply request values, process validations, update model values, invoke application, and render response. Managed beans are JavaBeans that can be accessed from JSF pages and are used to store data. Facelets is the templating language used by JSF 2 that replaced JSP. Navigation between pages can be done through configuration, implicit navigation based on action outcomes, or redirection. New features in JSF 2.2 include faces flows for page flows, HTML5 support, and a file upload component.
Firebase. Предмет и область применения — Тимур АхметгареевPeri Innovations
Firebase provides tools to improve mobile app development and user experience. It offers analytics, notifications, remote config and other services to help developers better understand users, roll out changes, and run A/B tests. While the documentation and capabilities continue expanding, some limitations include historical audience data and lack of audience comparison tools. Overall, Firebase is a full-featured platform that simplifies the development process and allows extensive analysis of user behavior.
This document discusses Angular Material, an UI component library for building attractive and consistent Angular applications. It provides modern components that work across devices and are optimized for Angular. To use Angular Material, install it via the Angular CLI and add Material components to templates. It includes features like typography, themes, and schematics to generate common components.
Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIsAkhil Mittal
We have already learnt a lot on WebAPI. I have already explained how to create WebAPI, connect it with database using Entity Framework, resolving dependencies using Unity Container as well as using MEF. In all our sample applications we were using default route that MVC provides us for CRUD operations. In this article I’ll explain how to write your own custom routes using Attribute Routing. We’ll deal with Action level routing as well as Controller level routing. I’ll explain this in detail with the help of a sample application. My new readers can use any Web API sample they have, else you can also use the sample applications we developed in my previous articles.
Angular JS - Develop Responsive Single Page ApplicationEdureka!
AngularJS, a MVW framework from Google is based on JavaScript, a language globally known to millions of developers worldwide - thus giving it a much lower learning curve even for complete beginners. Integrating AngularJS is simple as it evaluates page once HTML is in the DOM and make easier to bind Angular on top of existing applications. It can run along with Node.js, an asynchronous development platform with lightning speed execution, which makes building Mean Stack applications easier and faster. AngularJS comes with a very good documentation and also have wide range of third party modules making it user-friendly for developers.
This document provides a user manual for an interactive development environment called Hog that allows for the creation of Apache Pig scripts. It describes Hog's installation, design including simple and complex interfaces, available node functions, output display options, and FAQs. The manual was developed in 2016 by KEYW Corp to guide users in leveraging Hog's various features.
Introduction to React for Frontend DevelopersSergio Nakamura
The document provides an introduction to React for frontend developers. It discusses why React is useful, including its declarative style, automatic updates, use of a virtual DOM, and modular component structure. It then covers React basics like building functional components, what JSX is, and how to use JavaScript code within JSX.
DNS windows server(2008R2) & linux(SLES 11)Tola LENG
In this practice you will be able:
-Configure Primary DNS and Secondary DNS
-Configure DNS zone transter
-DNS Delegation
-DNS Security zone transfer
-Configure also Linux(Sles 11) and Windows Server 2008R2
Configure Webserver & SSL secure & redirect in SuSE Linux EnterpriseTola LENG
In this chapter you will be able:
-How to install webserver in suse linux server
-How to configure webserver
-How to hosting website and web application
-How to configure secure connection (SSL, Redirect)
Day 1 of the training covers introductory C++ concepts like object-oriented programming, compilers, IDEs, classes, objects, and procedural programming concepts. Day 2 covers more advanced class concepts like constructors, destructors, static members, returning objects, and arrays of objects. Day 3 covers function and operator overloading.
1. The document provides instructions for configuring iptables firewall rules on a SUSE Linux server to set up a network with internal servers and clients.
2. It outlines steps to allow specific services and access between servers and clients like SSH, DNS, file sharing, remote desktop, and internet access.
3. The configuration includes setting up masquerading and destination NAT rules to enable connectivity and allow internal clients to access the internet through the firewall server.
Configure active directory & trust domainTola LENG
The document outlines steps for configuring an Active Directory environment, including:
1. Creating OUs and user accounts
2. Adding users to security groups
3. Joining a Windows client to the domain
4. Setting user profile and login restrictions
5. Configuring a trust between two domains with either a two-way or one-way trust relationship
The prepared by line indicates the tasks were completed by LENG Tola from the SNA15-B class.
The document provides step-by-step instructions for installing Linux SUSE (Sless11) using VMware Workstation. It describes: 1) Creating a new virtual machine and selecting Linux as the guest operating system; 2) Configuring storage, RAM, and other settings; 3) Mounting the Linux SUSE ISO image and booting the installation; 4) Completing the installation process by partitioning disks, setting up users and passwords, and configuring networking. Upon finishing, the virtual machine will be booted with the newly installed Linux SUSE operating system.
The spatial theory of electoral competition assumes that voter choices are based on the distance between their own political positions and those of candidates in a political space. It models this using Euclidean distance, with voters preferring candidates whose positions are closest to their own. This clustering of ideological positions means candidates' strategies are highly constrained. Surveys in Turkey in 2001 and 2004 showed support for the pro-European, centrist Justice and Development Party, while other parties took more polarized stances on issues like the EU and Kurdish rights.
This document describes the network topology and IP addressing scheme for a company network. The network consists of multiple VLANs for different departments connected by switches and routers. It provides details of the subnet IDs, IP ranges, and subnet masks configured for each VLAN and network segment.
Configure proxy firewall on SuSE Linux Enterprise Server 11Tola LENG
In this practice you will be able:
-How to install and configure the iptables and proxy firewall when we want to block the packet.
-How to allow or deny the services or packet when the client access to the Internet.
The document outlines the steps to install and configure Nagios network monitoring software on a system. It details installing necessary services like Nagios, Apache2, and PHP. It also covers creating a Nagios username and password. The bulk of the document describes configuring Nagios to monitor specific hosts like a switch, servers, and an XP machine by editing host configuration files and setting parent hosts. Finally, it mentions inserting host pictures into the Nagios interface and viewing the status map.
Logging is essential for debugging applications and monitoring what is happening. The document discusses different logging frameworks like Log4j, Logback, and SLF4J. SLF4J acts as a facade and allows plugging in different logging frameworks. Log4j is commonly used and configuration involves setting log levels and output destinations. Examples demonstrate basic usage of Log4j for logging information and errors.
The document provides guidelines for how to become a good presenter. It outlines the key steps and phrases to use when structuring a presentation, including how to welcome the audience, introduce yourself and the presentation, explain the structure, conclude and summarize sections, thank the audience, and invite and answer questions. The overall goal is to clearly guide the audience through the presentation from beginning to end using consistent language.
The document provides an overview of Struts 2 including:
1. The architecture of Struts 2 which uses patterns like front controller and composite.
2. A basic "Hello World" example demonstrating creating an action class and mapping it in struts.xml.
3. The Action interface and ActionSupport class which provides common functionality like validation. ActionSupport implements interfaces like Validateable.
4. Aware interfaces like SessionAware which allow injecting objects like the session into actions.
Ansible is an open source automation tool that allows users to configure, manage, and deploy software on remote machines without requiring an agent. It uses SSH to connect to nodes and executes modules written in Python. Playbooks allow users to automate multiple tasks by defining YAML files containing a list of commands. Ansible is agentless and can manage hundreds of nodes with a single command.
Basic Security
@ Updates
-Update manager
-Enable automatic security updates(Update Setting)
=> Super windows => type the key word (System Setting) =>
@ Firewall
-In Ubuntu all ports are block by default
-Default firewall-ufw (turned off by default)
+sudo ufw status
+sudo ufw enable/disable
-Firestarter for graphical interface (recommanded)
+sudo apt-get install firestarter
+Preferences
@ User Accounts
-User & Groups
+Disable user guest
-Do not use root user (Disable by default)
+sudo passwd
+sudo passwd -l root (disable/changed expiry password)
-Use sudo instead of root (/etc/sudoers)
+sudo visudo OR sudo gedit /etc/sudoers(To set the privilege user authorized)
+sudo adduser tolaleng sudo
-Deleting Users
+sudo deluser canamall
-Removing world readable permission to home directory
+sudo chmod 0750 /home/username
-Locking/Unlocking user
+sudo passwd -l username (enable user expiry)
+sudo passwd -u username (disable user expiry)
-passwords
+sudo chage canamall (Set the password expiration)
+sudo chage-l canamall (show the password expiration)
@ Antivirus
-Clam TK (Under Accessories), other anti-virus
@ Unistall Applications
-Ubuntu Software Center-> Installed software section-> Select application and click remove
@ Processes
-To see processes
+ps aux or top
+system monitor(cacti, nagios,)
-
@ Logs
-Some of logs
+ /var/log/messages : general log messages
+ /var/log/boot : system boot log
+ /var/log/debug/ : debugging log messages
+ /var/log/auth.log : user login and authentication logs
+ /var/log/daemon.log : running services such as squid,ntpd and other log message to this file
+ /var/log/kern.log : kernel log file
-Viewing logs
+ tail, more, cat, less, grep
+ GNOME system log viewer
@Firewall
ufw
=> Security Host
* Create Standard User and enable user passwd (complexity password, strong passwd, passwd expired, invalid day of passwd, Lock and Unlock user, disable user Guest, )
* Secure remote network and host
-Telnet(Secure with the host and address connection)
-SSH (Secure with the authentication encryption key)
=> Security Backup (Data Hosting)
*Make a Full Backup of Your Machine
-Aptik (backup application)
-rsync (Remote synce)
-Gsync (Remote)
-Amanda
-Rsnapshot
JSP provides a scripting environment for Java code to generate dynamic web page content. Key elements include directives like <jsp:include> and <jsp:forward> for page composition, scriptlets for Java code, and expressions for output. The Expression Language (EL) offers a simpler way than scriptlets to access data and call methods. JSPs are compiled into servlets, so they can use Java classes and web technologies like MVC.
File Share Server, FTP server on Linux SuSE and WindowsTola LENG
-Install and configure Services
-Configure Suse Linux for FTP File Share Server
-Configure Permission
- Configure Point IP address to specific users.
- FTP Acccess
How to configure IPA-Server & Client-Centos 7Tola LENG
The document provides steps for configuring an IPA-Server on Centos 7, which includes assigning an IP address, downloading and installing IPA server services, and configuring the freeIPA server and client. It notes that the IP address must be assigned manually along with the DNS, gateway, and subnet mask.
-Configure DHCP (Create LAN Server and LAN Client) on Windows Server 2008R2
-Configure Relay on SuSE Linux Enterprise Server 11
-Allow Client Use DHCP IP for each LAN
The document outlines exercises for learning Servlets, JSPs, and Java web development fundamentals including:
1. Hello World applications using Servlets and JSPs
2. Form processing and request handling with Servlets
3. Customer registration and voting applications
4. Connection pooling with JDBC for a book database
5. Session management using cookies and URL rewriting
6. The MVC pattern for building web applications
7. Using filters for basic security
8. Avoiding scriptlets and using expression language (EL) and JSTL tags
9. A book shopping cart application demonstrating various concepts
10. A case study on building an employee or book management system with MVC,
JSF 2.0 tutorials provide an overview of topics covered including JSF 2.0 introduction, managed beans and scoping, JSF tags, navigation, lifecycle and listeners, validators, converters, and internationalization. The document discusses key aspects of JSF including it being a Java EE standard web application framework, implementing the MVC pattern, providing reusable UI components, and extensibility. It also provides an example "hello world" JSF application and demonstrates managed bean scoping with different beans.
This document provides an overview of key Spring concepts including dependency injection, inversion of control, annotation-based configuration, bean lifecycle, profiles, AOP, and testing. It describes how Spring offers a simpler approach to enterprise Java development using POJOs and how different features like profiles, conditional beans, and expressions work.
Java Server Faces (JSF) is a Java web application framework that uses the model-view-controller (MVC) architectural pattern. JSF has a component-based user interface that separates UI components from business logic. It provides features like data binding, validation, internationalization and AJAX. JSF applications typically consist of JavaBeans components, JSP pages that represent views, and configuration files that define workflows between pages.
This document provides an overview of JavaServer Faces (JSF), including:
- An introduction to JSF and what it is
- A description of the JSF request lifecycle and faces servlet
- An explanation of JSF component models and commonly used tags
- A step-by-step guide for creating a basic "Hello World" JSF application
- Details about JSP architectures (Model 1 and Model 2) that provide context for JSF
The document discusses Spring, a popular Java application framework. It provides definitions and explanations of key Spring concepts like frameworks, dependency injection, and the Spring application context. It describes the modular architecture of Spring, including core modules for aspects like data access, web, and AOP. It also compares Spring to Hibernate, explaining that Spring is a framework that helps follow MVC architecture while Hibernate provides object-relational mapping.
1. The document provides an overview of the major Java 2 Enterprise Edition (J2EE) technologies including Java servlets, JavaServer Pages (JSP), Enterprise JavaBeans (EJB), Java Message Service (JMS), Java Database Connectivity (JDBC), and Java Naming and Directory Interface (JNDI).
2. It describes the basic anatomy and functionality of servlets, JSP, EJB components including session and entity beans, and JMS.
3. Examples of simple servlet, JSP, EJB, and JMS code are included to illustrate how each technology can be implemented.
The document provides an overview of J2EE (Java 2 Enterprise Edition) technologies including servlets, JSP, EJB, and how they are used to build web applications. It describes the major components of J2EE like servlets, JSP, EJB, their anatomy and usage. Sample code is also included to demonstrate servlets and JSP.
- JSF is a Java specification for building component-based web interfaces using the MVC pattern. It aims to make web development feel more like building desktop GUIs.
- Popular implementations include Apache MyFaces and JBoss Seam. MyFaces provides the core JSF functionality while Seam integrates additional features like EJB3 and object persistence.
- The presentation demonstrated building a simple registration form application using JSF with MyFaces and Seam to showcase their features and how they simplify web development.
JBoss Application Server 7 includes several key features:
1. It is a lightweight Java EE 6 compliant container that provides fast startup times of less than 3 seconds.
2. It simplifies classloading and configuration for easier management and deployment.
3. It supports the use of managed beans, dependency injection and common services as specified by the CDI specification.
The document provides an introduction to the Struts framework. It describes Struts as an open source MVC framework that implements the JSP Model 2 architecture. It stores routing information in a configuration file and separates the model, view, and controller layers. All requests are routed through the Struts controller which uses the configuration file to map requests to actions, which then call services and forward to view resources.
The document provides instructions for setting up an environment to develop and deploy EJB applications using NetBeans IDE. It includes steps to install Java, NetBeans, JBoss application server, and a database. It also explains how to create an EJB project in NetBeans with a sample session bean, build and deploy the project on JBoss. The sample bean allows adding and retrieving books from a list.
This document provides instructions for setting up a development environment for Java Server Faces (JSF). It outlines requirements like having JDK 1.5 or higher installed and recommends verifying the Java installation. It then provides steps to setup the JDK if needed, set the JAVA_HOME environment variable, and append the Java compiler location to the system path.
This document contains 100 Java and Java EE interview questions related to topics like Java servlets, JSP, Spring, Hibernate, JDBC, JSF, Struts, EJB and more. Some key questions covered include what are considered web components in Java, what is Hibernate and ORM, differences between proxy and adapter patterns, types of dependency injection supported by Spring, and advantages of Spring framework.
Some of the common interview questions asked during a Java Interview. These may apply to Java Interviews. Be prepared with answers for the interview questions below when you prepare for an interview. Also have an example to explain how you worked on various interview questions asked below. Java Developers are expected to have references and be able to explain from their past experiences. All the Best for a successful career as a Java Developer!
Alessio Soldano is a principal software engineer at JBoss/Red Hat who has been a committer to the JBoss WS project since 2007. He leads the JBoss Web Services team. JBoss WS provides integration of the Apache CXF web services framework with the JBoss Application Server. This integration allows CXF's features and compliance with web services specifications to be used within the JBoss AS container. Alessio demonstrated how to deploy basic web service endpoints and use WS-Security with the JBoss AS 7.1 container.
Contextual Dependency Injection for Apachecon 2010Rohit Kelapure
The document discusses the history and evolution of Java EE and its specifications such as EJB and JSF. It introduces key concepts in Java EE 6 including Contexts and Dependency Injection (CDI), which provides a standard way to inject dependencies into Java objects without hardcoding them. CDI allows for loose coupling through contextual lifecycles and scopes, interceptors, and producers that control bean instantiation.
This document provides an overview of JavaServer Faces (JSF), a Java framework for building user interfaces for web applications. It discusses that JSF is a standard created by Java Community Process to make client-side development browser-independent and include features like state management. It also describes key characteristics of JSF like being server-side, using a component framework, and supporting features like validation and error handling. The document outlines the JSF application lifecycle process and how JSF uses managed backing beans to hold user-entered data. It provides examples of converting a JSP to a JSF page and the JSF navigation model.
This document provides an overview of JavaServer Faces (JSF), a Java framework for building user interfaces for web applications. It discusses that JSF is a standard Java framework created as a Java Community Process to make client-side development browser-independent and include features like state management. It also summarizes that JSF uses a model-view-controller approach with UI components on the server-side, has a defined programming model and tag libraries, and helps with reusability and easier event handling and separation of behavior and presentation. Finally, it provides examples of converting a JSP to a JSF page and using managed beans and navigation in JSF applications.
This document discusses integrating JavaServer Faces (JSF), Enterprise Java Beans (EJB), and the Java Persistence API (JPA) in a Java EE application. It provides a brief overview of each technology and how they can be used together, with JSF for the presentation tier, EJBs for the business tier hosted in the EJB container, and JPA entities for the persistence tier. The document focuses on using annotations to enable dependency injection between the tiers, allowing JSF managed beans to access EJB session beans and JPA entities.
Spring5 hibernate5 security5 lab step by stepRajiv Gupta
This document provides an overview of Spring 5, Hibernate 5, and Spring Security 5. It outlines 10 steps for implementing Spring and Hibernate, including setting up the data access object (DAO) layer, service layer, Hibernate configuration, testing, and integrating Spring MVC. It also details 11 steps for implementing Spring Security, such as role-based access control, authentication, custom login and logout pages, and restricting access based on user roles. The document serves as a tutorial for integrating Spring, Hibernate, and Spring Security in a Java web application.
This document discusses various object-oriented design patterns including creational, structural, and behavioral patterns. It provides examples of common design patterns like singleton, factory, abstract factory, builder, prototype, adapter, decorator, proxy, facade, iterator, strategy, chain of responsibility, observer, and template patterns. It also discusses pillars of object-oriented programming like abstraction, encapsulation, modularity, and hierarchy.
The document provides information on JavaScript fundamentals including:
- JavaScript is an object-oriented scripting language used to make web pages interactive. It was originally called LiveScript and developed by Netscape.
- JavaScript can be used for both client-side scripting in web browsers and server-side scripting using Node.js. It is an interpreted language that is loosely typed, prototype-based, and supports operators, control structures, and functions.
- Common uses of JavaScript include form validation, dynamic updating of content, and basic interactivity on web pages. It works with HTML and CSS to create dynamic web pages.
Flush() synchronizes the database with pending changes in the persistence context. Close() ends the session and detaches all objects. Clear() detaches all objects but keeps the session open, allowing further work before needing to
Weblogic 11g admin basic with screencastRajiv Gupta
Installation of weblogic 11g
Creation and configuration of Admin server with three managed server
Creation of And Configuring Machines in Weblogic Server
Administering Managed Server With Node Manager
Struts 2 complete ppt including most of the topics such as architecure of Struts2, Action Interface, ActionSupport , Aware Interfaces, Namespace,Multiple mapping files, Dynamic Method Invocation , OGNL, valueStack, Control tags, UI tags, Interceptors, validation framework, Struts2 Type Conversion,Internationalization (i18n) support
Here is an example of inheritance in Java:
```java
class Employee {
String name;
int id;
public Employee(String name, int id) {
this.name = name;
this.id = id;
}
}
class Programmer extends Employee {
String language;
public Programmer(String name, int id, String language) {
super(name, id);
this.language = language;
}
}
```
Here Employee is the base/super class and Programmer is the derived/sub class that inherits from Employee. Programmer extends Employee and uses super() to pass values to the Employee constructor.
This document provides an overview of servlets and related Java web application concepts. It discusses the servlet lifecycle, how servlets handle HTTP requests and responses, and how they fit into the Java EE context. It also covers servlet containers, the model-view-controller pattern, using servlet contexts and configurations, session management, filters, and multithreading issues.
The document discusses various aspects of dependency injection (DI) in Spring, including:
- Using constructor and setter injection to inject dependencies into beans
- Declaring inner beans and aliases
- Initializing collections in beans
- Understanding different bean scopes like singleton and prototype
- Autowiring bean dependencies
- Making beans aware of their names and the application context
- Inheriting properties from parent bean definitions
- Lifecycle callbacks for initializing and destroying beans
- Method injection and lookup method injection
The document provides examples and explanations of these different DI features in Spring. It describes how Spring manages object dependencies and allows the container to inject collaborating objects.
The document provides an overview of the Spring framework. It discusses that Spring simplifies enterprise Java development through dependency injection, aspect-oriented programming, and reducing boilerplate code. It describes the main Spring modules including the core container, AOP, DAO, and web modules. The core container manages the beans in a Spring application, creating, configuring, and wiring them together. The document contrasts BeanFactory and ApplicationContext, noting ApplicationContext provides additional features like internationalization support and publishing events.
To avoid name clashing, we can access classes using their fully qualified names like:
pack1.Student student1;
pack2.Student student2;
53 Rajeev Gupta
Session-2
Inheritance
Type of inheritance
Diamond problem
InstanceOf operator
Final, Abstract classes and interface
Acess control: public, private,protected and default
Packages
Abstract class
Interface
54 Rajeev Gupta
Inheritance
How to manage Multiple Warehouses for multiple floors in odoo point of saleCeline George
The need for multiple warehouses and effective inventory management is crucial for companies aiming to optimize their operations, enhance customer satisfaction, and maintain a competitive edge.
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingCeline George
The Accounting module in Odoo 17 is a complete tool designed to manage all financial aspects of a business. Odoo offers a comprehensive set of tools for generating financial and tax reports, which are crucial for managing a company's finances and ensuring compliance with tax regulations.
Unit 5: Dividend Decisions and its theoriesbharath321164
decisions: meaning, factors influencing dividends, forms of dividends, dividend theories: relevance theory (Walter model, Gordon model), irrelevance theory (MM Hypothesis)
The *nervous system of insects* is a complex network of nerve cells (neurons) and supporting cells that process and transmit information. Here's an overview:
Structure
1. *Brain*: The insect brain is a complex structure that processes sensory information, controls behavior, and integrates information.
2. *Ventral nerve cord*: A chain of ganglia (nerve clusters) that runs along the insect's body, controlling movement and sensory processing.
3. *Peripheral nervous system*: Nerves that connect the central nervous system to sensory organs and muscles.
Functions
1. *Sensory processing*: Insects can detect and respond to various stimuli, such as light, sound, touch, taste, and smell.
2. *Motor control*: The nervous system controls movement, including walking, flying, and feeding.
3. *Behavioral responThe *nervous system of insects* is a complex network of nerve cells (neurons) and supporting cells that process and transmit information. Here's an overview:
Structure
1. *Brain*: The insect brain is a complex structure that processes sensory information, controls behavior, and integrates information.
2. *Ventral nerve cord*: A chain of ganglia (nerve clusters) that runs along the insect's body, controlling movement and sensory processing.
3. *Peripheral nervous system*: Nerves that connect the central nervous system to sensory organs and muscles.
Functions
1. *Sensory processing*: Insects can detect and respond to various stimuli, such as light, sound, touch, taste, and smell.
2. *Motor control*: The nervous system controls movement, including walking, flying, and feeding.
3. *Behavioral responses*: Insects can exhibit complex behaviors, such as mating, foraging, and social interactions.
Characteristics
1. *Decentralized*: Insect nervous systems have some autonomy in different body parts.
2. *Specialized*: Different parts of the nervous system are specialized for specific functions.
3. *Efficient*: Insect nervous systems are highly efficient, allowing for rapid processing and response to stimuli.
The insect nervous system is a remarkable example of evolutionary adaptation, enabling insects to thrive in diverse environments.
The insect nervous system is a remarkable example of evolutionary adaptation, enabling insects to thrive
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...Celine George
Analytic accounts are used to track and manage financial transactions related to specific projects, departments, or business units. They provide detailed insights into costs and revenues at a granular level, independent of the main accounting system. This helps to better understand profitability, performance, and resource allocation, making it easier to make informed financial decisions and strategic planning.
Understanding P–N Junction Semiconductors: A Beginner’s GuideGS Virdi
Dive into the fundamentals of P–N junctions, the heart of every diode and semiconductor device. In this concise presentation, Dr. G.S. Virdi (Former Chief Scientist, CSIR-CEERI Pilani) covers:
What Is a P–N Junction? Learn how P-type and N-type materials join to create a diode.
Depletion Region & Biasing: See how forward and reverse bias shape the voltage–current behavior.
V–I Characteristics: Understand the curve that defines diode operation.
Real-World Uses: Discover common applications in rectifiers, signal clipping, and more.
Ideal for electronics students, hobbyists, and engineers seeking a clear, practical introduction to P–N junction semiconductors.
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schoolsdogden2
Algebra 1 is often described as a “gateway” class, a pivotal moment that can shape the rest of a student’s K–12 education. Early access is key: successfully completing Algebra 1 in middle school allows students to complete advanced math and science coursework in high school, which research shows lead to higher wages and lower rates of unemployment in adulthood.
Learn how The Atlanta Public Schools is using their data to create a more equitable enrollment in middle school Algebra classes.
Odoo Inventory Rules and Routes v17 - Odoo SlidesCeline George
Odoo's inventory management system is highly flexible and powerful, allowing businesses to efficiently manage their stock operations through the use of Rules and Routes.
As of Mid to April Ending, I am building a new Reiki-Yoga Series. No worries, they are free workshops. So far, I have 3 presentations so its a gradual process. If interested visit: https://www.slideshare.net/YogaPrincess
https://ldmchapels.weebly.com
Blessings and Happy Spring. We are hitting Mid Season.
The ever evoilving world of science /7th class science curiosity /samyans aca...Sandeep Swamy
The Ever-Evolving World of
Science
Welcome to Grade 7 Science4not just a textbook with facts, but an invitation to
question, experiment, and explore the beautiful world we live in. From tiny cells
inside a leaf to the movement of celestial bodies, from household materials to
underground water flows, this journey will challenge your thinking and expand
your knowledge.
Notice something special about this book? The page numbers follow the playful
flight of a butterfly and a soaring paper plane! Just as these objects take flight,
learning soars when curiosity leads the way. Simple observations, like paper
planes, have inspired scientific explorations throughout history.
1. JSF 2.0 tutorials
In this lecture series, i will disucss about JSF2, the lecutre series is divided in below topics, you can easily learn JSF
by following tutorial series step by step.
SW tool required:
Java 7.x
Tomcat 7.x
Eclipse Juno
JSF 2.1 reference implemenation : grab jar from javaserverfaces.java.net/download.html
javax.faces-2.1.17.jar
Topics:
1. Introduction to JSF
2. Managed bean and Scoping
3. JSF tags
Input-output tags, Selection tags, Control tags, data-table
4. Nevigation
5. JSF life cycle and Phase Listeners
6. JSF Validators
7. JSF Converters
8. Internationalization
2. 1. Introduction to JSF2.0
What is JSF?
– JavaServer Faces (JSF) is the standard web application
framework for Java Enterprise Edition (Java EE)
Why should I use JSF?
– As a Java standard, it has solid industry support
– Growing in usage worldwide
– Strong support in Java IDEs
As with all JEE specification JSF2.0 specification is addresss by JSR-314 that begin its work in May 2007 and defined
and released JSF 2.0 July 2009
The JSF API is basically a set of Java interfaces
and abstract classes that define a contract which a Reference Implementation (RI) must fulfill
There are two open source JSF RIs available:
– Oracle RI, code-named “Mojarra”
– Apache MyFaces RI
JSF features
MVC
Implements the Model View Controller (MVC) design pattern
RAD
Rapid Application Development for web applications
UI Components
User Interfaces developed with reusable components
Many component suites available, such as ICEfaces
Render-Kits
Components can render themselves
according to multiple client devices
Validation/Conversion
User input and server
Extensibility
Framework is highly extensible via pluggable architecture
navigation-handler, view-handler, phase-listener,
el-resolver, validators, converters
Internationalization
Views can manifest themselves in different languages
3. Templating
Facelets provides a powerful templating mechanism
Composite Components
Easily create custom pieces of markup with Facelets
In Nutshell what is JSF 2.0?
JavaServer Faces (JSF) is a user interface (UI) framework for Java web applications
• UI is constructed from reusable UI components
• Simplifies data transfer to and from the UI
• UI state can be managed between client request
• Provides a simple action model mapping client events to server side application code
• Allows custom UI Components to be easily created and reused
Simplified provide simplified Data Transfer b/w view and model layer
JSF provides a simple value binding mechanism
Simple Java types such as String and int are automatically converted by the framework
There is no need to manually clean and convert values found in the request map
Extension points allow for the conversion of more complex Java objects
Component Tree
The JSF framework manages the hierarchy in a component tree on the server side. Although components are
specified declaratively using XML markup, their run-time representation are Java class instances that are
maintained by the JSF framework in a component tree. The componet tree has short life cycle nearly equal to
duration of request and response.
Enough theory , lets start hello world JSF application
First configure eclipse with tomcat7
Then
Start eclipse…choose dynamic web project
4. Choose configuration JSF v2.1 project….click next…
Now you can see eclipse is shouting for configuration …
Click manage libery …create user library give suitable name
5. Now click add external jar and provide jsf2.1 jar downloaded earlier…only one jar is required…
The say finished
Now create an xhtml page (don’t use jsp for view in JSF2)
6. Now add following to created page , to get server, session etc information on index.xhtml
Server Name: #{request.serverName}<br />
Context Path: #{request.contextPath}<br />
Servlet Path: #{request.servletPath}<br />
Server Port: #{request.serverPort}<br />
Request Method: #{request.method}<br />
Server Info: #{application.serverInfo}<br />
Session ID: #{session.id}<br />
Now index.xhtml looks like this…….
7. Now run it…get the output……
Now lets do an simple application that accept user firstName and lastName and echo it…although application is very
simple but I use it to demonstrate JSF works?
Now first of all create an POJO User as shown…
8. Now copy following in index.xhtml
<h:form id="simpleForm">
Enter Name:
<h:inputText value="#{user.name}" required="true" /><br/>
Enter address:
<h:inputText value="#{user.address}" required="true"/><br/>
<h:commandButton value="Submit" action="welcome" />
</h:form>
When user fills values in this form value is bound to an instance of bean (ie in request scope), when user submit the
form action mentioned is “welcome” what it means?
It means that control goes to welcome.xhtml (aka RequestDispaching in servlet/jsp)
10. 2. Managed bean and Scoping
Although We have already used managed bean in last example but now will dicuss it in detail
specially about scoping.
Managed bean?
JSF allows users to design a complex tree of named POJO Beans
Beans have a predetermined lifespan known as scope
Beans can be defined using:
– Managed Bean Creation facility (faces-config.xml)
– Java EE 5 annotations
Managed Beans also have a lifecycle which depends on their specified scope
Bean Names
JSF 2 introduces the @ManagedBean annotation
Names can be specified with the name attribute
@ManagedBean(name=“someName”)
If a name is not specified the class name is used as the Bean name, mixed case starting with lower case
The eager attribute can be used to insure that a bean is loaded in a non-lazy fashion
o @ManagedBean(name=“someName”, eager=true)
Note: import javax.faces.bean. ManagedBean;
Bean Scopes
JSF 1.x originally defined four scope types:
Application
Lifespan continues as long as the web application is deployed
Session
Lifespan of the HttpSession, destroyed by session timeout or manual invalidation
Unique to each user but share across multiple browser tabs
Request
Lifespan duration of an HTTP request received by the server and response sent to client
No Scope
Bean isn’t placed into scope
JSF 2 introduces three new scopes:
View
Bean lasts the duration of the view
Page navigation or page refreshes cause the Bean to be destroyed and reinitialized
Flash
Short conversation-style scope that exists for a single view transition including reloads
Custom
Allows developers to implement their own custom scope behavior
Note: beans can be configured in in faces-config.xml… but not requied in JSF2
11. Important scopes are :
Application: one per application
Session :one per browser,useful for session mgt
Request : per http request/response cycle
View :Bean lasts the duration of the view
Page navigation or page refreshes cause the Bean to be destroyed and reinitialized
Scopes can also be defined with annotations
– @ApplicationScoped
– @SessionScoped
– @ViewScoped
– @RequestScoped
– @CustomScoped(value="#{someMap}")
– @NoneScoped
Note: make sure to import:
javax.faces.bean.Xscoped;
Now lets demostrate an example that highlight effect of bean scoping and when to use what
Create 4 beans as shown:
@ManagedBean(name="applicationScopeBean")
@ApplicationScoped
public class ApplicationScopeBean {
@Override
public String toString(){
return "ApplicationScopeBean:"+super.toString();
}
}
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
@ManagedBean
@RequestScoped
public class RequestScopeBean {
@Override
public String toString(){
return "RequestScopeBean:"+super.toString();
}
}
12. import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean
@SessionScoped
public class SessionScopeBean {
@Override
public String toString(){
return "SessionScopeBean:"+super.toString();
}
}
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
@ManagedBean(name="viewScopeBean")
@ViewScoped
public class ViewScopeBean {
@Override
public String toString(){
return "ViewScopeBean:"+super.toString();
}
}
As you can see code is very simple, code will provide object stamp.
We will print object stemp for all bean using………
<h:form>
Application Scope :#{applicationScopeBean}<br/>
Sesssion scope :#{sessionScopeBean}<br/>
Request Scope :#{requestScopeBean}<br/>
View Scope :#{viewScopeBean}<br/>
<h:commandButton value="submit"></h:commandButton>
</h:form>
Now run this file on different browse
13. Now run it on same browser but on different tab..what is your observation.
Session stemp remain same.
But request and view stemp changes
Now question is what is the differnce b/w request and view scoped bean?
View bean remain same for an particular view , but request scope is only for one cycle of request/resonse and hence
smallest in scope among four we discussed.
Let us now create an new application jobApplicant
This application is going to be used in following excercies
Job-applicant.xhtml
<h:body>
<h:form>
<h:outputLabel for="firstName" value="First Name: " />
<h:inputText id="firstName" value="#{jobApplicant.firstName}" />
<br />
<h:outputLabel for="lastName" value="Last Name: " />
<h:inputText id="lastName" value="#{jobApplicant.lastName}" />
<br />
14. <h:commandButton value="Submit Applicant" />
</h:form>
<br />
- Server -<br />
First Name: <h:outputText value="#{jobApplicant.firstName}" />
<br />
Last Name: <h:outputText value="#{jobApplicant.lastName}" />
<br />
</h:body>
package com.beans;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
@ManagedBean(name="jobApplicant")
@RequestScoped
public class JobApplicant {
private String firstName;
private String lastName;
public JobApplicant(){}
//getter and setter
}
15. 3. JSF tags
Input-output tags, Selection tags, Control tags, data-table
JSF Input and Output Components
There are 3 parts to a component:
– The Component Class
– The Tag Class
– The Renderer Class
– The default JSF components render html (h: namespace)
– More information on component development will be
covered in later lectures
JSF
JSF input component
JSF contains a handful of basic components that are
equivalent to the HTML 4 elements
– <h:form />
– <h:inputText />
– <h:inputTextarea />
– <h:inputSecret />
– <h:inputHidden />
– <h:outputLabel />
– <h:outputLink />
– <h:outputFormat />
– <h:outputText />
Component Tags
Component tags are placed on JSF pages/views:
<h:outputText />
Tag attributes allow us to customize the appearance and behavior of components:
<h:outputText value=“Hello World” rendered=“true” />
Tags are nested in a parent-child containment format:
16. <h:form>
<h:outputLabel for=“fullName” />
<h:inputText id=“fullName” />
</h:form>
Value Binding
Bean values are assigned to component attributes using JSF EL syntax
• For example the managed bean myBean’s instance variable 'value1' is assigned to the input component
as follows:
<h:inputText value=“#{myBean.value1}”/>
<h:inputText value=“#{myBean.value1}”
rendered=“#{myBean.value2}”/>
Input Value Binding
Input components in JSF require that the bound bean property is mutable :
public void setValue1(Object value1){...}
public Object getValue1(){...};
• If the JSF introspection mechanism can’t find the corresponding setter or getter a run time error will
occur
• All other non “value” attribute bindings can be immutable as the setter method is never called by
the JSF framework
Output Value Binding
Output components in JSF assume that the associated value bindings are immutable but it is not
a requirement
public Object getValue1(){...};
• If the JSF introspection mechanism can’t find the corresponding getter a run time error will occur
• All non “value” component attribute bindings can be immutable as the setter method is never called by the
JSF framework
Form Input Component
The form input component is a required parent tag for all input components
• Any input components in the form tag will be submitted to the server when submit occurs
<h:form />
<h:inputText value=“#{bean.userName}”/>
...
</h:form/>
• Form tags can not be embedded but there can be more then one form per page
17. InputText Component
Input Text is the same as the <input type=“text”/> in html 4 allowing client side users to input text
• The value binding can be of type String, Number and all number primitives. JSF takes care of conversion
• InputText can be quite powerful when combined with converters, validators and ajax tags which will be
explained in more detail later
InputTextArea Component
InputTextArea is the same as the <input type=“textarea”/> in html 4 allowing client side users to input text
• The value binding should be of the type String for the value attribute
InputSecret Component
InputSecret Text is the same as the
<input type=“password”/> in HTML 4 allowing client
to enter hidden or secret text
• The component attribute autocomplete="off“ is handy for suppressing the form auto complete feature of most
modern browsers
InputHidden Component
Similar to the <input type=“hidden”/> in HTML 4
• Allows JSF developers to include hidden form data that will be submitted with the other form elements • Not used as
often in JSF as in standard HTML as
Bean scopes provide more intuitive state saving
OutputLabel Component
Renders the same output as the HTML 4 <label> tag
• Generally used in combination with an input component
• When the id attribute of an input component matches the for attribute of an outputLabel a fieldset tag will
automatically be inserted by the framework
OutputLink Component
Renders the same output as the HTML 4 <a> tag
• Not commonly used in JSF as most developers use framework features that aren’t implicitly supported by
this component
• JSF 2.0 introduces <h:link /> component which allows developers to use HTTP GET submits instead
18. of the standard JSF POST submits
OutputFormat Component
Allows developers to use Java i18n message bundles that have specified input parameters
• This component will be covered in later lectures around message bundles
• A simple example of its usage:
<h:outputFormat value=”Line number {0} !">
<f:param value=”153,44"/>
</h:outputFormat>
OutputText Component
Renders the same output as the HTML 4 <span> tag
• JSF 2.0 EL notation has somewhat reduced the use of the outputText component
#{myBean.value1}
Equivalent to
<h:outputText value=“#{myBean.value1}” />
• However it is still used when JSF conversion is needed
Command Components
The h:commandButton and h:commandLink components Implement UICommand
• JSF provides two ways to detect when a user interacts with UICommand components:
– Add the actionListener attribute
– Add the action attribute
• ActionListener and Action methods are usually located in a controller bean, not a model bean
• During the Invoke Application Phase of the lifecycle ActionListeners are called first followed by Actions
ActionListener and Action
Actions are generally used to invoke navigation
• ActionListeners are primarily used to execute business logic that does not result in navigation
• Both attributes can be used on a component:
<h:commandButton actionListener=“#{controller.authenticate}” action=“#{controller.login}” value=“login” />
• The 'authenticate' method is called first in the lifecyclefollowed by the 'login' method
19. commandButton
The h:commandButton renders an HTML <input type=“button” /> tag
• Unlike the input tag, this component will invoke an actionListener and/or action method when clicked
– This is a fundamental feature of an action based framework.
• The image attribute tells the component that it should render a specified image rather then the default button
widget
commandLink
The h:commandLink renders an HTML <a/> tag
• Unlike the <a/> tag this component will invoke an actionListener and/or action method when clicked
– This is a fundamental feature of an action based framework
• Child elements of the commandLink tag are wrapped by the anchor tag’s functionality
Immediate & Command Components
Command Components execute in the Invoke Application phase of the JSF lifecycle
• Conversion/Validation errors encountered in the Process Validations phase will cause the lifecycle to
skip the Invoke Application Phase
• The 'Immediate' attribute can be used to move the execution of ActionListeners and Actions to the Apply
Request Values phase
• The 'Immediate' attribute would be used with a “Cancel” button to insure ActionListeners and Actions
are called
JSF Selection Components
JSF contains a handful of basic "selection"
components that are equivalent to the HTML 4 select
elements.
20. Basic Selection Tag Usage
Each selection tag works like a parent-child container, and
has two necessary parts
The parent tag with the currently selected value:
<h:selectOneMenu value="#{modelBean.ourColor}">
The child tag(s) listing available items:
<f:selectItem itemLabel="Red" itemValue="red" />
The finished selectOneMenu code would be:
<h:selectOneMenu value="#{modelBean.ourColor}">
<f:selectItem itemLabel="Red" itemValue="red" />
<f:selectItem itemLabel="Green" itemValue="green" />
<f:selectItem itemLabel="Blue" itemValue="blue" />
</h:selectOneMenu>
Dynamic Selection Tag Usage
The available items can also be dynamically pulled from a bean:
<h:selectOneMenu value="#{modelBean.ourColor}">
<f:selectItems value="#{modelBean.availableColors}" />
</h:selectOneMenu>
The dynamic items could be an Array of Strings:
private String[] availableColors = {"Red", "Blue", "Green"};
public String[] getAvailableColors() {
return availableColors;
}
The items can now be modified directly in the backing bean list instead of at the page level
Now We will continue our previous program job applicant application
Now we will add two selection components to our page:
– h:selectOneRadio for title
• With a series of hardcoded f:selectItem
– h:selectOneMenu for country
• With a bound list of f:selectItems
• We will also introduce an h:panelGrid component to clean up our form layout
21. Step 1: Insert h:selectOneRadio Component
Insert the following at the top of the form:
<h:outputLabel for="title" value="Title: " />
<h:selectOneRadio id="title" value="#{jobApplicant.title}">
<f:selectItem itemLabel="Dr." itemValue="1" />
<f:selectItem itemLabel="Ms." itemValue="2" />
<f:selectItem itemLabel="Mrs." itemValue="3" />
<f:selectItem itemLabel="Miss" itemValue="4"/>
<f:selectItem itemLabel="Mr." itemValue="5"/>
</h:selectOneRadio>
• Each f:selectItem is hard coded into the page which is not a best practice
– Have to copy-paste between pages using the same component
– Incorrectly mixes model and view
– Better to dynamically load from a bean or database
Step 2: Insert h:selectOneMenu Component
Insert the following markup before the h:commandButton:
<h:outputLabel for="country" value="Country: " />
<h:selectOneMenu id="country" value="#{jobApplicant.country}">
<f:selectItem itemLabel="-Select-" noSelectionOption="true" />
<f:selectItems value="#{countryList.countries}" />
</h:selectOneMenu>
<br />
• Note our combination of selectable items:
– f:selectItem is used to present a default String that is not considered a selection (via noSelectionOption)
– f:selectItems has a value binding
• The values are not hard coded into the page and can be dynamically updated
Step 3: Add Variables to JobApplicant
Add two variables to JobApplicant.java:
private String title;
private String country;
• Generate getters and setters
• Note: These two variables are used to bind the model to the view
Step 4: Create CountryList Bean
Create a new bean class CountryList
@ManagedBean
@ApplicationScoped
public class CountryList {
private String[] countries = { "Canada", "United States" };
public String[] getCountries() {
22. return countries;
}
public void setCountries(String[] countryList) {
this.countries = countryList;
}
}
• Note: ApplicationScoped because it serves as a common list of countries bound to the h:selectOneMenu (Support
Managed Bean)
Step 5: Update Server Output
Update the server output after h:form tag:
<br />
- Server -<br />
Title: <h:outputText value="#{jobApplicant.title}" /><br />
First Name: <h:outputText value="#{jobApplicant.firstName}"
/><br />
Last Name: <h:outputText value="#{jobApplicant.lastName}"
/><br />
Country: <h:outputText value="#{jobApplicant.country}"
/><br />
Now run it to have this
h:panelGrid Description
h:panelGrid renders an HTML table
• Will be used to layout our existing components
• New rows are defined by the integer attribute 'columns'
– Once X number of child components are rendered a new row is started
• Child components are each placed in a table cell
24. DataTable
Now we will display data using data table,it is very important to display an arraylist or maps container data from
database to create an dynamic table
Consider
public class Employee {
private String id;
private String name;
private String phone;
private Date dob;
//getter and setter
}
@ManagedBean(name="employeeList")
@RequestScoped
public class EmployeeList {
public List<Employee>getEmployees(){
ArrayList<Employee>list=new ArrayList<Employee>();
Employee e1=new Employee();
e1.setId("121");
e1.setName("foo");
e1.setPhone("34343434");
e1.setDob(new Date(1983,10,2));
Employee e2=new Employee();
e2.setId("126");
e2.setName("bar");
e2.setPhone("543488888888434");
e1.setDob(new Date(1963,7,2));
Employee e3=new Employee();
e3.setId("1261");
e3.setName("jar");
e3.setPhone("000004343434");
e1.setDob(new Date(1953,1,2));
list.add(e1);
list.add(e2);
list.add(e3);
return list;
}
}
Now question is that how to display Employee list in an xhtml page?
Here we are going to use datatable as :
<h:dataTable value="#{employeeList.employees}" var="c" border="2">
<h:column>
<f:facet name="header">Employee Id:</f:facet>
#{c.id}
</h:column>
<h:column>
<f:facet name="header">Employee Name:</f:facet>
#{c.name}
26. 4. Nevigation
In JSF 1.2 we have to explicitly mention nevigation in faces-config.xml file as;
<navigation-rule>
<from-view-id>page1.xhtml</from-view-id>
<navigation-case>
<from-outcome>page2</from-outcome>
<to-view-id>/page2.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
This sort of explicit navigation is not required in JSF 2.0
We have Implicit navigation
How to use it?
1. Outcome in JSF page
<h:form>
<h:commandButton action="page2" value="Move to page2.xhtml" />
</h:form>
2. Outcome in Managed Bean
@ManagedBean
@SessionScoped
public class PageController implements Serializable {
public String moveToPage2(){
return "page2"; //outcome
}
}
Now code in page1.xhtml
<h:form>
<h:commandButton action="#{pageController.moveToPage2}"
value="Move to page2.xhtml by managed bean" />
</h:form>
Redirection
<h:form>
<h:commandButton action="page2?faces-redirect=true" value="Move to page2.xhtml" />
</h:form>
Conditional navigation in JSF2.0
JSF 2 comes with a very flexible conditional navigation rule to solve the complex page navigation flow, see the
following conditional navigation rule example
. JSF Page
A simple JSF page, with a button to move from this page to the payment page.
27. start.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!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>
<h2>This is start.xhtml</h2>
<h:form>
<h:commandButton action="payment" value="Payment" />
</h:form>
</h:body>
</html>
2. Managed Bean
A managed bean to provide sample data to perform the conditional checking in the navigation rule.
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.io.Serializable;
@ManagedBean
@SessionScoped
public class PaymentController implements Serializable {
private static final long serialVersionUID = 1L;
public boolean registerCompleted = true;
public int orderQty = 99;
//getter and setter methods
}
3. Conditional Navigation Rule
Normally, you declared the simple navigation rule in the “faces-config.xml” like this :
<navigation-rule>
<from-view-id>start.xhtml</from-view-id>
<navigation-case>
<from-outcome>payment</from-outcome>
<to-view-id>payment.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
With JSF 2, you can add some conditional checking before it move to the payment page, see following :
faces-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<faces-config
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version="2.0">
<navigation-rule>
<from-view-id>start.xhtml</from-view-id>
<navigation-case>
28. <from-outcome>payment</from-outcome>
<if>#{paymentController.orderQty < 100}</if>
<to-view-id>ordermore.xhtml</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>payment</from-outcome>
<if>#{paymentController.registerCompleted}</if>
<to-view-id>payment.xhtml</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>payment</from-outcome>
<to-view-id>register.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>
This is equal to the following Java code :
if (from-view-id == "start.xhtml"){
if(from-outcome == "payment"){
if(paymentController.orderQty < 100){
return "ordermore";
}else if(paymentController.registerCompleted){
return "payment";
}else{
return "register";
}
}
}
The code should be self explanatory enough.
Note
In the conditional navigation rule, the sequence of the navigation rule does affect the navigation flow,
always put the highest checking priority in the top.
29. 5. JSF life cycle and PhaseListners
The JSF2 framework defines a lifecycle that executes in distinct phases, these phases are:
1. Restore View
2. Apply Request Values
3. Process Validations
4. Update Model Values
5. Invoke Application
6. Render Response
Lifecycle has two logical portions Execute and Render
– Supports AJAX partial processing and partial rendering
– You can specify components that JSF processes on the server or that JSF renders when an Ajax call
returns
Restore View
A request comes through the FacesServlet controller.
The controller examines the request and extracts the view ID, which is
determined by the name of the xhtml page.
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 retrieved or created from the
FacesContext object, followed by their values.
Process validations
In this phase, each component will have its values validated against the application's validation
rules.
Update model value
30. In this phase JSF updates the actual values of the server-side model ,by updating the
properties of your backing beans.
Invoke application In this phase the JSF controller invokes the application to handle Form
submissions.
Render respons
In this phase JSF displays the view with all of its components in their current state.
Now before understanding JSF life cycle, lets discuss something ie called PhaseListner( aka Servlet Listners)
That can interfere during various life cycle phases. We can used it to observe what is going to happens during various
phases….
What is Phase Listners?
A PhaseListener is an Interface implemented on a java class that is registered with the JSF application
PhaseListeners provide hooks into the JSF lifecycle
Can be extremely helpful for application customization, optimization, and debugging
Can listen to all phases of the lifecycle or specific phases
The listener can be:
– Application wide with faces-config.xml
– Per page basis with <f:phaseListener>
Now to start let create another application, purpose of this application is to process job application by an applicant.
Job-applicant.xhtml
<h:body>
<h:form>
<h:panelGrid columns="2">
<h:outputLabel for="title" value="Title: " />
<h:selectOneRadio id="title" value="#{jobApplicant.title}">
<f:selectItem itemLabel="Dr." itemValue="1" />
<f:selectItem itemLabel="Ms." itemValue="2" />
<f:selectItem itemLabel="Mrs." itemValue="3" />
<f:selectItem itemLabel="Miss" itemValue="4" />
<f:selectItem itemLabel="Mr." itemValue="5" />
</h:selectOneRadio>
<h:outputLabel for="firstName" value="First Name: " />
<h:inputText id="firstName" value="#{jobApplicant.firstName}" />
<h:outputLabel for="lastName" value="Last Name: " />
<h:inputText id="lastName" value="#{jobApplicant.lastName}" />
<h:outputLabel for="country" value="Country: " />
<h:selectOneMenu id="country" value="#{jobApplicant.country}">
<f:selectItem itemLabel="-Select-" noSelectionOption="true" />
<f:selectItems value="#{countryList.countries}" />
</h:selectOneMenu>
<h:outputLabel for="salary" value="Salary: " />
<h:inputText id="salary" value="#{jobApplicant.salary}">
<f:convertNumber type="currency" integerOnly="true" />
</h:inputText>
<h:commandButton value="Submit Applicant" />
</h:panelGrid>
</h:form>
<br />
- Server -<br />
Title: <h:outputText value="#{jobApplicant.title}" />
<br />
First Name: <h:outputText value="#{jobApplicant.firstName}" />
<br />
Last Name: <h:outputText value="#{jobApplicant.lastName}" />
<br />
Country: <h:outputText value="#{jobApplicant.country}" />
<br />
Salary: <h:outputText value="#{jobApplicant.salary}" />
<br />
31. model
package com.beans;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
@ManagedBean(name="jobApplicant")
@ViewScoped
public class JobApplicant implements Serializable {
private static final long serialVersionUID = 1L;
private String firstName;
private String lastName;
private Integer title;
private String country;
private int salary;
public JobApplicant(){}
//getter and setter
}
for countries
package com.beans;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
@ManagedBean(name="countryList")
@ApplicationScoped
public class CountryList {
private String[] countries = { "Canada", "United States" };
public String[] getCountries() {
return countries;
}
public void setCountries(String[] countryList) {
this.countries = countryList;
}
}
Now run the application and play with it……..
32. Now our motive is to understand various life cycle phases….
So we are going to add PhaseListener to the jobApplication project
This PhaseListener will simply log the Phase ID to the Tomcat console log, before and after phases execute
Creating phase listner
step 1:Add and listner as shown
public class LoggingPhaseListener implements PhaseListener {
private static final long serialVersionUID = 1L;
………..
}
step 2: override methods
@Override
public void afterPhase(PhaseEvent event) {
System.out.println("AFTER PHASE: " + event.getPhaseId().toString());
}
@Override
public void beforePhase(PhaseEvent event) {
System.out.println("BEFORE PHASE: " + event.getPhaseId().toString());
}
@Override
public PhaseId getPhaseId() {
return PhaseId.ANY_PHASE;
}
step 3: register listner
LoggingPhaseListener class to be registered as a PhaseListener when the JSF
framework initializes
add following in jsf-config.xml
<lifecycle>
<phase-listener>
33. com.beans.listners.LoggingPhaseListener
</phase-listener>
</lifecycle>
step 4: ovserve the log
Next we are going to learn something about JSF Validators
After understanding validator we will come back on JSF life cycle…Don’t worry..
34. 6. JSF Validators
JSF utilizes validators to ensure user input matches criteria specified by the developer
This is achieved through:
– 6 standard built in JSF 2.0 validators
– required attribute on components
– Interdependent validation in the backing bean
– Custom validators (in a class or bean method)
JSF provides 6 built in validators:
– validateDoubleRange
• min/max range for a Double
– validateLongRange
• min/max range for a Long
– ValidateLength
• min/max input size
– ValidateBean
• Used in conjunction with Bean Validation API
• check preset business logic restraints
– validateRegex
• compare to a regular expression String
– validateRequired
• same as required attribute
Attribute "required"
JSF provides an attribute to ensure an input field is populated by the user
Use required="true/false"
For example:
<h:inputText value="#{modelBean.firstName}“ required="true"/>
How Validation is Performed
As part of the JSF Lifecycle a phase called PROCESS_VALIDATIONS is used
The lifecycle will be covered later
If validation fails JSF will generate an error message that can be displayed on the page
Validation error messages are displayed using <h:message>, for example:
<h:inputText id="firstName" value="#{modelBean.firstName}"
required="true"/>
<h:message for="firstName"/>
Custom Validator Class
Creating a custom validator is useful if you need to check input in a way not provided by the standard
validators
For example:
35. Country validation
Username uniqueness validation
Email format validation
We will step through the process of creating a custom validator latter let first appliy build in validator in
our existing application ….
Now modify earlier application xhtml page to incoporate JSF validation ….
final job applicant
-------------------------
<h:form>
<h:messages globalOnly="true" />
<h:panelGrid columns="3">
<h:outputLabel for="title" value="Title: " />
<h:selectOneRadio id="title" required="true"
value="#{jobApplicant.title}">
<f:selectItem itemLabel="Dr." itemValue="1" />
<f:selectItem itemLabel="Ms." itemValue="2" />
<f:selectItem itemLabel="Mrs." itemValue="3" />
<f:selectItem itemLabel="Miss" itemValue="4" />
<f:selectItem itemLabel="Mr." itemValue="5" />
</h:selectOneRadio>
<h:message for="title" />
<h:outputLabel for="firstName" value="First Name: " />
<h:inputText id="firstName" value="#{jobApplicant.firstName}"
required="true" />
<h:message for="firstName" />
<h:outputLabel for="lastName" value="Last Name: " />
<h:inputText id="lastName" value="#{jobApplicant.lastName}"
required="true" />
<h:message for="lastName" />
<h:outputLabel for="country" value="Country: " />
<h:selectOneMenu id="country" value="#{jobApplicant.country}"
required="true">
<f:selectItem itemLabel="-Select-" noSelectionOption="true" />
<f:selectItems value="#{countryList.countries}" />
</h:selectOneMenu>
<h:message for="country" />
<h:outputLabel for="salary" value="Salary: " />
<h:inputText id="salary" value="#{jobApplicant.salary}"
required="true">
<f:convertNumber type="currency" integerOnly="true" />
<f:validateLongRange minimum="1" maximum="1000000" />
</h:inputText>
<h:message for="salary" />
<h:commandButton actionListener="#{jobApplicant.submit}"
value="Submit Applicant" />
</h:panelGrid>
</h:form>
<br />
- Server -<br />
Title: <h:outputText value="#{jobApplicant.title}" />
<br />
First Name: <h:outputText value="#{jobApplicant.firstName}" />
<br />
Last Name: <h:outputText value="#{jobApplicant.lastName}" />
<br />
Country: <h:outputText value="#{jobApplicant.country}" />
<br />
Salary: <h:outputText value="#{jobApplicant.salary}" />
<br />
Focus on highlighted text , it is not difficult to guss the purpose of the tags incorporated.
Run it and Observe following output…
36. Now you observe that error message looks really bad, how to customized it( hold down I will be discuss it with
internationalization )
Interdependent Field Validation – ActionListener
Now lets say what my bussiness logic want that I should check firstname and last name from database and if they
already exist then I should not allow user to be created ..what to do?
Assume that firstName: foo
lastName:bar
is already exist, so I should not allow to enter that user again……..
Steps
Step:1
Paste following code in class JobApplicant
public void submit(ActionEvent ae) {
if (firstName.equals("foo") && lastName.equals("bar")) {
String msg = "foo bar already works for us";
FacesMessage facesMessage = new FacesMessage(msg);
FacesContext facesContext = FacesContext.getCurrentInstance();
String clientId = null; // this is a global message
facesContext.addMessage(clientId, facesMessage);
}
}
Step 2;
Replace earlier command button with this……
<h:commandButton actionListener="#{jobApplicant.submit}"
value="Submit Applicant" />
The new actionListener attribute is bound to the jobApplicant.submit() method.
Step 3;
Add following after<h:form> tags
<h:messages globalOnly="true" />
Now Validation should fail with the global error message “foo bar already works for us”
37. Custom Validator Exercise
Now lets add an email field and we only want to allow valid email into it.
Step 1;
Add after last name field:
<h:outputLabel for="email" value="email:" />
<h:inputText id="email" value="#{jobApplicant.email}"
validator="emailValidator" required="true" />
<h:message for="email" />
Step 2: add email field to our bean with getter and setter…….
Step 3: Create an validator class EmailValidator that implements Validator inteface
Step 4:
Add @FacesValidator("emailValidator") over it, so that it get register with framework.
Step 5:
Implement validate() method
As
@Override
public void validate(FacesContext arg0, UIComponent arg1, Object arg2)
throws ValidatorException {
String inputEmail = (String) arg2;
// Set the email pattern string. (?i) is a flag for case-insensitive.
Pattern p = Pattern.compile("(?i)b[A-Z0-9._%-]+@[A-Z0-9.-]+.[A-Z]{2,4}b");
// Match the given string with the pattern
Matcher m = p.matcher(inputEmail);
// Check whether match is found
boolean matchFound = m.matches();
if (!matchFound) {
String invalidEmailMsg = "Invalid Email";
FacesMessage message = new FacesMessage(
FacesMessage.SEVERITY_ERROR, invalidEmailMsg,
invalidEmailMsg);
throw new ValidatorException(message);
}
}
Now you must have understand that we have to refer
this validator in <h:inputText>
39. 7. JSF Converters
JSF uses converters to modify input and format output
Conversion options:
– Implicit or Explicit conversion of datatypes
– Standard convertDateTime and convertNumber tags
– Create Custom Converters
JSF implicitly converts bound values to the proper datatype,for example:
On the page:
<h:inputText value="#{modelBean.age}"/>
– In the backing bean:
private int age;
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
Instead of requiring a String datatype JSF can handle the int age automatically
Standard Converter Tag Examples
f:convertDateTime usage:
<h:inputText value="#{modelBean.dateOfBirth}">
<f:convertDateTime type="date"
timeZone="#{zoneUtil.currentTimeZone}"
pattern="MM/dd/yy"/>
</h:inputText>
f:convertNumber usage:
<h:inputText value="#{modelBean.accountBalance}">
<f:convertNumber type="currency" groupingUsed="true"
minIntegerDigits="2" maxIntegerDigits="2"
currencyCode="$"/>
</h:inputText>
Custom Converters
Creating a custom converter is useful if you need to format input or output to match your business logic
– For example:
Social Security number converter
Phone number converter
Credit card converter
Next i step through the process of creating a custom converter
The goal of this example is to Capitalize our firstName and lastName input using a custom
Converter
Step 1:
Create an Converter class
40. public class WordCapatilizationConverter implements Converter{
@Override
public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
// TODO Auto-generated method stub
return null;
}
@Override
public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {
// TODO Auto-generated method stub
return null;
}
}
Step 2: Annotate with
@FacesConverter("wordCapitalization")
Step 3:
Override methods and provide logic to word capatilization
@Override
public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
return fixCapitalization(arg2);
}
@Override
public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {
return fixCapitalization((String) arg2);
}
private String fixCapitalization(String inString) {
if (inString == null) {
return "";
}
StringBuffer str = new StringBuffer(inString.trim().toLowerCase());
if (str.length() == 0) {
return str.toString();
}
Character nextChar;
int i = 0;
nextChar = new Character(str.charAt(i));
while (i < str.length()) {
str.setCharAt(i++, Character.toUpperCase(nextChar.charValue()));
if (i == str.length()) {
return str.toString();
}
// Look for whitespace
nextChar = new Character(str.charAt(i));
while (i < str.length() - 2
&& !Character.isWhitespace(nextChar.charValue())) {
nextChar = new Character(str.charAt(++i));
}
if (!Character.isWhitespace(nextChar.charValue())) {
// If not whitespace, we must be at end of string
return str.toString();
}
// Remove all but first whitespace
nextChar = new Character(str.charAt(++i));
while (i < str.length()
&& Character.isWhitespace(nextChar.charValue())) {
str.deleteCharAt(i);
nextChar = new Character(str.charAt(i));
}
}
return str.toString();
}
Step 4: Apply conversion to view
42. 8. Internationalization
Internationalization
JSF has full support for Java il8n
• You can use internationalization in pages and beans
• Configure your supported languages in faces-config.xml
• JSF provides the ability to dynamically switch locales
• Can also override default JSF message and error text
faces-config.xml Supported Locales
The <locale-config> element is used in facesconfig.xml
Specify a default locale and any supported locales
– Use the lower-case, two-letter codes as defined by ISO-639
<application>
<locale-config>
<default-locale>en</default-locale>
<supported-locale>de</supported-locale>
<supported-locale>it</supported-locale>
</locale-config>
</application>
Note: The above code would support English, German, and Italian
faces-config.xml Resource Bundles
Strings are added to properties files and registered with JSF using the <resource-bundle>
element in faces-config.xml
Specify a base-name used by each properties file:
<application>
<resource-bundle>
<base-name>
com.messages
</base-name>
<var>msgs</var>
</resource-bundle>
</application>
We create a "messages_xy.properties" file for each supported locale
– Where "xy" is our two letter language identifier
– The files are placed in the specified package
43. Language Files
In each "messages_xy.properties" file we would specify:
– Key used in our page/bean
– Internationalized value for the key
For example the content of messages_en.properties:
firstName=First Name
lastName=Last Name
submit=Submit
And the content of messages_de.properties:
firstName=Vorname
lastName=Nachname
submit=Reichen Sie ein
Using Internationalization in Pages
In our page we can access these properties files using the EL (Expression Language)
The EL uses the <var> element specified in the <resource-bundle> to retrieve key values:
<h:outputText value="#{msgs['firstName']}" />
Or
<h:outputText value="#{msgs.firstName}" />
Would display:
– "First Name" in English
"Vorname" in German
Lets start modifiying existing application to support internationlization
Step 1: Create Resource Bundle
Create a file Msgs_en.properties in a new com.resources package and paste the
following into it:
title=Title
firstName=First Name
lastName=Last Name
email=Email
country=Country
salary=Salary
submitApplicant=Submit Applicant
Let create another resource bunld for german language
44. messages_de.properties:
firstName=Vorname
lastName=Nachname
submit=Reichen Sie ein
Step 2:
In the faces-config.xml file, add the resource bundle to the application node:
<application>
<resource-bundle>
<base-name>com.resources.Msgs</base-name>
<var>msgs</var>
</resource-bundle>
</application>
Step 3: change value binding
<h:outputLabel for="title" value="#{msgs.title}" />
<h:outputLabel for="firstName" value="#{msgs.firstName}" />
<h:outputLabel for="lastName" value="#{msgs.lastName}" />
<h:outputLabel for="email" value="#{msgs.email}" />
<h:outputLabel for="country" value="#{msgs.country}" />
<h:outputLabel for="salary" value="#{msgs.salary}" />
<h:commandButton value="#{msgs.submitApplicant}" .../>
Now run the application , you find label messages are coming from resource bundle
Now pending question how to customized error message in jsf 2, We have power to override default
messages usign
JSF Message Keys
JSF-override_xy.properties can reference existing keys
For example the JSF key for the default required message:
javax.faces.component.UIInput.REQUIRED
In the properties file override the value:
45. javax.faces.component.UIInput.REQUIRED=Missing a value.
Now changes the validation message for required="true“ to "Missing a value."
Override Standard JSF Messages
In order to override standard JSF messages create a file in the com.resources package named
JSF-override_en.properties
Paste the following key override into it:
javax.faces.component.UIInput.REQUIRED=Required
Open the faces-config.xml file and add the following entry to the <application> section:
<application>
<message-bundle>
com.resources.JSF-override
</message-bundle>
...
</application>
Now run and observe,that it print customized error messages