您的当前位置:我要购书网>在线阅读>Java/J2EE/JSP

myeclipse 下开发jsf教程

来源:互联网  作者:  发布:我要购物网收集整理  发布时间:2006-8-31 人气:763

First step with JavaServer Faces using EclipseThis tutorial facilitates the first steps with the quite new framework JavaServer Faces (JSF). Step by step an example application (a library) will be created, which illustrate the different elements of the framework.The example application will provide the following functionality.Display a book overview (list of books)Add, edit and delete a bookGenerals

Author:

Sascha Wolski

http://www.laliluna.de/tutorials.html Tutorials for Struts, EJB, xdoclet, JSF, JSP and eclipse.

Date:

December, 21 2004


Source code:

The sources do not contain any project files of eclipse or libraries. Create a new project following the tutorial, add the libraries as explained in the tutorial and then you can copy the sources in your new project.http://www.laliluna.de/assets/tutorials/first-java-server-faces-tutorial.zipPDF Version des Tutorials:http://www.laliluna.de/assets/tutorials/first-java-server-faces-tutorial-en.pdf

Development Tools

Eclipse 3.x

MyEclipse plugin 3.8

(A cheap and quite powerful Extension to Eclipse to develop Web Applications and EJB (J2EE) Applications. I think that there is a test version availalable at MyEclipse.)


Application Server

Jboss 3.2.5

You may use Tomcat here if you like.




Create a JavaServer faces projectCreate a new web project. File > New > Project.

Set a nice name and add the JSTL Libraries to the project.

Add the JavaServer faces Capabilities. Right click on the project and choose MyEclipse > Add JSF Capabilities.



The class Book

Add an new package de.laliluna.tutorial.library und create a new class named Book.





Open the class and add the following private properties:

id

author

title

available

Generate a getter- and setter-method for each property. Right click on the editor window and choose Source > Generate Getter- and Setter Methods.





Furthermore you have to add a constructor, which set the properties if you initialisize the instance variable of the newly object.

