EJB 3.0+beehive Developing customer feedback system

Source: Internet
Author: User
Tags filter define final mysql string java web jboss jboss server

Design Objectives

Customer feedback system as a company and customer Exchange platform, almost all enterprises to use, recently, the company let me responsible for customer feedback system development. Because of the business needs of the company and the foreign customers, the system must realize the switching of the languages of the Chinese, English and Japanese (internationalization requirements). After receiving the task, I decided to try to use the current open source community more popular Apache Beehive (Honeycomb) and the next generation of ejb,ejb3.0 technology to implement this system.


Development environment


Select platform, development tools


To support EJB3.0 and beehive, we chose the JBoss4.0.3 application Server as the operating platform, and it is the only application server that currently provides the EJB3.0 container.

Download and install JBoss4.0.3 servers and EJB3.0 containers Http://www.jboss.com/downloads/index

The database is selected MySql5.0, because we do not encode a specific database, so the database porting is also very convenient.

Download MySql5.0 http://dev.mysql.com/downloads/mysql/5.0.html

Because to develop EJB3.0 and beehive applications, choose Ecllipse this IDE,

Download Ecllipse SDK 3.1 http://eclipse.org/downloads/

To support EJB3.0 development, download the JBoss ecllipse ide this ecllipse plugin
Http://www.jboss.com/products/jbosside/downloads

Pollinate is another Ecllipse plug-in that is currently the only IDE to support Beehive Project development, although it is far less powerful than WebLogic Workshop, but with a certain BEA Workshop development experience, Using pollinate does not have much of a problem.

Download and install the pollinate plugin http://www.eclipse.org/pollinate/

Beehive Brief Introduction

Before system design, it is very important to choose a good system framework. Beehive is an open source project for APAHCE. Since May 2004, BEA Systems has announced the opening of a series of core runtime frameworks (Runtime framework) in WebLogic platform and its contribution to the Apache project, This beehive framework has been one of the focus of the open source community.

The goal of the Beehive is to make Java-EE development simpler, an extensible java-based application framework with an integrated metadata-driven programming model for Web services, Web applications, and resource access. The framework utilizes the latest innovations of JDK1.5, especially JSR175 metadata annotations, to reduce the coding of developers and thereby improve development efficiency. Currently, the Beehive Project includes Java controls, Netui,java Web service metadata, to help Java developers develop component-based and standard Java applications.

EJB3.0 Brief Introduction

In the customer feedback system, try to use the newest EJB3.0 to realize the development of the persistence layer. As we all know, because of the complexity of EJB, its performance in the Java EE architecture has not been very good. EJB is probably the only component in the Java EE architecture that has not honoured its ability to simply develop and increase productivity. The EJB3.0 specification makes efforts in this regard to mitigate the complexity of its development. The EJB3.0 cancels or minimizes the implementation of the callback methods that were previously required, and reduces the complexity of the entity bean and the O/R mapping model, which greatly reduces the developer's effort to perform low-level development.

Two important improvements in EJB3.0 are: Using the metadata annotation feature in Java5 and the hibernate O/R mapping model, in EJB3.0, any type of enterprise bean is simply a simple Java object (POJO) with appropriate annotations. Annotations can be used to define a bean's business interface, O/R mapping information, resource reference information, and the effect is the same as defining a deployment descriptor and interface in EJB2.1. Deploying descriptors in EJB3.0 is no longer necessary; The home interface is gone and you don't have to implement a business interface (the container can do that for you).

EJB3.0 the configuration

JBoss EJB3.0 is based on Hibernate 3.0.   To configure the data source, entity beans need to create hibernate. Properties configuration file. There is a default hibernate configuration file Ejb3.deployer/meta-inf/hibernate.properties under the EJB3.0 deployment package. Modify this file so that the entity bean uses the MySQL data source, and the modified configuration file is as follows:

Hibernate.transaction.manager_lookup_class=org.hibernate.transaction.jbosstransactionmanagerlookup
Hibernate.connection.release_mode=after_statement
Hibernate.transaction.flush_before_completion=false
Hibernate.transaction.auto_close_session=false
Hibernate.query.factory_class=org.hibernate.hql.ast.astquerytranslatorfactory

