您的位置:首页 > 其它

一个简单的Ejb 3.0 实现

2007-11-15 09:24 513 查看
一、配置环境
a、mysql 5.0.2.2 mysql-noinstall-5.0.22-win32.zip 解压缩后放在c盘根目录下,目录名mysql。下载地址:http://download.mysql.cn/ 本例所放目录:C:/mysql
b、mysql所需的jdbc 包 mysql-connector-java-5.0.4-bin.jar 下载地址:http://dev.mysql.com/downloads/connector/j/5.0.html,你会发现这个下载以后比较大,解压缩取其中的mysql-connector-java-5.0.4-bin.jar 包。
c、eclipse 3.2.1 下载地址 http://www.eclipse.org/downloads/
d、jboss 4.0.5 下载地址 http://easynews.dl.sourceforge.net/sourceforge/jboss/jems-installer-1.2.0.GA.jar?download 下载后命令行下运行java -jar jems-installer-1.2.0.GA.jar 本例安装目录:E:/jboss-4.0.5
e、jdk 1.5.0 这个本例没有给出下载地址,相信读者不难下载到。 安装后,配置好J***A_HOME, 本例没给出具体怎么配置,是因为每个人下载的安装包安装后的目录和目录所包含的内容可能有不一致的地方,但一定要保证你能在你的自己上运行java程序。
2.构建工程
做完准备工作以后开始建工程。本例所建工程是EmployeeManager,是一个java 工程,记住不是web工程。虽然本例是web 应用,至于什么道理我想读者自己体会,本人观点不要什么都依靠过多的IDE,一旦脱离了IDE就无从下手。
3.构建数据库
先启动C:/mysql/bin 下的 mysqld-nt.exe ,要用数据库,你要先启动数据库。
然后进入命令行,从C:/mysql/bin 进入,输入mysql -u root –p 一般进入mysql 是没有密码的,依你自己的情况而定。
建库,create database empd default charset=utf8; 为什么不是简单的create database empd; 是因为构建应用实现国际化的需要。
进入数据库:use empd;
建表:
create table user (id int not null auto_increment,
name char(10) not null,
password char(32) not null,
description char(100),
primary key(id)) engine=innodb;
4.本例所用jar 包,放在eclipse 所建工程下的lib文件夹中
1、ejb3-persistence.jar(以下两个是在jboss中拿出来的)
2、jboss-ejb3x.jar
3、servlet-api.jar(这个好象是我在tomact中拿出来的)
4、struts.jar(以下三个jar包是在struts 所包含的jar中)
5、commons-digester.jar
6、commons-logging.jar
5、
本例所有的实现是修改了eclipse的设置的。
Window->Preferences->Java->Build Path
选中Folders,修改output folder name的值为classes。然后建的工程,这样呢每新建或修改一个类,在classes目录下就会自动编译所生成的类文件。

至此本例所进行工作基本准备完毕。


二:构建po
我们大致说一下po在EJB 3.0 中的说法,它等于EJB 2 中的实体bean。在EJB 3.0中抛弃了这种叫法,因为它们的实现和表现形式已经有了太大的改变。我们这里姑且称它为po.
另外大致要说的一点是ejb 3.0 只能在jdk 1.5 以上的版本下运行。





/**//*


*


* Copyright 2007-2008 neil


*


*/


package com.qy.ejb.po;




import java.io.Serializable;




import javax.persistence.Column;


import javax.persistence.Entity;


import javax.persistence.GeneratedValue;


import javax.persistence.Id;


import javax.persistence.Table;






/** *//**


*


* @author neil


* @version 1.0


*


*/


@SuppressWarnings("serial")


@Entity


@Table(name = "user")




public class User implements Serializable ...{


private Integer id;




private String name;




private String password;




private String description;




@Id


@GeneratedValue




public Integer getId() ...{


return id;


}






public void setId(Integer id) ...{


this.id = id;


}




@Column(name = "name", nullable = false)




public String getName() ...{


return name;


}






public void setName(String name) ...{


this.name = name;


}




@Column(name = "password", nullable = false)




public String getPassword() ...{


return password;


}






public void setPassword(String password) ...{


this.password = password;


}




@Column(name = "description", nullable = true, length = 100)




public String getDescription() ...{


return description;


}






public void setDescription(String description) ...{


this.description = description;


}


}