The following source code show the class book.public class Book implements Serializable {

// ------------------ Properties --------------------------------
private long id;
private String author;
private String title;
private boolean available;

// ------------------ Constructors --------------------------------
public Book(){}
public Book(long id, String author, String title, boolean available){
this.id = id;
this.author = author;
this.title = title;
this.available = available;
}

// ------------------ Getter and setter methods ---------------------

public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public boolean isAvailable() {
return available;
}
public void setAvailable(boolean available) {
this.available = available;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}



Add a getter and setter for the class./**
* Set the properties
* @param book
*/
public void setBook(Book book){
this.setId(book.getId());
this.setAuthor(book.getAuthor());
this.setTitle(book.getTitle());
this.setAvailable(book.isAvailable());
}

/**
* @return book object
*/
public Book getBook(){

return new Book(this.getId(),
this.getAuthor(),
this.getTitle(),
this.isAvailable());
}



The database classWe use a class to provide some test data without using a database. Download the sample application of this tutorial and copy the class SimulateDB.java find in the folder srchttp://www.newbooks.com.cn/de/laliluna/tutorial/library/ in the package de.laliluna.tutorial.library.The class BookList

Create a futher class BookList in the package de.laliluna.library. This class inlcudes the property books, which represent the list of books. Generate a getter- and seter-method for the property books and change the getter-method like the following.public class BookList {

// ------------------------- Properties ---------------------------
Collection books;

// ------------------------- Getter and Setter --------------------

/**
* @return collection of books
*/
public Collection getBooks(){

SimulateDB simulateDB = new SimulateDB();

/* Holt sich die Session auf dem Externen Context
*/
Map session = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();

/* Lies alle Bücher auf der simulierten Datenbank aus
*/
books = simulateDB.getAllBooks(session);

return books;
}

/**
* @param books The books to set.
*/
public void setBooks(Collection books) {
this.books = books;
}
}

Your package explorer will look like the picture below.

Action listener methodsTo provide that a user can add, edit or delete a book, we have to include the appropriate functionality. This functionality will be implemented in action listener methods / classes. If an event occur (ex.: a user clicks on a link) an action listener method / class will be called and processed.Open the class Book and add four methods , which process the following functionality.Initializise a bookEdit a bookSave a bookDelete a bookInitialize a book/**
* Initial the properties of the class with null
* @param event
*/
public void initBook(ActionEvent event){

/*
* init the book object
*/
this.setBook(new Book());
}

Edit a book/**
* Get the book to edit and assign it to the bean
*
* @param event
*/
public void selectBook(ActionEvent event){

SimulateDB simulateDB = new SimulateDB();

/*
* Get the session map of the external context
*/
Map session = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();

/*
* Find the UIParameter component by expression
*/
UIParameter component = (UIParameter) event.getComponent().findComponent("editId");

/*
* parse the value of the UIParameter component
*/
long id = Long.parseLong(component.getValue().toString());

/*
* get the book by id and set it in the local property
*/
this.setBook(simulateDB.loadBookById(id, session));
}

Save a book/**
* Add or update the book in the simulated database.
* If the book id is not set the book will be added
* otherwise the book will be updated
*
* @param event
*/
public void saveBook(ActionEvent event){

SimulateDB simulateDB = new SimulateDB();

/*
* Get the session map of the external context
*/
Map session = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();

/*
* Add or update the book in the simulated database
*/
simulateDB.saveToDB(this.getBook(), session);
}

Delete a book/**
* Delete a book in the simulated database
*
* @param event
*/
public void deleteBook(ActionEvent event){

SimulateDB simulateDB = new SimulateDB();

/*
* Get the session map of the external context
*/
Map session = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();

/*
* Find the UIParameter component by expression
*/
UIParameter component = (UIParameter) event.getComponent().findComponent("deleteId");

/*
* parse the value of the UIParameter component
*/
long id = Long.parseLong(component.getValue().toString());

/*
* delete the book by id
*/
simulateDB.deleteBookById(id, session);
}



The file faces-config.xmlThe faces-config.xml is the central configuration file of JavaServer faces. In this file you define the workflow of the application (on which action which site will be processed) , the managed bean classes by JSF and something more. The workflow of the library application looks like the following.

We define a navigation rule for this workflow.Open the file faces-config.xml and add the following configuration.



List of books
/listBooks.jsp

editBook
/editBook.jsp




Add or edit a book
/editBook.jsp

listBooks
/listBooks.jsp





Define a navigation rule/listBooks.jspDefine the jsp file for which the containing navigation rule is relevant.Define a navigation caseeditBookDefine a name for this navigation case/listBooks.jspRefers to the setted JSP FileAll parameters saved in the request will be losed when you set this tag.

If you want to access the bean classes in your JSP files, you have to register the bean classes in faces-config.xmlAdd the following source code.


Book bean

bookBean
de.laliluna.tutorial.library.Book
request




BookList Bean

bookListBean
de.laliluna.tutorial.library.BookList
session


Define a managed beanbookBeanDefine a name for the managed bean. This name is used in the JSP file.de.laliluna.tutorial.library.BookDefine the class which represent the bean.requestDefine in which scope the bean is saved.Create the JSP filesIn the first step we create a JSP file named index.jsp, which forwards the user to the list of books.index.jsp






In the second step we create the book overview.listBooks.jsp<%@ page language="java" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>




">

List of books





value="#{bookListBean.books}"
var="book"
border="1">
















value="#{book.available}" />





action="editBook"
actionListener="#{bookBean.selectBook}">

name="id"
value="#{book.id}" />






action="listBooks"
actionListener="#{bookBean.deleteBook}">

name="id"
value="#{book.id}" />




action="editBook"
actionListener="#{bookBean.initBook}">









<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>With directive taglib we include the JSF tag librariesRenders a view component. All others tags must be included within this tag.Renders a HTML form.Renders a HTML table. The tag is used to loop over a list of data like a for loop. The parameter value assign a list of data, in our case the list of books of the library. With the parameter var you define the variable used to access a element (a book) of the list within the tag (loop).




Renders a column with a column header. display the header.
print out a header label.
refers to the property author of the current element of the list. action="editBook"
actionListener="#{bookBean.selectBook}">Renders a HTML link, which submits the form. The parameter action define the navigation case, which is processed, after the form submits In our case the navigation case editBook, we have added befor in the faces-config.xml, will be processed. We assign the action listener method to the link with the parameter actionListener. After the user submit the form the method will be processed.

The last JSP file includes a form to add and edit a book.editBook.jsp<%@ page language="java" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>




">

Add / Edit a book









value="#{bookBean.author}">



value="#{bookBean.title}">



value="#{bookBean.available}" />



action="listBooks"
actionListener="#{bookBean.saveBook}" />





Renders a HTML hidden element. Value refers to the managed bean bookBean and its property id, which indicated in the faces-config.xml.Renders a HTML table with two columns. Renders a HTML text field. Value refers to the property author of our class Book. action="listBooks"
actionListener="#{bookBean.saveBook}" />Renders a HTML submit button with the value save and the action listBooks. The action listener method saveBook will be processed if the user submit the form.

Test the applicationStart the jboss and deploy the project as Packaged Archive.

Call the project now http://localhost:8080/LibraryWeb/

相关文章
· mysql5.0中文乱码解决方案
· mysql与jsp网页中文乱码问题的解决方案
· myeclipse 下开发jsf教程
· mysql的distinct group by sql语..
· mysql数据迁移tips,ora-00907: mis..
· mysql支持utf-8编码全攻略
· mysql查询优化系列讲座之调度和锁定
· myeclipse开发struts框架的hello wo..
· myeclipse中j2ee项目之间的组织结构
· mysql系统的发布、安装
热点文章
%>
· creating user controls
· 提高fastreplace速度 (fstrrep.pas)
· asc ii 完整码表及简介
· 自动生成拼音(汉字反查到拼音)
· sql2000无法安装的解决办法
· 浏览器集成教学 自定义浏览器
· vc++技术内幕(第四版)笔记(第7章)
· mysql5.0中文乱码解决方案
· sql server日期计算
· vc下利用ado连接access数据库
 淘宝旺旺:我要购书网上书店『图书目录
本购书中心地址: 杭州市延安路111号清波商厦南楼D座(总部) 上海市闸北区老沪太路网上购书中心(沪部),  邮编:310002
电子邮件:books@51goushu.com  经营许可证编号:沪ICP备06038574号
版权所有 2003-2008 © All Rights Reserved .购书网