After Sessionfactory is created, the automatic output schema creation statement to the database, using update to create and update the original schema without affecting the data in the original database

Hibernate.hbm2ddl.auto=update
#hibernate. hbm2ddl.auto=create
Hibernate.show_sql =true
Hibernate.cache.provider_class=org.hibernate.cache.hashtablecacheprovider
# Clustered Cache with Treecache
#hibernate. Cache.provider_class=org.jboss.ejb3.entity.treecacheproviderhook
#hibernate. Treecache.mbean.object_name=jboss.cache:service=ejb3entitytreecache

Modify the Blue Font section to change its default data source to Mysqlds (JBoss's data source configuration reference JBoss related documentation).

Hibernate.connection.datasource=java:/mysqlds
Hibernate.dialect=org.hibernate.dialect.mysqldialect

Hibernate.jndi.java.naming.factory.initial=org.jnp.interfaces.namingcontextfactory
Hibernate.jndi.java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces

Persistence Layer Design

Create a Ejb3.0 Project


First use the JBoss IDE, create a EJB3.0 project, select New->project->ejb3.0 Project,

Select the Next button and enter the name of the project in program name: Feedback, click Next,

Then select JBoss4.0.3 Server as the default for the project. Click the Finish button, which generates a EJB3.0 project where the Jndi.property file in the root directory indicates some configuration of the JBoss server name service.

Data Persistence layer

Use EJB3.0 entity beans to implement the system's data persistence layer. The entity bean for EJB3.0 is also an annotated simple Java object (POJO). Once it is accessed by Entitymanager it becomes a persistent object and becomes part of the persistence context. A persistence context is loosely coupled with a transaction context; Strictly speaking, it implicitly coexists with a transaction session. Developing entity beans in EJB3.0 is very simple and can be programmed like a typical Java bean, with a small number of annotations to define entity relationships, O/R mappings, etc. In EJB2.1 these are done through the developer's own design pattern or other technology (for example, the self-growth primary key strategy). The following defines an item entity bean that represents a customer-initiated topic:

//declares that the class is an entity Bean object that represents a client-initiated topic public class Item implements serializable{private static final long Serialversionuid = -3318132295818643572l; private int itemId;  Private Collection 
  
    feedBacks;  private user user;  ...//Here defines a one-to-one relationship between entity beans (Optional = false) (name = "UserId", unique = false, Nullable = false) public User GetUser () { return user; //Declare entity Bean's primary key and Growth policy (Generate=generatortype.auto) (name= "itemId") public int getitemid () {return itemId;}//DECLARE subject entity A one-to-many relationship with the feedback entity, and the development of cascading and fetching methods (cascade=cascadetype.all,fetch=fetchtype.lazy,mappedby= "item") (Name= "itemId") public Collection 
   
     getfeedbacks () {return feedBacks.} public void Setfeedbacks (Collection 
    
      fe Edbacks) {this.feedbacks = FeedBacks;} 
     
   
 
  

In the example above, the blue part is the metadata annotation feature of the JDK1.5, and if it is named that the class is a EJB3.0 entity bean, then a EJB3.0 entity bean is generated at the time of deployment, The EJB3.0 container of JBoss identifies EJB3.0 entity beans and maps them to the corresponding database tables. Please refer to EJB3.0 related technical documentation.

Business Logic Layer

Using a stateless session bean in the customer feedback system to implement the business logic layer of the system, in the EJB3.0 specification, writing a stateless reply bean (SLSB) requires only a simple Java file and a comment on the class layer. This bean can extend the Javax.ejb.SessionBean interface, but these are not required. A slsb no longer needs a home interface, and no EJB needs it anymore. A bean class can implement a business interface or do not implement it. If no business interface is implemented, the business interface is generated by any public method. If only a few business methods are exposed to the business interface, these methods can use annotations. By default, all generated interfaces are local (native) interfaces, and you can use annotations to declare this interface as a remote (remote) interface.

It is convenient to create a session bean using the JBoss IDE, select the New->others->ejb3.0->session bean, open the Session Bean Creation wizard, as shown in the figure

Select stateless in the session Bean type to indicate that you want to create a stateless bean. In Bean name, enter the name of the session bean that you want to create, where we create a stateless conversation bean:feedbacks that handles customer feedback. After clicking the Finish button, the session Bean's interface file and implementation file are generated: FeedBacks, the business interface of the stateless session bean:

Public interface feedbacks{Public  FeedBack addfeedback (int itemid,string title,string content,int userId, Collection feedbackfiles);p ublic void deletefeedback (int feedbackid);.}

In the business interface of the session bean, add the interface of the session bean. The remote interface in which the bean is declared to implement the session bean

Implementation of stateless session Bean:

Public  class Feedbacksbean implements FeedBacks {public FeedBack addfeedback (int itemid,string title,string content , int userid,collection feedbackfiles) {//Add implementation code here ...} ......}
Completed in the implementation.
Complete all business logic encodings in the implementation. Where the bean is declared to be a stateless session bean.

WEB Layer Design

Create a beehive Project


First create a beehive project, select New->project->beehive Project, and open the Beehive Project Creation Wizard, as shown in the figure:

Enter in name, applied by: Feedbackapp. The next step is to select the application template to define. After you complete the steps above, a beehive project is generated, and the newly generated project has added all the Beehive resources you need. You can then develop page flows and Java controls.

Use Java Control in the Beehive used in Ejb3.0

Beehive provides EJB control for obtaining an EJB instance, but does not support EJB3.0, so consider using the Java controls technique in the customer feedback system to write an EJB instance with the Jndi name of the EJB3.0 instance.

The Java control architecture is a lightweight component architecture based on JavaBeans that exposes a simple and consistent client model for accessing various Java EE resource types. The framework provides a number of functions, including: Configuration based on JSR-175 metadata and external configuration data, automatic resource management, context services, and an extensible design model for creating new control types.

To develop the Java control, first introduce the EJB 3.0 project into the current Beehive project, which you can set up in Project->property->build path. Then write a Java control called Ejbfinder to achieve the acquisition of Ejb3.0 real columns.

The development of Java control is divided into two steps, first defining the Java control interface as follows:

Indicates that the interface is part of the interface of the control Ejbfinder public interface Ejbfinder {public    Object GETEJB (String ejbname); And then define the implementation part of Java control,
Indicates that the class is the implementation part of the control Ejbfinder public class Ejbfinderimpl implements Ejbfinder, java.io.Serializable { / Implement the method in the business interface public Object GETEJB (String ejbname) { try{context = new InitialContext (); Gets the ejb3.0 instance based on the Jndi name and returns the instance return (Context.lookup (ejbname)); } catch (Namingexception e) { e.printstacktrace (); return null; } }}


A Java control is a reusable component that can be used anywhere in a platform application. The above Java control is used for the Jndi name of the EJB instance, looking in the entire context, and returning the EJB instance. We can then use this Java control in the Pageflow (page flow) in the Beehive Web application to get the ejb3.0 instance:

Add the following code in the Pageflow page flow control file that needs to use the EJB3.0 instance to declare that the control is used

. Apache.beehive.controls.api.bean.Control ()
protected Ejbfinder _ejbfindercontrol;

Then we can use this Ejbfinder control to get the desired ejb3.0 instance.

Feedbacksbean= (FeedBacks) _EJBFINDERCONTROL.GETEJB (FeedBacks.class.getName ());

Because the view of the control is not yet available in pollinate, in order to illustrate the relationship between Java controls and Pageflow (page flow), you can refer to the reference view in the above table of the BEA Workshop, in which the main body is a pageflow (page flow), and the right user is a Java control named users that is used in the page stream.

Developing Netui page Flow

Netui page flow, a Web application framework based on Apache Sruts, has a single file programming model that is easy to use and based on JSR-175 metadata. This page flow builds on the core struts separation of the model/view/controller elements, such as automatic state management and Best-of-breed integration with controls, XMLBeans and Javaserverfaces.

Page flow uses a specially designed annotation and method to control the behavior of a WEB application Java class called the Controller (Controller) class. In the directory that contains the controller class, the Java Server page (JSP) used in the page flow is also included. A JSP is to be part of the page flow, and it must be in the page flow directory. Special tags used by JSP files help bind to data and business logic operations. The code implemented by the action method in the controller file can cause site navigation, data delivery, or call back-end business logic through the control. Furthermore, the business logic in the controller class is independent of the representation code defined in the JSP file, which makes the development and maintenance of the whole Web application more clear and efficient.

Create a page stream in pollinate and select New->other->page Flow Wizard as shown in the figure

Click Next to enter the name of the page flow in the pop-up box. Here we create a process customer feedback page flow topics, click Complete, then generate a basic page flow, open page flow in the folder, double-click the page flow control file Controller.java, click on the Flow page to open the page stream Design view, as shown below

It consists of a begin action and a index.jsp page. On the left is the design component, including Action,page, adding the required pages and action to the page stream.

To add action handling code in the page flow control file:

//page flow control file that declares the target of the flow. Controller (Multiparthandler = Jpf.MultipartHandler.memory, forwards = {. Forward (name = "Showtopics", Path = "topiclist.jsp"),. Forward (name = "Addtopicaccessories", Path = "accessories.jsp"),. Forward (name = "Showlinkmen", Path = "linkmanlist.jsp"),. Forward (name = "Detailtopic", Path = "detailtopic.jsp"),. Forward (name = "Newtopic", Path = "newtopic.jsp")}) public class Controller extends Pageflowcontroller {//controls used in page flow declaration. AP Ache.beehive.controls.api.bean.Control () protected Ejbfinder _ejbfindercontrol;. Apache.beehive.controls.api.bean.Control () protected Filecontrol _filecontrol ...//each action corresponds to a page flow, The following action corresponds to an action that adds a feedback topic.  Action () public Forward addtopic () {this.topicform = null;  This.topicform = new Topicform ();  Topicform.setfilelist (New ArrayList ());  This.loadlinkman (); return new Forward ("Newtopic"); } ... 

You can use the Netui tag in the paging file to implement binding data, resource declarations, template usage, and so on, so that you can minimize Java coding in the paging file, making the page easier to maintain and manage. The following is a page that displays a list of topics topiclist.jsp:

<netui-template:template templatepage= ". /web/template/template.jsp "> <netui-template:section name=" Leftcol "> <jsp:include page=" newTopicNav.jsp "/> </netui- template:section> <netui-template:section name= "Centercol" > <ejar-ui:window width= "70%" title= "" "> <netui:form action = "/newtopic" > <% file= ".          /WEB/TEMPLATE/ERRORS.JSPF "%> <table> <tr> <td> <netui:span value=" "> </netui:span> </td>         <td> <netui:select datasource= "pageFlow.topicForm.receiverName" optionsdatasource= "" > </netui:select>           </td> </tr> <tr> <td> <netui:span value= "" > </netui:span> </td> <td>         <netui:textbox datasource= "PageFlow.topicForm.title" > </netui:textBox> </td> </tr> <tr> <td> <netui:span value= "" > </netui:span> </td> <td> <netui:textbox datasour Ce= "PageFlow.topicForm.deadline" > </netui:textBox> <netui:span ValUe= "" > </netui:span> </td> </tr> <tr> <td> <netui:span value= "" ></netui:span > </td> <td> <netui-data:repeater datasource= "PageFlow.topicForm.fileList" netui-data:repeateritem> <netui:image src= "Http://www.webjx.com/htmldata/resources/images/i.p.attach.gif" ></                        netui:image> <netui:span value= ""/>   </netui-data:repeaterItem> </netui-data:repeater> </td> </tr> <tr> <td> <netui:span value= "" ></net ui:span> </td> <td> <netui:textarea datasource= "PageFlow.topicForm.content" C         Ols= "A" rows= "ten" > </netui:textArea> </td> </tr> <tr> <td colspan= "2" height= "40" <netui:button value= "" type= "Submit" action= "/savetopicform" > </netui:button>    <netui:bu Tton type= "Submit" value= "" > </netui:button> </td> </tr> </table> </netui:form> <br > </ejar-ui:window> </netui-template:section> </netui-template:template>

The final page flow file corresponds to the Design view in pollinate as follows:

After building the entire project, the page flow control file is compiled into a class file and a corresponding configuration file web-inf.pageflow-struts-generated jpf-struts-config-[page flow name].xml, The configuration file defines the configuration for the annotations in a series of control files, as follows:

<struts-config> <form-beans> <form-beanname= "Uploadfileform" type= "Org.form.UploadFileForm" Classname= " Org.apache.beehive.netui.pageflow.config.PageFlowActionFormBean "> <set-property property=" Actualtype "value=" Org.form.UploadFileForm "/> </form-bean> </form-beans> <global-exceptions/> <global-forwards> <forward name=" showt Opics "path="/topiclist.jsp "/> <forward name=" addfeedbackaccessories "path="/feedbackaccessories.jsp "/> </global-f orwards> <action-mappings> <actionpath= "/addaccessories" name= uploadfileform "type=" Org.apache.beehive.netui.pageflow.internal.FlowControllerAction "input=" Addtopicaccessories "
Parameter= "Topics. Controller "scope=" Request Validate= "true" > <forward name= "Newtopic" path= "/newtopic.jsp"/> "!--forward" addtop Icaccessories "(validationerrorforward)--> <forward name=" addtopicaccessories "path="/accessories.jsp "/> </action> ...... <message-resources key= "_defaultvalidationmessages" parameter= " Org.apache.beehive.netui.pageflow.validation.defaultMessages "null=" true "/> </struts-config>

Due to the limited space, can not elaborate on the use of pollinate, readers may refer to related articles: Pollinate visual development page flow (JPF) http://dev2dev.bea.com.cn/techdoc/200504503.html

Achieve internationalization

To implement the display of Chinese and English in Japanese, take the following steps:

Specifies the character set as UTF-8 when developing and compiling code. Eclipse can be set in the project properties. Using a filter, if all requests are passed through a servlet control allocator, use the filter execution statement of the servlet to convert all requests from the browser (request) to UTF-8 because the request package sent by the browser is encoded according to the operating system on which the browser resides. may be various forms of coding. Request.setcharacterencoding ("UTF-8"). You need to configure Web.xml to activate the filter. In the JSP header statement:

<%@ page contenttype= "text/html;charset= UTF-8"%>.

In the JSP's HTML code, declare UTF-8:



Setting the database connection method is UTF-8. For example, when connecting to MySQL, configure the URL as follows:

Jdbc:mysql://localhost:3306/feedback_db?useunicode=true&characterencoding=utf-8

Other interacting with the outside can be set when the encoding set UTF-8, such as reading files, operating XML and so on.

Time display in different time zones

Because the client may be in a different time zone, different server times should be displayed. Because of the client-side, you need to take a section of JavaScript code to get the time zone offset from the client. This offset is for GMT time, which is GMT, in minutes.

function getTimeZone () {var d = new Date ();   Document[getnetuitagname ("LoginForm", this)][getnetuitagname ("timezone", this)].value=    D.gettimezoneoffset () ;   }

Get it back to the server side and save it in session. The time displayed is calculated based on the offset when the time is displayed.

Summarize

Technology


EJB3.0 is based on Hibernate3.0, greatly simplifying the difficulty and complexity of development, enabling developers to develop quickly and efficiently, beehive as an open source project for Apache, with the strong support of BEA, enabling developers to implement Java component based development, an ideal choice for building SOA in open source projects Choose.

Tools
The Eclipse pollinate, as the only tool that supports beehive development, can quickly create beehive projects, but there are still problems with the synchronization of code and Design view during development, such as in. The. Forward defined in controller is not recognized in Design view. Therefore, compared with Bea's workshop, pollinate still has a long way to go. Therefore, for the development of large applications, the BEA Workshop is still the choice, for those beginners, you can also use the Workshop of BEA and combine its own Help system to learn Pageflow,java Control,java WebService , including portals, integrated applications, and other advanced technologies. After a certain understanding of these technologies, learning beehive development will be more rapid and effective.

Through an example, this paper introduces how to combine EJB3.0 and beehive to rapidly develop the application of Java EE. Due to the introduction of some new technology, there are inevitably omissions and errors in the text, and we welcome the correction. And thanks to Kevin Kevman for his technical help.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.