1. Trang chủ
  2. » Công Nghệ Thông Tin

leJSF Mkyong Tutorial

321 622 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề JSF Mkyong Tutorial
Tác giả Mkyong
Trường học Unknown
Chuyên ngành Computer Science
Thể loại Tutorial
Năm xuất bản 2012
Thành phố Unknown
Định dạng
Số trang 321
Dung lượng 5,03 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

@SessionScoped public class HelloBean implements Serializable private static final long serialVersionUID = 1L ; private String name ; public String getName return name; } public void se

Trang 2

@ManagedBean //allow call this bean in xhtml page

@SessionScoped

public class HelloWorld implements java.io.Serializable{

private static final long serialVersionUID = 1L;

private String name;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public static long getSerialversionuid() {

return serialVersionUID; }

}

web.xml

<? xml version ="1.0" encoding ="UTF-8"?>

< web-app id ="WebApp_ID" version ="2.5"

< param-name >javax.faces.STATE_SAVING_METHOD</ param-name >

< param-value >client</ param-value >

</ context-param >

< context-param >

< name >javax.servlet.jsp.jstl.fmt.localizationContext</ param-name >

param-< param-value >resources.application</ param-value >

Trang 3

< servlet-name >Faces Servlet</ servlet-name >

< servlet-class >javax.faces.webapp.FacesServlet</ servlet-class >

< load-on-startup >1</ load-on-startup >

</ servlet >

< servlet-mapping >

< servlet-name >Faces Servlet</ servlet-name >