我并不想讲它的大致意思,如果你对hibernate有了解的话,你大致会看明白,如果你对hibernate 不了解的话你可以查google.

三: 构建接口








/**//*


*


* Copyright 2007-2008 neil


*


*/


package com.qy.ejb.dao;




import com.qy.ejb.po.User;






/** *//**


*


* @author neil


* @version 1.0


*


*/




public interface UserDao ...{







/** *//**


* get single user


*


* @param name


* @param password


* @return User


* @throws Exception


*/


public User getUser(String name, String password) throws Exception;




}



五:构建无状态session





/**//*


*


* Copyright 2007-2008 neil


*


*/


package com.qy.ejb.session;




import java.util.List;




import javax.ejb.Remote;


import javax.ejb.Stateless;


import javax.persistence.EntityManager;


import javax.persistence.PersistenceContext;


import javax.persistence.Query;




import com.qy.ejb.dao.UserDao;


import com.qy.ejb.po.User;






/** *//**


*


* @author neil


* @version 1.0


*


*/


@Stateless




@Remote( ...{ UserDao.class })




public class UserDaoBean implements UserDao ...{




@PersistenceContext


protected EntityManager em;// the manager of entity






public User getUser(String name, String password) throws Exception ...{




// define query sentence


StringBuffer hql = new StringBuffer();


hql.append("from User u where u.name='" + name + "'");


hql.append(" and u.password='" + password + "'");




// create the query


Query query = em.createQuery(hql.toString());


List queryList = query.getResultList();




// if the result is null




if (queryList.size()==0) ...{


return null;


}




// if the user's length greater 1




if (queryList.size() > 1) ...{


throw new Exception(


" Cann't exists user who the same name and the same password");


}




// return single user


return (User) queryList.get(0);


}




}





至此关于ejb 3.0中 的核心代码已经展示完毕,但仍然不可以运行,因为我们没有配置文件。从上面的代码你会发现一个问题,我没有过多的解释,没有用中文,我想如果你对程序喜爱 的话,我想你大致明白什么道理,没有解释是本文篇幅已经有些长,如果解释的话是在代码中解释还是代码外解释,我没定,但代码中解释是用英文还是中文也没法 做。不想破坏代码的简单性。

六:构建访问ejb的公共类





1.Constants




/**//*


*


* Copyright 2007-2008 neil


*


*/


package com.qy.beans;




/** *//**


*


* @author neil


* @version 1.0


*


*/




public class Constants ...{


public static final String USER_DAO_JNDI = "UserDaoBean/remote";




}


2.LookJndiFactory




/**//*


*


* Copyright 2007-2008 neil


*


*/


package com.qy.db;




import java.util.Properties;




import javax.naming.InitialContext;


import javax.naming.NamingException;






/** *//**


*


* @author neil


* @version 1.0


*


*/




public class LookJndiFactory ...{




public static Object getDaoByJndiName(String jndiName) throws NamingException ...{


Properties pros = new Properties();


pros.setProperty("java.naming.factory.initial",


"org.jnp.interfaces.NamingContextFactory");


pros.setProperty("java.naming.provider.url", "localhost:1099");


pros.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming");




InitialContext ctx = new InitialContext(pros);




return ctx.lookup(jndiName);


}




}




七:构建struts 资源
下面的Resourece文件只有一个,如果用中文或其它语言的话还需要其它的,Resource文件,本例就不再列出,有兴趣的朋友可以自己实现一下。
1.MessageResources.properties

# login.jsp
login.jsp.title=Login
login.jsp.content=Login on
login.jsp.loginName.displayname=Login Name
login.jsp.password.displayname=Password

error.login.jsp.loginName.required=Please input your login name
error.login.jsp.password.required=Please input your password
error.login.jsp.loginName.exists=user not exists or password is incorrect
error.login.jsp.login.failuer=login failure

#welcome.jsp
welcome.jsp.title=welcome
welcome.jsp.content=hello

