 | 级别: 初级 宋 晟IBM 软件部、软件开发支持中心(SEC)
2003 年 12 月 01 日 本课程是作为 Enterprise JavaBeans 开发的入门课程。主要目的是让您掌握开始编写 EJB 所需的知识。本教程涵盖了 EJB 的基本知识,如何编写无状态 (stateless) 和有状态(stateful)会话 bean,以及 CMP 和 BMP 类型的实体 bean。我们将采用 EJB 开发的最佳工具 VisualAge for Java 企业版来完成开发和布署 EJB 到 WebSphere 应用服务器高级版中。本教程不是要详细地讲解服务器端 EJB 运行的内部细节。本教程的关注是在于给学生提供必要的信息来进行开发。至于 EJB 容器和服务器是如何实现的则与本教程无关。在完成本教程后,您应该具有足够的知识来进行 EJB 开发了。本教程没有讨论 EJB 的安全(与其容器的实现相关),简单地介绍了事务处理概念(我们将有专门的文章来解释 EJB 的事务处理概念)。我们也介绍 EJB 开发常用的一些设计思想。
本教程主要目的
Enterprise JavaBeans 概览
无状态会话 Bean (Stateless Session Bean)
客户端开发和测试
将 EJB 部署到 WebSphere 应用服务器
有状态会话 Bean (Stateful Session Bean)
序 列 化
实体 Bean 和 CMP
本教程主要目的
先决条件
The JSP in Listing 1 uses all of the major Jive objects to print the name of each thread in a
given forum. I'll discuss each of the objects and methods in more detail later, but the concepts shown here are
important for understanding how Jive works:
- Begin just about any Jive operation by creating a Jive authorization token. In this case, the anonymous
authorization token is created.
- Using this authorization token, get a concrete forum factory.
- From the forum factory, get a forum. If the permissions of the authorization token don't match the permissions set
on the forum, an exception is thrown and the user can't access the forum.
- Iterate through all the threads in the forum, printing the name of each one.
Listing 1: Printing out the names of all the threads in a forum
<%@ page import="java.util.Iterator,com.coolservlets.forum.*" %>
<%
//JSP to print out the names of all the threads in a forum.
//Get an anonymous authorization object.
Authorization auth = AuthorizationFactory.getAnonymousAuthorization();
ForumFactory factory = ForumFactory.getInstance(auth);
//Loading a forum object throws an Unauthorized exception if the
//the permissions set on the forum don't correspond to your access level.
try {
//Load the forum named myForum
Forum forum = factory.getForum("myForum");
//Get an iterator for all the threads in myForum
Iterator threads = forum.threads();
while (threads.hasNext() ) {
ForumThread thread = (ForumThread)threads.next();
%>
<%= thread.getName() %>
<%
}
}
catch (UnauthorizedException ue) {
System.err.println("You do not have permission to read this forum.");
}
%> |
Example 2: Customizing Jive
On lockerjock we already had users and our own user authentication scheme, so we couldn't use the Jive authentication
scheme without modification. We needed to merge the Jive user authentication with our own.
While I could have modified the SQL in the Jive code to look in our user table rather than Jive's, I decided it
would be simpler and require a lot less future maintenance to just use the Jive user table. So, I would simultaneously
maintain two sets of user tables. When a lockerjock user was created, I'd create a Jive user; when a user changed their
data, I'd update the Jive user data. To encapsulate all of the methods I'd need to work with Jive, I created a Jive
helper class.
Manipulating Jive users requires a Jive authorization object. While an authorization object can be created for any
user, only the one created from the Jive administration user (the user with ID number 1) has the authority to
manipulate other users. Listing 2 shows a helper method for creating a Jive authorization object.
Listing 2: Creating the administration authorization object
public static Authorization getLJJiveAdminAuthorization()
{
if (m_adminAuth != null)
{
return m_adminAuth;
}
else
{
try
{ m_adminAuth =
AuthorizationFactory.getAuthorization( ADMIN_ID, ADMIN_PWD );}
catch( UnauthorizedException ue ) {
System.out.println("Error in getLJJiveAdminAuthorization: "
+ ue.toString());
}
}
return m_adminAuth;
}
|
The code checks if an administration authorization object already exists, then creates one from the
AuthorizationFactory. This administration authorization token will be used extensively.
The next step is to create a helper method for creating a Jive user (see Listing 3). This
code obtains a concrete instance of ForumFactory by calling the getInstance() method with the
administration authorization token. The authorization token passed to the forum factory determines with what
permissions the rest of the objects in the system will be accessed; because the administration authorization token is
used, all Jive objects will be accessed with full permission.
The profile manager manages users and groups. In this case, it's used to create the user and to set user properties.
It returns the newly created user object.
Listing 3: Creating a Jive user
public User createForumUser(String name, String username,
String password, String email)
{
ProfileManager profileManager = null;
ForumFactory forumFactory = null;
User newUser = null;
forumFactory =
ForumFactory.getInstance(ForumHelper.getLJJiveAdminAuthorization());
try {
if (forumFactory != null)
{
profileManager = forumFactory.getProfileManager();
newUser = profileManager.createUser(username,password,email);
newUser.setName( name );
newUser.setEmailVisible(true);
newUser.setNameVisible(true);
}
}
catch( UserAlreadyExistsException uaee )
{
System.out.println("Error in createUser: " + uaee.toString());
System.out.println("User is: " + username);
}
catch( UnauthorizedException ue )
{
System.out.println("Error in createUser: " + ue.toString());
}
return newUser;
}
|
Listing 4 shows a helper method to get a Jive user. This code creates an authorization token
for the user that's being retrieved. It obtains the user ID from this authorization token, because this ID is what the
profile manager needs to retrieve the Jive user object. Note that this helper method obtains the profile manager using
the administration authorization token.
Listing 4: Getting a Jive user
public User getUser(String userName, String password)
{
ProfileManager profileManager = null;
ForumFactory forumFactory = null;
User user = null;
Authorization userAuth = getUserAuthorization(userName, password);
if (userAuth == null)
{
return null;
}
forumFactory =
ForumFactory.getInstance(ForumHelper.getLJJiveAdminAuthorization());
try {
if (forumFactory != null)
{
profileManager = forumFactory.getProfileManager();
user = profileManager.getUser( userAuth.getUserID() );
}
}
catch( UserNotFoundException unfe ) {
System.out.println("Error in getUser: " + unfe.toString());
}
return user;
}
|
Putting it all together
At lockerjock we use servlets to control the application, data beans to store the data, and JSP files to display the
data.
In our login servlet, I create a ForumHelper and call getUser(), passing it the name and
password gathered from the lockerjock user object. If the Jive user object returned is not null, it's put into the
session with the rest of our data beans, as shown here in Listing 5:
Listing 5: Adding the Jive user to the session
ForumHelper forumHelper = new ForumHelper();
User user = forumHelper.getUser(userBean.getScreenName(),
userBean.getPassword());
if (user != null)
{
session.putValue(LockerjockConstants.SESSION_JIVE_USER, user);
}
|
I used modified versions of three Jive JSP files: viewForum.jsp, viewMessage.jsp, and
post.jsp. I modified them because the default JSP files shipped with Jive allow non-users to post as a
special anonymous user. Because we require that all forum posters be lockerjock users, I modified the Jive JSP files to
check the session for the presence of both a Jive user and a lockerjock user. A user is allowed to interact with Jive
only when both are present. The code is shown in Listing 6:
Listing 6: Controlling access to the Jive forum JSP files
<%
User jiveUser
= (User)session.getValue(LockerjockConstants.LOCKERJOCK_JIVE_USER);
UserBean userBean
= (UserBean)session.getValue(LockerjockConstants.LOCKERJOCK_USER_BEAN);
if (jiveUser != null && userBean != null)
{
// do forum stuff, yadayadayada
}
%>
|
Unlike the default Jive JSP files, we control access to our forums based on what parts of lockerjock a user has
access to, not based on the user's forum permissions. For example, you can only view a trivia league forum if you are a
member of that trivia league; your Jive permissions are secondary to your lockerjock ones.
Therefore, we get the forum object based on our administration authorization, not the user's authorization. At this
point, the default Jive JSP files redirect to an error page if the user is not authorized to this particular forum, but
we never do the redirect because the administration user is always authorized. You would be redirected before hitting
the code in Listing 7 if you weren't authorized to this part of lockerjock. This code retrieves
the forum name from the forum object.
Listing 7: Getting the forum name
<%
String pForumID = request.getParameter("forum");
// get the forumID, create the forum object
int forumID =
((pForumID!=null&&!pForumID.equals(""))?(Integer.parseInt(pForumID)):-1);
ForumFactory forumFactory =
ForumHelper.getForumFactory(ForumHelper.getLJJiveAdminAuthorization());
Forum forum = null;
String forumName = null;
try {
if (forumFactory != null)
forum = forumFactory.getForum(forumID);
}
catch( UnauthorizedException ue )
{
//default Jive forum JSPs redirect to an error page if
//the forum factory doesn't have permission to get this forum
}
catch( ForumNotFoundException fnfe )
{
}
if (forum != null)
forumName = forum.getName();
%>
|
I can't resist including what I consider one of Jive's coolest features -- the ability to create a forum on the fly.
Listing 8 shows the surprisingly simple helper method to do so. It's just a matter of getting a
forum factory with the administration authorization token, then calling createForum() on that forum
factory. We use this method to create a league forum when a user creates a new trivia league.
Listing 8: Creating a forum on the fly
public Forum createForum(String name, String description)
{
ForumFactory forumFactory = null;
Forum newForum = null;
try
{
if( description == null )
description = "";
forumFactory =
ForumFactory.getInstance(ForumHelper.getLJJiveAdminAuthorization());
if (forumFactory != null)
newForum = forumFactory.createForum( name, description );
}
catch( UnauthorizedException ue ) {
System.out.println("Error in createForum: " + ue.toString());
}
catch( ForumAlreadyExistsException fae ) {
System.out.println("Error in createForum: " + fae.toString());
}
return newForum;
}
|
Summary
Jive gives the Web community an open-source, 100% Java forum software package. As I've shown, it can be used straight
up, or modified and extended to fit just about any need. The developers are amazingly friendly, helpful, and prolific.
Indeed, many new features, such as search, have been introduced since I began using Jive, and the only problem I have
is trying to find the time to learn about and deploy them. I encourage you to try Jive too!
参考资料
关于作者  | |  | 宋 晟 has authored this article |
对本文的评价
|  |