< url-pattern >/faces/*</ url-pattern >

< servlet-name >Faces Servlet</ servlet-name >

< url-pattern >*.faces</ url-pattern >

< h:inputText value ="#{helloWorld.name}" />

< h:commandButton action ="welcome" value ="Welcome Me" />

</ h:form >

</ h:body >

</ html >

welcome.xhtml

Trang 4

<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

Trang 5

Reference :

JSF 2.0 hello world example

Posted on September 7, 2010 , Last modified : November 6, 2012

Trang 6

First, review the final project structure, in case you are confused about where should create the corresponding files or folder later.

1 JSF 2.0 Dependencies

Maven central repository has the JSF version up to 1.2 only, to get the JSF 2.0, you may need to

download from Java.net repository

The maven central repository is updated JSF library to 2.1.7 The previous Java.net repository is

no longer required

For Java EE Application Server like Glassfish

In most Java EE application servers, it has build-in support for JSF 2.0, so you need to

download the single JSF API for development purpose

Trang 7

</repository>

</repositories>

For simple servlet container like Tomcat

This is a bit troublesome, you need to download following dependencies

Trang 8

The el-ri.jar is an arguable dependency in the Tomcat servlet container, even it’s not stated in

the release note, but you need this library to solve the “JSP version of the container is older than 2.1…” error message

Trang 9

@SessionScoped

public class HelloBean implements Serializable

private static final long serialVersionUID = 1L ;

private String name ;

public String getName ()

return name;

}

public void setName( String name ) {

this.name name ;

File : hello.xhtml – Renders a JSF text box and link it with the “helloBean” (JSF managed bean),

“name” property, and also a button to display the “welcome.xhtml” page when it’s clicked.

<?xml version = "1.0" encoding = "UTF-8"?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

<h:inputText value = "#{helloBean.name}"></h:inputText>

<h:commandButton value = "Welcome Me"

action = "welcome"></h:commandButton>

</h:form>

Trang 10

</h:body>

</html>

Note

In JSF 1.x, you had to declare the “navigation rule” in “faces-config.xml“, to tell which page to

display when the button is clicked In JSF 2.0, you can put the page name directly in the button’s

“action” attribute For simple navigation, it’s more than enough, but, for complex navigation, you are still advised to use the “navigation rule” in “faces-config.xml“.

File : welcome.xhtml – Display the submitted text box value.

<?xml version = "1.0" encoding = "UTF-8"?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

<h:body bgcolor = "white">

<h3>JSF 2.0 Hello World Example - welcome.xhtml</h3>

“helloBean” again and display the name property value via the getName() method.

4 JSF 2.0 Serlvet Configuration

Just like any other standard web frameworks, you are required to configure JSF stuffs in

web.xml file.

File : web.xml

<?xml version = "1.0" encoding = "UTF-8"?>

<web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"

Trang 11

In JSF 2.0 development, it’s recommended to set the “javax.faces.PROJECT_STAGE” to

“Development“, it will provide many useful debugging information to let you track the bugs easily For deployment, just change it to “Production“, you just do not want your customer to

look at this annoying debugging information :)

5 Demo

A long article end with a project demo :)

Trang 12

URL : http://localhost:8080/JavaServerFaces/hello.jsf

A simple JSF page, with a text box and a button

When the button is clicked, displays the submitted text box value

Download Source Code

Download It (v2.1.7 example)- JSF2.0-hello-world-example-2.1.7.zip (8KB)

Download It (old v2.1.0-b03 example)- JSF-2-Hello-World-Example-2.1.0-b03.zip (8KB)

References

Trang 13

1 JavaServer Faces Technology

2 JSF 2.0 release note

3 Wiki : JavaServer Faces

4 Wiki : XHTML file explanation

5 java.lang.IllegalArgumentException: javax.faces.context.ExceptionHandlerFactory

6 JSF 2.0 + Tomcat : It appears the JSP version of the container is older than 2.1…

7 Eclipse IDE : Unsupported content type in editor

8 Eclipse IDE : xhtml code assist is not working for JSF tag

2.JSF 2.0 +Ajax hello world example

public class HelloWorld implements java.io.Serializable{

private static final long serialVersionUID = 1L;

private String name;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public static long getSerialversionuid() {

return serialVersionUID; }

public String SayWelcome(){

if(this.name!=null && !this.name.equals( "" )){

return "Ajax message :" +this.name;

Trang 14

return "" ; }

< h:inputText id ="name" value ="#{helloWorld.name}" />

< h:commandButton value ="Welcome Me"

< f:ajax execute ="name" render ="output"></ f:ajax >

Trang 15

Reference :

JSF 2.0 + Ajax hello world example

Posted on September 8, 2010 , Last modified : August 29, 2012

By mkyong

In JSF 2.0, coding Ajax is just like coding a normal HTML tag, it’s extremely easy In this tutorial, you will restructure the last JSF 2.0 hello world example, so that, when the button is clicked, it will make an Ajax request instead of submitting the whole form

1 JSF 2.0 Page

A JSF 2.0 xhtml page with Ajax support

helloAjax.xhtml

Trang 16

<?xml version = "1.0" encoding = "UTF-8"?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

<h:inputText id = "name" value = "#{helloBean.name}"></h:inputText>

<h:commandButton value = "Welcome Me">

<f:ajax execute = "name" render = "output" />

<h:commandButton value = "Welcome Me">

<f:ajax execute = "name" render = "output" />

</h:commandButton>

<h:outputText id = "output" value = "#{helloBean.sayWelcome}" />

In the <f:ajax> tag :

1. execute=”name” – Indicate the form component with an Id of “name” will be sent to the

server for processing For multiple components, just split it with a space in between, e.g

execute=”name anotherId anotherxxId” In this case, it will submit the text box value.

2. render=”output” – After the Ajax request, it will refresh the component with an id of

“output“ In this case, after the Ajax request is finished, it will refresh the

Trang 17

@SessionScoped

public class HelloBean implements Serializable

private static final long serialVersionUID = 1L ;

private String name ;

public String getName ()

return name;

}

public void setName( String name ) {

this.name name ;

Access the URL : http://localhost:8080/JavaServerFaces/helloAjax.jsf

When the button is clicked, it makes an Ajax request and pass the text box value to the server for

processing After that, it refresh the outputText component and display the value via

getSayWelcome() method, without any “page flipping effect“.

Trang 18

Download Source Code

Download it – JSF-2-Ajax-Hello-World-Example.zip (8KB)

3.Resources (library) in JSF 2.0

Example :

Trang 19

< h:outputStylesheet library ="default"

< h3 >JSF 2.0 Hello World Example - hello.xhtml</ h3 >

< h:form >

< h:inputText id ="name" size ="30" value ="#{helloWorld.name}"

/>

< h:commandButton value ="Welcome Me"

< f:ajax execute ="name" render ="output"></ f:ajax >

In JSF 2.0, all your web resources files like css, images or JavaScript, should put in “resources”

folder, under the root of your web application (same folder level with “WEB-INF“)

Trang 20

The sub-folder under “resources” folder is consider as “library” or “project theme“, later you

can reference those “resources” with library attribute This new JSF resources management mechanism is really useful, it allow developer to change the web resources easily by

“theme/library” or “versioning”

See below examples :

Figure 1-0 : Example of a JSF2 project folder structure.

1 Normal Example

Here are some examples using “resources” and “library” in JSF 2.0.

1 Include CSS file – h:outputStylesheet

Trang 21

<h:outputStylesheet library = "theme1" name = "css/style.css" >

HTML output…

<link type = "text/css" rel = "stylesheet"

href = "/JavaServerFaces/faces/javax.faces.resource/css/style.css? ln=theme1" >

2 Display images – h:graphicImage

<h:graphicImage library = "theme1" name = "img/sofa.png" >

HTML output…

<img src = "/JavaServerFaces/faces/javax.faces.resource/img/sofa.png? ln=theme1" >

3 Include JavaScript – h:outputScript

<h:outputScript library = "theme1" name = "js/hello.js" >

Refer to Figure 1-0, create a “version” folder matching regex \d+(_\d+)* under “library”

folder, and the default JSF ResourceHandler will always get the highest version to display

P.S Assume your project is Figure 1-0 structure

Include CSS file – h:outputStylesheet

<h:outputStylesheet library = "default" name = "css/style.css" >

Since “default” theme contains version “1_0” and “2_0“, JSF will always get the resources from

the highest version, and append the version at the end of the resource

Trang 22

Thanks BalusC for the comment, guide and correction, and sorry for my previous misleading guide.

References

1 What is the JSF resource library for and how should it be used?

2 JSF ResourceHandler JavaDoc

3 JSF 2.0 New Feature Preview Series (Part 2.1): Resources

4.Configure managed beans in JSF 2.0

< managed-bean-name >helloWorld</ managed-bean-name >

< managed-bean-class >com.mkyong.common.HelloWorld</ class >

managed-bean-< managed-bean-scope >session</ managed-bean-scope >

</ managed-bean >

</ faces-config >

Reference:

Configure Managed Beans in JSF 2.0

Posted on September 9, 2010 , Last modified : August 29, 2012

Trang 23

By mkyong

In JSF 2.0, Java bean that can be accessed from JSF page is called Managed Bean The

managed bean can be a normal Java bean, which contains the getter and setter methods, business logic or even a backing bean (a bean contains all the HTML form value)

There are two ways to configure the managed bean :

1 Configure Managed Bean with Annotation

In JSF 2.0, you can annotated a Managed Bean with new @ManagedBean annotation.

public class HelloBean implements Serializable

private static final long serialVersionUID = 1L ;

private String name ;

public String getName ()

return name;

}

public void setName( String name ) {

this.name name ;

}

}

2 Configure Managed Bean with XML

With XML configuration, you can use the old JSF 1.x mechanism to define the managed bean in

a normal faces-config.xml file.

<?xml version = "1.0" encoding = "UTF-8"?>

</managed-bean>

</faces-config>

Trang 24

Best Practice

It’s recommended to put the managed beans in a separate XML file because the faces-config.xml is used

to set the application level configurations.

So, you should create a new XML file and put the managed beans detail inside, and declared the

XML file in the javax.faces.CONFIG_FILES initialize parameter, which is inside the INF/web.xml file.

Injecting Managed beans in JSF 2.0

Posted on September 10, 2010 , Last modified : August 29, 2012

By mkyong

In JSF 2.0, a new @ManagedProperty annotation is used to dependency injection (DI) a

managed bean into the property of another managed bean

Let see a @ManagedProperty example :

Trang 25

MessageBean.java – A managed bean named “message“.

public class MessageBean implements Serializable

//business logic and whatever methods

public class HelloBean implements Serializable

@ManagedProperty ( value = "#{message}" )

private MessageBean messageBean;

//must povide the setter method

public void setMessageBean( MessageBean messageBean ) {

this.messageBean messageBean ;

}

//

}

In this example, it uses the @ManagedProperty annotation to DI the “message” bean

(MessageBean.java) into the property (messageBean) of the “hello” bean (HelloBean.java) via setter method, setMessageBean().

Trang 26

6.Implicit navigation in JSF 2.0

Example :

MessageBean.java

package com.mkyong.common;

public class MessageBean implements java.io.Serializable {

private String message;

public String getMessage() {

return message;

}

public void setMessage(String message) {

this.message = message;

}

public String movePageController(){

if(this.message==null || this.message.equals( "" )){

return "SayHelloBean?faces-redirect=true" ; }

return "welcome?faces-redirect=true" ; }

action ="#{messageBean.movePageController()}" />

</ h:form >

</ h:body >

</ html >

Trang 27

In JSF 2, it treats “outcome” as the page name, for example, navigate to “page1.xhtml”, you have

to put the “outcome” as “page1″ This mechanism is called “Implicit Navigation“, where you

don’t need to declare the tedious navigation rule, instead, just put the “outcome” in the action

attribute directly and JSF will find the correct “view id” automatically.

There are two ways to implements the implicit navigation in JSF 2

1 Outcome in JSF page

You can put the “outcome” directly in the JSF page

page1.xhtml – A JSF page with a command button to move from current page to “page2.xhtml”.

2 Outcome in Managed Bean

Besides, you can also define the “outcome” in a managed bean like this :

Trang 28

@ManagedBean

@SessionScoped

public class PageController implements Serializable

public String moveToPage2 (){

return "page2" ; //outcome

<h:commandButton action = "#{pageController.moveToPage2}"

value = "Move to page2.xhtml by managed bean" >

< h:form>

Redirection

By default, JSF 2 is perform a forward while navigating to another page, it caused the page URL

is always one behind :) For example, when you move from “page1.xhtml” to “page2.xhtml”, thebrowser URL address bar will still showing the same “page1.xhtml” URL

To avoid this, you can tell JSF to use the redirection by append the “faces-redirect=true” to the

end of the “outcome” string

For simple page navigation, this new implicit navigation is more then enough; For complex page

navigation, you are still allow to declare the page flow (navigation rule) in the faces-config.xml

Trang 29

< f:loadBundle basename ="com.mkyong.message.message" var ="msg"/>

< h2 >JSF 2.0 and Resource bundle example</ h2 >

< ol >

< li >< h:outputText value ="#{msg['message']}" /></ li >

< li >< h:outputText value ="#{msg['message.test1']}" /> </ li >

< li >< h:outputText value ="#{msg['message.test2']}"

escape ="false"/> </ li >

< li >< h:outputText value ="#{msg['message.test3']}"

escape ="false"/> </ li >

< li >

< h:outputFormat value ="#{msg['message.param1']}">

< f:param value ="param 1"></ f:param >

</ h:outputFormat >

</ li >

Trang 30

< li >

< h:outputFormat value ="#{msg['message.param2']}"

< f:param value ="param 1"></ f:param >

< f:param value ="param 2"></ f:param >

JSF 2.0 and Resource Bundles example

Posted on September 8, 2010 , Last modified : August 29, 2012

By mkyong

Trang 31

In this tutorial, we demonstrate the use of resource bundle to display messages in JSF 2.0 For maintainability concern, it’s always recommended to put all the messages in properties file, instead of hard-code the message in page directly.

1 Properties File

Create a properties file, contains message for the page, and put it into the project’s resource folder, see figure below

messages.properties

message = This is "message"

message.test1 = This is "message.test1"

message.test2 = This is "<h2>message.test3</h2>"

message.test3 = This is "&lt;h2&gt;message.test4&lt;/h2&gt;"

message.param1 = This is "message.param1" - { }

message.param2 = This is "message.param2" - { } and { }

Project folder structure

2 Using Resource Bundles

There are two ways to load the properties file into JSF 2.0

1 Global Resource Bundle

To load the properties file globally, so that all the jsf pages can access the messages You can

create a “faces-config.xml” file and declare the properties file explicitly.

Trang 32

2 Local Resource Bundle

To load the properties file locally, or for specified page only Declare the <f:loadBundle /> tag

in the page that need to access the message in the messages.properties.

<f:loadBundle basename = "com.mkyong.messages" var = "msg" /

3 JSF 2.0 Pages

In this case, the messages.properties file is given a name of “msg“, to access the message, just use “msg.key“.

hello.xhtml

<?xml version = "1.0" encoding = "UTF-8" ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

<li><h:outputText value = "#{msg.message}" >< /li>

<li><h:outputText value = "#{msg['message.test1']}" >< /li>

<li><h:outputText value = "#{msg['message.test2']}" >< /li>

<li><h:outputText value = "#{msg['message.test2']}" escape = "false"

/ >< /li>

<li><h:outputText value = "#{msg['message.test3']}" >< /li>

<li><h:outputText value = "#{msg['message.test3']}" escape = "false"

/ >< /li>

Trang 33

<li>

<h:outputFormat value = "#{msg['message.param1']}" >

<f:param value = "param0" >

< h:outputFormat>

< li>

li>

<h:outputFormat value = "#{msg['message.param2']}" >

<f:param value = "param0" >

<f:param value = "param1" >

A normal way to access the message

<h:outputText value = "#{msg.message}" >

To display HTML tag in the message, just add the “escape” attribute and set it to false.

<h:outputText value = "#{msg['message.test2']}" >

<h:outputText value = "#{msg['message.test2']}" escape = "false" >

<h:outputText value = "#{msg['message.test3']}" >

<h:outputText value = "#{msg['message.test3']}" escape = "false" >

//properties file

message.test2 = This is " <h2> message.test3 < h2>

message.test3 = This is " &lt; h2 &gt; message.test4 &lt; /h2 &gt; "

Example 4

For a parameter message, just use the <h:outputFormat /> and <f:param / > tag.

<h:outputFormat value = "#{msg['message.param1']}" >

<f:param value = "param0" >

< h:outputFormat>

Trang 34

<h:outputFormat value = "#{msg['message.param2']}" >

<f:param value = "param0" >

<f:param value = "param1" >

< h:outputFormat>

//properties file

message.param1 = This is "message.param1" - {0}

message.param2 = This is "message.param2" - {0} and {1}

Trang 35

public class Language implements java.io.Serializable{

private String localeCode;

private static Map<String, Object> countries;

static{

countries=new LinkedHashMap<String, Object>();

Trang 36

countries.put( "English" , Locale.ENGLISH);

countries.put( "Chinese" , Locale.SIMPLIFIED_CHINESE);

}

public Map<String, Object> getCountriesInMap(){

return countries; }

public String getLocaleCode() {

return localeCode;

}

public void setLocaleCode(String localeCode) {

this.localeCode = localeCode;

}

public static Map<String, Object> getCountries() {

return countries; }

public static void setCountries(Map<String, Object> countries) {

Language.countries = countries;

Trang 37

< default-locale >en</ default-locale >

< f:loadBundle basename ="com.mkyong.message.message" var ="msg"/>

< h2 >JSF 2.0 and Resource bundle example</ h2 >

< ol >

< li >< h:outputText value ="#{msg['message']}" /></ li >

< li >< h:outputText value ="#{msg['message.test1']}" /> </ li >

< li >< h:outputText value ="#{msg['message.test2']}"

escape ="false"/> </ li >

< li >< h:outputText value ="#{msg['message.test3']}"

escape ="false"/> </ li >

< li >

< h:outputFormat value ="#{msg['message.param1']}">

< f:param value ="param 1"></ f:param >

</ h:outputFormat >

</ li >

< li >

< h:outputFormat value ="#{msg['message.param2']}"

< f:param value ="param 1"></ f:param >

< f:param value ="param 2"></ f:param >

Trang 38

Language / Locale Supported since version

English, US (en_US) 1.1

Trang 39

German, Germany (de_DE) 1.1 Chinese, PRC (zh_CN) 1.5

Chinese, Taiwan (zh_TW) 1.5 Czech, Czech Republic (cs_CZ) 1.5 Dutch, Belgium (nl_BE) 1.5

Dutch, Netherlands (nl_NL) 1.5 English, Australia (en_AU) 1.5 English, Britain (en_GB) 1.5

English, Canada (en_CA) 1.5

English, New Zealand (en_NZ) 1.5 English, Singapore(en_SG) 1.5 French, Belgium (fr_BE) 1.5

French, Canada (fr_CA) 1.5

French, France (fr_FR) 1.5

French, Switzerland (fr_CH) 1.5 German, Austria (de_AT) 1.5

German, Liechtenstein (de_LI) 1.5 German, Switzerland (de_CH) 1.5 Italian, Italy (it_IT) 1.5

Italian, Switzerland (it_CH) 1.5 Japanese (ja_JP) 1.5

Korean (ko_KR) 1.5

Polish (pl_PL) 1.5

Russian (ru_RU) 1.5

Spanish (es_ES) 1.5

Arabic, Egypt (ar_EG) 2.3

Arabic, Israel (ar_IL) 2.3

Bulgarian, Bulgaria (bg_BG) 2.3 Catalan, Spain (ca_ES) 2.3

Croatian, Croatia (hr_HR) 2.3 Danish, Denmark(da_DK) 2.3 English, India (en_IN) 2.3

English, Ireland (en_IE) 2.3

English, Zimbabwe (en_ZA) 2.3 Finnish, Finland (fi_FI) 2.3

Greek, Greece (el_GR) 2.3

Hebrew, Israel (iw_IL)* 2.3

Hindi, India (hi_IN) 2.3

Hungarian, Hungary (hu_HU) 2.3 Indonesian, Indonesia (in_ID)* 2.3

Trang 40

Ukrainian, Ukraine (uk_UA) 2.3

Vietnamese, Vietnam (vi_VN) 2.3

Reference :

JSF 2 internationalization example

Posted on November 9, 2010 , Last modified : August 29, 2012

By mkyong

In JSF application, you can change your application locale programmatically like this :

//this example change locale to france

FacesContext getCurrentInstance () getViewRoot () setLocale (new Locale ( 'fr' )

It makes JSF support for internationalization or multiple languages easily

Complete JSF internationalization example

In this tutorial, we show you a JSF 2.0 web application, which display a welcome page, retrieve

a welcome message from properties file, and change the welcome message dynamically based onthe selected language

Ngày đăng: 06/05/2014, 13:54

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN

w