2. LoginForm





/**//*


*


* Copyright 2007-2008 neil


*


*/


package com.qy.struts.form;




import javax.servlet.http.HttpServletRequest;




import org.apache.struts.action.ActionErrors;


import org.apache.struts.action.ActionForm;


import org.apache.struts.action.ActionMapping;


import org.apache.struts.action.ActionMessage;










/** *//**


*


* @author neil


* @version 1.0


*


*/


@SuppressWarnings("serial")




public final class LoginForm extends ActionForm...{





String loginName;


String password;







public String getLoginName() ...{


return loginName;


}






public void setLoginName(String loginName) ...{


this.loginName = loginName;


}






public String getPassword() ...{


return password;


}






public void setPassword(String password) ...{


this.password = password;


}






/** *//**


* Reset all properties to their default values.


*


* @param mapping The mapping used to select this instance


* @param request The servlet request we are processing


*/




public void reset(ActionMapping mapping, HttpServletRequest request) ...{


loginName = null;


password = null;


}







/** *//**


* Reset all properties to their default values.


*


* @param mapping The mapping used to select this instance


* @param request The servlet request we are processing


* @return errors


*/


public ActionErrors validate(




ActionMapping mapping, HttpServletRequest request ) ...{


ActionErrors errors = new ActionErrors();







if( getLoginName() == null || getLoginName().length() < 1 ) ...{


errors.add("loginName",new ActionMessage("error.login.jsp.required"));


}




if( getPassword() == null || getPassword().length() < 1 ) ...{


errors.add("password",new ActionMessage("error.login.jsp.password.required"));


}






return errors;


}




}




3. LoginAction





/**//*


*


* Copyright 2007-2008 neil


*


*/


package com.qy.struts.action;




import javax.servlet.http.HttpServletRequest;


import javax.servlet.http.HttpServletResponse;


import javax.servlet.http.HttpSession;




import org.apache.commons.logging.Log;


import org.apache.commons.logging.LogFactory;


import org.apache.struts.action.Action;


import org.apache.struts.action.ActionForm;


import org.apache.struts.action.ActionForward;


import org.apache.struts.action.ActionMapping;


import org.apache.struts.action.ActionMessage;


import org.apache.struts.action.ActionMessages;


import org.omg.CORBA.portable.ApplicationException;




import com.qy.beans.Constants;


import com.qy.db.LookJndiFactory;


import com.qy.ejb.dao.UserDao;


import com.qy.ejb.po.User;


import com.qy.struts.form.LoginForm;




/** *//**


*


* @author neil


* @version 1.0


*


*/




public class LoginAction extends Action ...{




/** *//**


* Commons Logging instance.


*/


private Log log = LogFactory.getFactory().getInstance(


this.getClass().getName());




public ActionForward execute(ActionMapping mapping, ActionForm form,


HttpServletRequest request, HttpServletResponse response)




throws Exception ...{




LoginForm loginForm = (LoginForm) form;


String userName = loginForm.getLoginName();


String password = loginForm.getPassword();




UserDao userDao = (UserDao) LookJndiFactory


.getDaoByJndiName(Constants.USER_DAO_JNDI);




ActionMessages messages = new ActionMessages();






try ...{


User user = userDao.getUser(userName, password);




if (user == null) ...{


messages.add("login", new ActionMessage(


"error.login.jsp.loginName.exists"));


}




} catch (ApplicationException ape) ...{


messages.add("login", new ActionMessage(


"error.login.jsp.login.failuer"));


}




HttpSession session = request.getSession();




session.setAttribute("loginName", loginForm.getLoginName());




this.saveErrors(request, messages);




if (messages.size() != 0) ...{


log.error("login failure!");


return mapping.getInputForward();


}


log.info("login success!");


return mapping.findForward("success");


}




}



4. SetCharacterEncodingFilter




/**//*


*


* Copyright 2007-2008 neil


*


*/


package com.qy.webservice.filter;




import java.io.IOException;




import javax.servlet.Filter;


import javax.servlet.FilterChain;


import javax.servlet.FilterConfig;


import javax.servlet.ServletException;


