Beruflich Dokumente
Kultur Dokumente
A few topics
Java persistence API EJB Hibernate Spring
The Java Persistence API - A Simpler Programming Model for Entity Persistence (an artitcle from SUN)
http://java.sun.com/developer/technicalArticles/J2EE/jpa/ article link includes a downloadable example https://glassfish-samples.dev.java.net/source/browse/*checkout*/glassfishsamples/ws/javaee5/docs/UserREADME.html contains config and setup for running glassfish /java db samples if you are using glassfish sun app server (which is bundled with netbeans) A major enhancement in EJB technology is the addition of the new Java Persistence API, which simplifies the entity persistence model and adds capabilities that were not in EJB 2.1 technology. The Java Persistence API deals with the way relational data is mapped to Java objects ("persistent entities"), the way that these objects are stored in a relational database so that they can be accessed at a later time, and the continued existence of an entity's state even after the application that uses it ends. In addition to simplifying the entity persistence model, the Java Persistence API standardizes object-relational mapping. In short, EJB 3.0 is much easier to learn and use than was EJB 2.1, the technology's previous version, and should result in faster development of applications. With the inclusion of the Java Persistence API, EJB 3.0 technology also offers developers an entity programming model that is both easier to use and yet richer. The Java Persistence API draws on ideas from leading persistence frameworks and APIs such as Hibernate, Oracle TopLink, and Java Data Objects (JDO), and well as on the earlier EJB container-managed persistence. The Expert Group for the Enterprise JavaBeans 3.0 Specification (JSR 220) has representation from experts in all of these areas as well as from other individuals of note in the persistence community.
Spring
A tutorial at http://static.springsource.org/springws/sites/1.5/reference/html/tutorial.html Spring manages xml messaging creating web services that can be used by soap. Soap is an xml-based RMI mechanism. Recall, XML is text, and so soap uses text to invoke methods of remote objects and to transfer the payload back.
Goals of Spring
Spring should be a pleasure to use Your application code should not depend on Spring APIs Spring should not compete with good existing solutions, but should foster integration. (For example, JDO, Toplink, and Hibernate are great O/R mapping solutions. We don't need to develop another one.) Spring Features Spring is a layered Java/J2EE application platform, based on code published in Expert One-on-One J2EE Design and Development by Rod Johnson (Wrox, 2002).
Spring includes
The most complete lightweight container, providing centralized, automated configuration and wiring of your application objects. The container is non-invasive, capable of assembling a complex system from a set of loosely-coupled components (POJOs) in a consistent and transparent fashion. The container brings agility and leverage, and improves application testability and scalability by allowing software components to be first developed and tested in isolation, then scaled up for deployment in any environment (J2SE or J2EE). A common abstraction layer for transaction management, allowing for pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues. Generic strategies for JTA and a single JDBC DataSource are included. In contrast to plain JTA or EJB CMT, Spring's transaction support is not tied to J2EE environments. A JDBC abstraction layer that offers a meaningful exception hierarchy (no more pulling vendor codes out of SQLException), simplifies error handling, and greatly reduces the amount of code you'll need to write. You'll never need to write another finally block to use JDBC again. The JDBCoriented exceptions comply to Spring's generic DAO exception hierarchy. Integration with Toplink, Hibernate, JDO, and iBATIS SQL Maps: in terms of resource holders, DAO implementation support, and transaction strategies. First-class Hibernate support with lots of IoC convenience features, addressing many typical Hibernate integration issues. All of these comply to Spring's generic transaction and DAO exception hierarchies.
Spring, continued
AOP functionality, fully integrated into Spring configuration management. You can AOP-enable any object managed by Spring, adding aspects such as declarative transaction management. With Spring, you can have declarative transaction management without EJB... even without JTA, if you're using a single database in Tomcat or another web container without JTA support. A flexible MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI. Note that a Spring middle tier can easily be combined with a web tier based on any other web MVC framework, like Struts, WebWork, or Tapestry. You can use all of Spring's functionality in any J2EE server, and most of it also in non-managed environments. A central focus of Spring is to allow for reusable business and data access objects that are not tied to specific J2EE services. Such objects can be reused across J2EE environments (web or EJB), standalone applications, test environments, etc without any hassle. Spring's layered architecture gives you a lot of flexibility. All its functionality builds on lower levels. So you can e.g. use the JavaBeans configuration management without using the MVC framework or AOP support. But if you use the web MVC framework or AOP support, you'll find they build on the core Spring configuration, so you can apply your knowledge about it immediately. Other Spring Projects: Each project focuses on addressing a particular enterprise middleware problem in open-source. See the Spring projects page for more information. In brief, Spring allows OOD/OOP programmers to focus on objects, not on the mechanics of database interfaces (connections, queries, and so on).
Hibernate
This is now in a separate hibernate.ppt
FirstBean\WEBINF\classes\thepackage\FirstBean.java
package thepackage; public class GreeterBean { public String sayHello() { return("Hello, World!"); } }
Note: The src could actually be in another directory called src, but ultimately the class file will have to be in this directory. Use any package name you like
FirstBean\WEB-INF\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> </web-app> Note: there is no servlet so this webapp tag can be empty. There is a JSP (later slide).
FirstBean\beanExample.jsp
<%@ page language="java" %> <html> <head><title>Hello Example</title></head> <body> <jsp:useBean id="greeter" class=thepackage.GreeterBean" scope="session"/> <%= greeter.sayHello() %> </body> </html> Note: Jsp and html go in the top level of the webapp directory structure. Note: URL in next slide: localhost:port/webappcontext/jspname.jsp
SecondBean\WEBINF\classes\thepackage\NumberBean.java
package thepackage; public class NumberBean { private int integerProperty = 1; public int getIntegerProperty() { return integerProperty; } public void setIntegerProperty(int newInteger) { integerProperty = newInteger; }} As in previous example, this could actually go in a separate dir called src, but the class file will need to go in \classes\thepackage
SecondBean\beanExample.jsp
<%@ page language="java" %> <jsp:useBean id="number" class=packagename.NumberBean" scope="session"/> <html> <head><title>Second Bean Example</title></head> <body> JavaBean state starts at <%= number.getIntegerProperty() %> <% number.setIntegerProperty(2); %> <br> JavaBean state is now <%= number.getIntegerProperty() %> </body> </html>
deployment
Other directories for this example are the same as the first example. Still need to javac the java source file. A jar command for this example, assuming the cmd.exe is in the SecondBean directory and classpaths are correctly set:
jar cvf SecondBean.war beanExample.jsp WEB-INF
Secondbean example
Remember to build directory structure with WEB-INF containing web.xml. Put jsp and css at top level. Jar into a war file. Drop it into webapps of tomcat or in the server/default/deploy directory of JBoss.
/** * * @author HIGGINDM */ public class InfoHandler { String name; double gpa; int age; String address; public String getAddress() { return address; }
public void setAddress(String address) { this.address = address; }
firstPage.jsp gets current values and passes file name for serialization
<%@ page language="java" %> <jsp:useBean id="theBean" class="com.masslight.beans.SerializableBean" scope="page" /> <html> <title>Serialized bean, Page One</title> <body> <br> <%= theBean.getIntegerProperty() %> <% theBean.setIntegerProperty(8+theBean.getIntegerProperty()); %> <br> <%= theBean.getIntegerProperty() %> <% theBean.save(theBean, "theBeanFile.ser"); %> <br> <a href="http://localhost:8080/SerializableBean/secondPage.jsp">click here</a>
</body> </html>
</body> </html>
architecture
EJB servers: Composed of server software, the EJB server is analogous to the Object Request Broker (ORB) from the CORBA world. The server provides a way for the client to transact with the EJBs. It also provides naming services. EJB containers Located inside the EJB server, the EJB containers provide a means for invoking an EJBs methods. An EJB client can send a request to invoke a method on an EJB to the EJB container. The EJB container invokes the appropriate method on the EJB. Containers provide support for security, object persistence, resource pooling, and transaction processing. EJB clients EJB clients find EJBs through a naming and directory service. The client then sends a message to an EJB container, which determines the EJB method that the client wants to invoke. Enterprise JavaBeans Enterprise JavaBeans can be session beans, entity beans, or message-driven beans. We will discuss these more in the next section. EJBs reside within EJB containers. Directory service The directory/naming service provides the ability to locate any object registered with the directory/naming service. It provides a mapping between a given name of an entity and, in the case of EJBs, a stub that corresponds to the home interface of an Enterprise JavaBean (this will be discussed later in the chapter).
Passivation/Activation An EJB container can manage its primary memory allocation by passivating and activating the EJBs that it manages. Passivation saves the state of a bean to persistent storage, and swaps it out of memory. Activation is just the opposite of passivation: the state of a bean is restored from persistent storage and is swapped into memory. The processes of passivation and activation apply to stateful session beans and all entity beans. Before the EJB is passivated and after the EJB is activated, the container calls the ejbPassivate() or ejbActivate(), respectively, of the EJB's bean class so that the EJB can perform any necessary setup to handle the EJB's change of state. Persistence Stateful session beans and entity beans are persistent. The EJB container or the bean class of the EJB provides the necessary functionality to support the persistence of the bean's state. To save a bean, we can get a javax.ejb.Handle object for the bean by invoking the EJB's getHandle() method. Restoration is accomplished by invoking the getEJBObject() method on the Handle object.
naming:
deployment
The sevlet running and the example dir showing .ear file
<!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> <servlet> <servlet-name>HelloWorld</servlet-name> <servlet-class>HelloWorld</servlet-class> </servlet> <servlet-mapping> <url-pattern>/servlet/HelloWorld</url-pattern> <servlet-name>HelloWorld</servlet-name> </servlet-mapping> </web-app>
Run ant and then move .ear file to deploy directory of jboss
session info servlet example no beans here, just practice using ant\jboss\ear
Put servlet in the src directory. Servlet code is in the slide notes.
Sessioninfo\build\deploymentdescriptors\we b.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> <servlet> <servlet-name>SessionInfo</servlet-name> <servlet-class>SessionInfo</servlet-class> </servlet> <servlet-mapping> <servlet-name>SessionInfo</servlet-name> <url-pattern>/servlet/SessionInfo</url-pattern>
</servlet-mapping>
</web-app>
Sessioninfo\build\deploymentdescriptors\ap plication.xml
<?xml version="1.0" encoding="ISO-8859-1"?> <application> <display-name>SessionInfo</display-name> <module> <web> <web-uri>sessioninfo.war</web-uri> <context-root>/sessioninfo</context-root> </web> </module> </application>
/deploymentdescriptors/jbossapp.xml
<jboss-app> <loader-repository> example2:archive=sessioninfo.ear </loader-repository> </jboss-app>
<!-- Compile Java Files and store in /build/src directory --> <target name="build" > <javac srcdir="${src}" destdir="${classdir}" debug="true" includes="**/*.java" /> </target> .
Using ant
http://www.roseindia.net/jboss/buildingweb applicationwithant.html This url is pretty good except one mistake. Build directories etc as indicated and use ant tool. Deploy servlet in deploy directory of JBoss.
<max-pool-size>15</max-pool-size>
<!-- Don't allow connections to hang out idle too long, never longer than what wait_timeout is set to on the server...A few minutes is usually okay here, it depends on your application and how much spikey load it will see -->
<idle-timeout-minutes>2</idle-timeout-minutes>
<exception-sorter-class-name>com.mysql.jdbc.integration.jboss.ExtendedMysqlExceptionSorter</exception-sorterclass-name> <valid-connection-checker-classname>com.mysql.jdbc.integration.jboss.MysqlValidConnectionChecker</valid-connection-checker-class-name> </local-tx-datasource> </datasources>
My servlet
In slide notes Youll need J2EE.jar in your classpath. If you hunt around, you can find a download for just the jar file, not the entire Sun WebServer.
http://openejb.apache.org/tomcat-detailedinstructions.html Download openejb.war from apache Move to tomcat webapps directory. Visit http://localhost:8080/openejb/installer (it does the installation) Wait Shutdown and restart tomcat. Revisit that link to check installation. Follow directions in installation info at apache as per link above
http://openejb.apache.org/
http://docs.codehaus.org/display/OPENEJ B/Tomcat+ObjectFactory Setting up paths and files to install and run ejbs IMPORTANT: You need to copy the openejb-loader to tomcat/webapps folder.
Maven
Install maven Update path settings for maven I found I needed to restart my computer to apply the path settings
https://mediamill.cla.umn.edu/mediamill/e mbed/7008 Although he uses a tool for this, you can build it all with any editor. You can deploy in tomcat using the standard directory structure. Or, jar the directory stucture as a war file and drop into webapps.
A cp.bat file
My class path settings: set CLASSPATH=.;C:\ejb_jar_files\ejb.jar;C:\ejb_jar_files\jndi.jar;C:\ejb_jar _files\geronimo-ejb.jar;C:\ejb_jar_files\j2ee.jar;c:\FtoCEJB; These must be on one line. I built a batch file called cp.bat. I used javac on the command line. In the structure below, the webapp can be dropped into Tomcats webapps directory. My directory structure: FtoCEJB
-WEB-INF
classes
mycode FtoC.class FtoCServlet.class FtoCBean.class
web.xml lib
J2ee.jar //I dont know if this is needed
FtoCServlet
package mycode; import javax.ejb.EJB; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class FtoCServlet extends HttpServlet { @EJB FtoC bean; protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { res.setContentType("text/plain"); ServletOutputStream out = res.getOutputStream(); String degrees=req.getParameter("degrees"); out.println("Welcome to F to C Converter"); out.println(bean.convert(degrees)+" degrees"); } }
Web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <servlet> <servlet-name>FtoCServlet</servlet-name> <servlet-class>mycode.FtoCServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>FtoCServlet</servlet-name> <url-pattern>/FtoC/*</url-pattern> </servlet-mapping> </web-app>
Examples index.jsp
Heres another
links
http://javanotebook.com/2007/09/28/opene jb_3_and_tomcat_6.html This site had a nice example and good explanation
Netbeans
Netbeans is a complete builder IDE for java, beans and web app deployment, but also for C/C++, Ruby and PHP. The Netbeans v6.5 can be downloaded with Glassfish, a sun server, and a bundled Tomcat server. It also contains the java database Derby. Deployment is very easy a click of a button.
Netbeans deployment
The first tutorial involves using java persistence in a web app You Create java classes and deploy to glassfish server using NetBeans IDE Creates beans and jsf and ear files and deploys. http://www.netbeans.org/kb/61/javaee/pers istence.html#getstarted
You can follow the hibernate tutorial also for this first project
Steps: In Netbeans build a New project with JSF and hibernate frameworks To project: Add entity mappings from Database
(youll need to start the db beforehand) and youll need to know user/pw. Select tables to use and generate persistence classes.
Apache must be running to manage phpmyadmin. Apache is probably on port 80 but if it is on port 8080 youll need to stop it before starting (running/deploying) this project in the glassfish server.
settings
I used glassfish server Java EE5 Left context path as it was
Subjects CRUD
HelloSpring
Choose New Project (Ctrl-Shift-N) from the IDE's File menu. Under Categories select Java Web. (If you are using NetBeans 6.1, select Web.) Under Projects select Web Application. Click Next. In Project Name, type in HelloSpring. Click Next. In Step 3, Server and Settings, select the server you plan to work with from the Server drop-down list. Leave all other settings at their defaults and click Next. In Step 4, the Frameworks panel, select Spring Web MVC 2.5:
When you select Spring Web MVC 2.5, note that you can configure the name and mapping of the Spring dispatcher servlet under the Configuration tab. If you click the Libraries tab, note that JSTL libraries are by default added to the classpath during project creation.
Click Finish. The IDE creates a project for the entire application, including all metadata, as well as the project's Ant build script which you can inspect from the Files window (Ctrl-2). You can view the template structure from the Projects window (Ctrl-1). Also note that four files open by default in the IDE's Source Editor: dispatcher-servlet.xml, applicationContext.xml, redirect.jsp, and index.jsp.
Run skeleton
Web.xml is generated for you and any URL *.htm maps to Springs dispatcher servlet.
just a bit of web.xml: <servlet> <servlet-name>dispatcher</servletname> <servletclass>org.springframework.web.servlet.Di spatcherServlet</servlet-class> <load-on-startup>2</load-on-startup> </servlet>
Three beans are defined in this file: indexController, viewResolver, and urlMapping.
When the DispatcherServlet receives a request that matches *.htm such as index.htm, it looks for a controller within urlMapping that can accommodate the request. Above, you see that there is a mappings property that links /index.htm to indexController. The runtime environment then searches for the definition of a bean named indexController, which is conveniently provided by the skeleton project. Note that indexController extends ParameterizableViewController. This is another class provided by Spring, which simply returns a view. Above, note that p:viewName="index" specifies the logical view name, which is resolved using the viewResolver by prepending /WEB-INF/jsp/ and appending .jsp to it. This allows the runtime to locate the file within the WAR file of the application, and respond with the welcome page view (/WEB-INF/jsp/index.jsp).
EJB example
http://www.netbeans. org/kb/55/persistence. html The ZooApp
Allows new animal and pavilion creation (something wrong with link up)
Setting up database
Note. This tutorial uses the JavaDB database server but you can also complete the tutorial using the MySQL database server. To create the database in MySQL, download and extract the mysql-consult.zip archive. The archive contains SQL scripts for creating and populating the consult database. For more information on configuring the IDE to work with MySQL, see the Connecting to a MySQL Database tutorial.
Download derby-consult.zip and extract the archive to your local system. When you extract the archive you will see the SQL scripts for creating and populating the database. The archive also has scripts for dropping tables. In the Services window, expand the Databases node, right-click the JavaDB node and choose Start Server. Right-click the Java DB node and choose Create Database. Type consult as the Database Name, User Name, and Password in the Create Java DB dialog. Click OK. A new node appears under the Databases node (jdbc:derby://localhost:1527/consult [consult on CONSULT]).
Building the derby consult database from a file after run sql- check tables
When creating entity classes from a database, the IDE automatically generates the appropriate code for the various field types.
Database TableDescriptionDesign Features CLIENT A client of the consulting agencyNon-generated, composite primary key (whose fields do not constitute a foreign key) CONSULTANTAn employee of the consulting agency whom clients can hire on a contract basisIncludes a resume field of type LONG VARCHAR CONSULTANT_STATUS A consultant's status with the consulting agency (for example, Active and Inactive are possible statuses)Non-generated primary key of type CHAR RECRUITERAn employee of the consulting agency responsible for connecting clients and consultants PROJECT A project that a client staffs with consultants of the consulting agencyNongenerated, composite primary key that includes two fields constituting a foreign key to the CLIENT table BILLABLE A set of hours worked by a consultant on a project, for which the consulting agency bills the relevant clientIncludes an artifact field of type CLOB ADDRESS A client's billing address PROJECT_CONSULTANTJoin table indicating which consultants are currently assigned to which projectsCross-references PROJECT and CONSULTANT, the former having a composite primary key
entities
EntityRelated EntityRelationship InformationDescription CLIENT RECRUITER nullable one-to-one with manual editing; nullable oneto-many if not edited CLIENT has many RECRUITERs and RECRUITER has zero or one CLIENT (if not manually edited) CLIENT ADDRESSnon-nullable one-to-oneCLIENT has one ADDRESS and ADDRESS has zero or one CLIENT CLIENT PROJECTnon-nullable one-to-many; in a Project entity, the value of the client field is part of the Project's primary keyCLIENT has many PROJECTs and PROJECT has one CLIENT CONSULTANT PROJECTmany-to-manyCONSULTANT has many PROJECTs and PROJECT has many CONSULTANTs CONSULTANT BILLABLEnon-nullable one-to-manyCONSULTANT has many BILLABLEs and BILLABLE has one CONSULTANT CONSULTANT_STATUS CONSULTANTnon-nullable one-tomanyCONSULTANT_STATUS has many CONSULTANTs and CONSULTANT has one CONSULTANT_STATUS CONSULTANT RECRUITERnullable one-to-manyCONSULTANT has zero or one RECRUITER and RECRUITER has many CONSULTANTs BILLABLE PROJECTnon-nullable one-to-manyBILLABLE has one PROJECT and PROJECT has many BILLABLEs
When using the wizard to create entity classes from a database, the IDE examines the relationships between the tables. In the Projects window, if you expand the jpa.entities Source Package node you can see that the IDE generated an entity class for each table except for the PROJECT_CONSULTANT table. The IDE did not create an entity class for PROJECT_CONSULTANT because the table is a join table. The IDE also generated two additional classes for the tables with composite primary keys: CLIENT and PROJECT. The primary key classes for these tables (ClientPK.java and ProjectPK.java) have PK appended to the name.
Now that the entity classes are created, you can create the web interface for displaying and modifying the data. You will use the JSF Pages from Entity Classes wizard to generate JavaServer Faces pages. The code generated by the wizard includes checks based on the annotations in the entity classes. The wizard also gives you the option to enable Ajax functionality in the application by extending the JavaServer Faces technology with Dynamic Faces technology. For each entity class the wizard generates the following: a JPA controller class a JSF controller class a JSF converter class a directory containing four JSP files (Detail.jsp, Edit.jsp, List.jsp, New.jsp) managed bean elements, converter elements and navigation rules for the entity in faces-config.xml The wizard also generates the following classes used by the controller classes: exception classes used by the JPA controllers utility classes used by the JSF controllers