import javax.servlet.ServletRequest;


import javax.servlet.ServletResponse;






/** *//**


*


* @author neil


* @version 1.0


*


*/




public class SetCharacterEncodingFilter implements Filter ...{






public void init(FilterConfig filterConfig) throws ServletException ...{




}




public void doFilter(ServletRequest req, ServletResponse res,




FilterChain filterChain) throws IOException, ServletException ...{




req.setCharacterEncoding("UTF-8");




// transfer to next filter


filterChain.doFilter(req, res);




}






public void destroy() ...{




}




}



5. struts-config 文件



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


<!DOCTYPE struts-config PUBLIC


"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"


"http://struts.apache.org/dtds/struts-config_1_2.dtd">




<struts-config>





<!-- ======== Form Bean Definitions =================================== -->


<form-beans>


<form-bean name="loginForm" type="com.qy.struts.form.LoginForm"/>


</form-beans>




<!-- ========== Action Mapping Definitions ============================== -->


<action-mappings>


<!-- Say Hello! -->


<action path = "/login"


type = "com.qy.struts.action.LoginAction"


name = "loginForm"


scope = "request"


validate = "true"


input = "/login.jsp"


>


<forward name="success" path="/welcome.jsp" redirect="true" />


</action>


</action-mappings>







<!-- ========== Message Resources Definitions =========================== -->




<message-resources parameter="MessageResources"/>


</struts-config>




6.web.xml




<?xml version="1.0" encoding="iso-8859-1"?>


<!DOCTYPE web-app


PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"


"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">


<web-app>


<display-name>Struts Sample Application</display-name>





<!-- Standard Action Servlet Configuration -->


<servlet>


<servlet-name>action</servlet-name>


<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>


<init-param>


<param-name>config</param-name>


<param-value>/WEB-INF/struts-config.xml</param-value>


</init-param>


<load-on-startup>2</load-on-startup>


</servlet>




<!-- Standard Action Servlet Mapping -->


<servlet-mapping>


<servlet-name>action</servlet-name>


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


</servlet-mapping>




<filter>


<filter-name>Set Character Encoding</filter-name>


<filter-class>com.qy.filter.SetCharacterEncodingFilter</filter-class>


</filter>




<!-- Filter Mapping -->


<filter-mapping>


<filter-name>Set Character Encoding</filter-name>


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


</filter-mapping>





<!-- The Usual Welcome File List -->


<welcome-file-list>


<welcome-file>login.jsp</welcome-file>


</welcome-file-list>





<!-- Struts Tag Library Descriptors -->


<taglib>


<taglib-uri>/tags/struts-bean</taglib-uri>


<taglib-location>/WEB-INF/tld/struts-bean.tld</taglib-location>


</taglib>


<taglib>


<taglib-uri>/tags/struts-html</taglib-uri>


<taglib-location>/WEB-INF/tld/struts-html.tld</taglib-location>


</taglib>


<taglib>


<taglib-uri>/tags/struts-logic</taglib-uri>


<taglib-location>/WEB-INF/tld/struts-logic.tld</taglib-location>


</taglib>


<taglib>


<taglib-uri>/tags/struts-nested</taglib-uri>


<taglib-location>/WEB-INF/tld/struts-nested.tld</taglib-location>


</taglib>


</web-app>





八:编写jsp


1.login.jsp




<%...@ taglib uri="/tags/struts-bean" prefix="bean" %>




<%...@ taglib uri="/tags/struts-html" prefix="html" %>




<%...@ taglib uri="/tags/struts-logic" prefix="logic" %>




<%...@ page language="java" contentType="text/html; charset=utf-8" %>


<html:html locale = "true">




<head><title><bean:message key="login.jsp.title"/></title>


</head>


<h2><bean:message key="login.jsp.content"/></h2>


<html:errors/><p>




<html:form action="/login">


<TABLE border="0">


<TBODY style="font-size: 13px;" leftMargin=10 topMargin=0 marginheight="0"


marginwidth="0">


<TR>


<TH><bean:message key="login.jsp.loginName.displayname"/></TH>


<TD><html:text name="loginForm" property="loginName" /></TD>


</TR>


<TR>


<TH><bean:message key="login.jsp.password.displayname"/></TH>


<TD><html:password name="loginForm" property="password" /></TD>


</TR>


<TR>


<TD><html:submit property="submit" value="Submit" /></TD>


<TD><html:reset /></TD>


</TR>


</TBODY>


</TABLE>




</html:form>


</BODY>


</html:html>


2. welcome.jsp




<%...@ taglib uri="/tags/struts-bean" prefix="bean" %>




<%...@ taglib uri="/tags/struts-html" prefix="html" %>




<%...@ taglib uri="/tags/struts-logic" prefix="logic" %>


<html:html locale="true">


<head>


<title><bean:message key="welcome.jsp.title"/></title>


<html:base/>


</head>


<body bgcolor="white"><p>




<logic:present name="loginName">


<h2>


<bean:message key="welcome.jsp.content"/>


<bean:write name="loginName" />


</h2>


</logic:present>


</html:html>



九:build.xml


<project name="empd" default="help" basedir=".">




<property name="app.home" value="." />


<property name="app.name" value="empd" />


<property name="javadoc.pkg.top" value="com" />




<property name="src.home" value="${app.home}/src"/>


<property name="lib.home" value="${app.home}/lib"/>


<property name="classes.home" value="${app.home}/classes"/>


<property name="deploy.home" value="${app.home}/deploy"/>


<property name="doc.home" value="${app.home}/doc"/>


<property name="web.home" value="${app.home}/web"/>




<property name="build.home" value="${app.home}/build"/>


<property name="build.classes" value="${build.home}/WEB-INF/classes"/>


<property name="build.lib" value="${build.home}/WEB-INF/lib"/>





<property name="jboss.deploy.home" value="E:jboss-4.0.5serverdefaultdeploy"/>




<!-- ==================== Compilation Classpath =========================== -->




<!--


This section creates the classpath for compilation.


-->




<path id="compile.classpath">




<!-- The object files for this application -->


<pathelement location="${classes.home}"/>




<!-- The lib files for this application -->


<fileset dir="${lib.home}">


<include name="*.jar"/>


<include name="*.zip"/>


</fileset>




</path>






<!-- ==================== Build Targets below here========================= -->






<!-- ==================== "help" Target =================================== -->




<!--


This is the default ant target executed if no target is specified.


This helps avoid users just typing 'ant' and running a


default target that may not do what they are anticipating...


-->




<target name="help" >


<echo message="Please specify a target! [usage: ant <targetname>]" />


<echo message="Here is a list of possible targets: "/>


<echo message=" clean-all.....Delete build dir, all .class and war files"/>


<echo message=" prepare.......Creates directories if required" />


<echo message=" compile.......Compiles source files" />


<echo message=" build.........Build war file from .class and jar file other files"/>


<echo message=" deploy........Copy war file to the webapps directory" />


<echo message=" javadoc.......Generates javadoc for this application" />


</target>




<!-- ==================== "clean-all" Target ============================== -->




<!--


This target should clean up any traces of the application


so that if you run a new build directly after cleaning, all


files will be replaced with what's current in source control


-->




<target name="clean-all" >


<delete dir="${build.home}"/>


<delete dir="${deploy.home}"/>




<!-- delete the javadoc -->


<delete dir="${doc.home}"/>




</target>




<!-- ==================== "prepare" Target ================================ -->




<!--


This target is executed prior to any of the later targets


to make sure the directories exist. It only creates them


if they need to be created....


Other, similar, preparation steps can be placed here.


-->




<target name="prepare">




<mkdir dir="${deploy.home}"/>




<mkdir dir="${doc.home}"/>


<mkdir dir="${doc.home}/api"/>




<mkdir dir="${build.home}"/>


<mkdir dir="${build.home}/WEB-INF" />


<mkdir dir="${build.home}/WEB-INF/classes" />


<mkdir dir="${build.home}/WEB-INF/lib" />




</target>




<!-- ==================== "compile" Target ================================ -->




<!--


This only compiles java files that are newer


than their corresponding .class files.


-->




<target name="compile" depends="prepare" >


<javac srcdir="${src.home}" destdir="${classes.home}" debug="yes" >


<classpath refid="compile.classpath"/>


</javac>


</target>




<!-- ==================== "build" Target ================================== -->




<!--


This target builds the war file for the application


by first building the directory structure of the


application in ${build.home} and then creating the


war file using the ant <war> task


-->




<target name="build" depends="compile" >




<!-- Copy all the webapp content (jsp's, html, tld's, xml, etc. -->


<!-- Note that this also copies the META-INF directory -->


<copy todir="${build.home}">


<fileset dir="${web.home}"/>


</copy>




<!-- Now, copy all the Java class files -->


<copy todir="${build.home}/WEB-INF/classes">


<fileset dir="${classes.home}">


<exclude name="com/qy/ejb/**"/>


</fileset>


</copy>




<!-- Now, copy all the properties files, etc that go on the classpath -->


<copy todir="${build.home}/WEB-INF/classes">


<fileset dir="${src.home}">


<include name="**/*.properties" />


<include name="**/*.prop" />


</fileset>


</copy>




<!-- Now, copy all the jar files we need -->


<copy todir="${build.home}/WEB-INF/lib">


<fileset dir="${lib.home}" />


</copy>




<!-- Create the <war> file -->


<jar jarfile="${deploy.home}/${app.name}.war"


basedir="${build.home}"/>





<jar jarfile="${deploy.home}/${app.name}Ejb.jar">


<fileset dir="${classes.home}">


<include name="com/qy/ejb/**"/>


</fileset>


<metainf dir="${app.home}/META-INF">


<include name="persistence.xml"/>


</metainf>


</jar>




</target>







<!-- ==================== "deploy" Target ================================= -->




<!--


This target simply copies the war file from the deploy


directory into the Tomcat webapp directory.


-->




<target name="deploy" depends="build" >




<!-- Copy the contents of the build directory -->


<copy todir="${jboss.deploy.home}" file="${deploy.home}/${app.name}.war" />


<copy todir="${jboss.deploy.home}" file="${deploy.home}/${app.name}Ejb.jar" />




</target>




<!-- ==================== "doc" Target ==================================== -->




<!--


This task creates javadoc. It is dependent upon only the


'compile' target so it is not executed in a normal build.


As a result, the target needs to be run on its own.


-->




<target name="javadoc" depends="compile">


<javadoc sourcepath = "${src.home}"


destdir = "${doc.home}/api"


packagenames = "${javadoc.pkg.top}.*"/>


</target>




</project>



前几个target能运行,但最后一个有点问题,要把eclipse lib 下的几个jar包加入到classpath 中去,另外也别忘了加入运行javadoc的两个工具jar包,dt.jar,tools.jar,这两个jar包在java 安装目录里不难找到。

十:数据库配置文件
1、mysql-connector-java-5.0.4-bin.jar
放到:E:/jboss-4.0.5/server/default/lib 下
2、Mysql-ds.xml



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


<datasources>


<local-tx-datasource>


<jndi-name>empdEjb</jndi-name>


<connection-url>jdbc:mysql://localhost:3306/empd?useUnicode=true&characterEncoding=UTF-8</connection-url>


<driver-class>com.mysql.jdbc.Driver</driver-class>


<user-name>root</user-name>


<password></password>


<exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>


<metadata>mySQL</metadata>


</local-tx-datasource>


</datasources>


该文件放到 E:/jboss-4.0.5/server/default/deploy 下,除了上面两个文件需要自己放置目录外,其余的文件就按ant打包以后的放置。

3、persistence.xml


<persistence>


<persistence-unit name="empdEjb">


<jta-data-source>java:/empdEjb</jta-data-source>


<properties>


<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />


</properties>


</persistence-unit>


</persistence>






发布了好几天,忘了数据库的配置没写,汗颜阿:)



十一:运行该程序
1,C:/mysql/bin open mysqld-nt.exe
2,E:/jboss-4.0.5/bin open run.bat
3,http://localhost:8080/empd
别忘了在数据库表中加入数据。

注:以上内容来自网络,
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: