Wednesday, October 7, 2009

First EJB3.0 example, EJB3.0 tutorial, @EJB not working

Here I am putting very easy example for EJB3.0. It has Session Bean, Entity Bean and JPA example. All these examples are in very step wise. I have used glassfish application server. For other application server I was getting error when I used @EJB. So decided to use glassfish application server.

1. Install glassfish-tools-bundle-for-eclipse-1.1.exe
2. start -> All Program -> GlassFish tool bundle for eclipse 1.1 -> GlassFish tool bundle for eclipse
3. File -> New Project -> EJB
4. Put name of Project say school -> click on add project to EAR say SchoolEAR
5. File -> New Project -> Dynamic Web Project -> Put name of Project say schoolWEB -> click on add project to EAR say SchoolEAR
6. Click on SchoolWEB -> Webcontent -> Right click and create one JSP page say search.jsp

search.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Student Search Page</title>
</head>
<body bgcolor="green"><h1> ABC SCHOOL </h1>
<table align="center">
<tr><td>Enter Student Roll </td><td><input type="text" name="roll"></td>
</tr><tr><td><input type="submit" name="searchStudent" value="Search""></td>
</tr>
</table>
</body>
</html>

7. Go to Server Pan and start server (Bundled GlassFish V2.1)
8. Add project SchoolEAR to server
9. Run http://localhost:8082/SchoolWEB/search.jsp (Just for test whether page is coming) now you should able to see the search page in your browser.

Now Add one servlet:
1. Go to School Project -> ejbModule -> create Servlet -> put Package Name: com and classname: SearchServlet -> Finish
2. SearchServlet.java

package com;
import java.io.IOException;
import javax.ejb.EJB;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SearchServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public SearchServlet()
{ super();
System.out.println("SearchServlet IS CALLING");
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("THIS IS SEARCH SERVLET");
int roll = Integer.parseInt(request.getParameter("roll"));
System.out.println("Roll Entered :: "+roll);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("THIS IS DO POST METHOD");
}
}

3. Your web.xml of SchoolWEB should be like this: (Path C:\GlassFish_Workspace\EJB3\Practice_1\SchoolWEB\WebContent\WEB-INF\web.xml)
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>SchoolWEB</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>SearchServlet</display-name>
<servlet-name>SearchServlet</servlet-name>
<servlet-class>com.SearchServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>SearchServlet</servlet-name>
<url-pattern>/SearchServlet</url-pattern>

</servlet-mapping>
</web-app>

NOTE: One problem with this version of Glassfish that every time when you change code you have to clean your project and restart server. :(

4. Change little bit your JSP code to call this new servlet.
Search.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Student Search Page</title>
</head>
<body bgcolor="green">
<h1> ABC SCHOOL </h1>
<form action="SearchServlet">
<table align="center"><tr>
<td>Enter Student Roll </td><td><input type="text" name="roll"></td>
</tr><tr><td>
<input type="submit" name="searchStudent" value="Search""></td>
</tr>
</table>
</form>
</body>
</html>

5. Clean your all project and restart the servercall on browser: http://localhost:8082/SchoolWEB/search.jsp
Put some roll number and see the server log file (say entered 110)you should get the output like INFO: THIS IS SEARCH SERVLETINFO: Roll Entered :: 110

Now add Session Bean: [IMPORTANT]
1. Click on School project -> ejbModule -> Right click -> New -> Interface -> package com and class name: ISearchBean

ISearchBean.java
package com;
public interface ISearchBean {
public String search(int roll);
}
2. Click on School project -> ejbModule -> Right click -> New -> SessionBean -> package com and class name: SearchBean
SessionType: StatelessSearchBean.java

package com;
import javax.ejb.Stateless;
@Statelesspublic class SearchBean implements ISearchBean{
public SearchBean() { }
@Override
public String search(int roll) {
if(roll == 110){ return "Binod Kumar Suman"; }
return "Name does not match";
}
}

Note: You used here first EJB annotation @Stateless :)
3. Change servlet to call this session bean with use of @EBJ annotation

SearchServlet.java
package com;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SearchServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@EJB
private ISearchBean searchBean;

public SearchServlet() {
super();
System.out.println("SearchServlet IS CALLING");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("THIS IS SEARCH SERVLET");
int roll = Integer.parseInt(request.getParameter("roll"));
System.out.println("Roll Entered :: "+roll);
if(searchBean == null){ System.out.println("SearchBean is still null"); }
else{ System.out.println("Search Bean is working fine");
System.out.println("Result :: "+searchBean.search(roll)); }
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("THIS IS DO POST METHOD"); }
}

4. Now run the jsp file from browser:http://localhost:8082/SchoolWEB/search.jsp
Put roll number 110and check server output:
INFO: SearchServlet IS CALLINGINFO: THIS IS SEARCH SERVLET
INFO: Roll Entered :: 110
INFO: Search Bean is working fine
INFO: Result :: Binod Kumar Suman

*********** NOW ADD JPA Persistence part *****************
Now we will see how to save data using EJB3.0 JPA (Plesae get introduction of EJB3.0 JPA from this URL http://binodsuman.blogspot.com/2009/10/jpa-introduction-what-is-jpa-java.html)
1. To use JPA in EJB3.0, you have to add persistence.xml in META-INF folder, thatshould have your database connection information.
2. Create one entity class say student
student.java in com.entity folder

package com.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "studentinfo")
public class Student {
private int roll; private String name; private String cell;
@Id
@Column(name="roll",unique=true,updatable=true)
public int getRoll() { return roll; }

public void setRoll(int roll) { this.roll = roll; }
@Column(name="sname",updatable=true)
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getCell() { return cell; }
public void setCell(String cell) { this.cell = cell; }

}
persistence.xml in (C:\GlassFish_Workspace\EJB3\Practice_1\School\ejbModule\META-INF\persistence.xml)
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence persistence_1_0.xsd" version="1.0">
<persistence-unit name="student_unit" transaction-type="RESOURCE_LOCAL">
<provider>oracle.toplink.essentials.PersistenceProvider</provider>
<class>com.entity.Student</class>
<properties>
<property name="toplink.logging.level" value="FINEST" />
<property name="toplink.jdbc.driver" value="org.postgresql.Driver" />
<property name="toplink.jdbc.url" value="jdbc:postgresql://localhost:5432/postgres" />
<property name="toplink.jdbc.user" value="postgres" />
<property name="toplink.jdbc.password" value="suman" />
</properties>
</persistence-unit>
</persistence>

I have used here postgres sql, you can use any database.Create one table studentinfo
CREATE TABLE studentinfo(
roll int4 NOT NULL,
sname char(100),
cell char(15), CONSTRAINT "studentinfo_PK" PRIMARY KEY (roll)
)

Now change in SearchBean.java

package com;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import com.entity.Student;
@Stateless
public class SearchBean implements ISearchBean{
private static EntityManagerFactory emf;
private static EntityManager em;
public SearchBean() { }
@Override
public String search(int roll) {
if(roll == 110){ return "Binod Kumar Suman"; }
return "Name does not match";
}

@Override
public void saveStudent(Student student) {
System.out.println("IN SEARCH BEAN TO SAVE STUDENT RECORD");
try{
emf = Persistence.createEntityManagerFactory("student_unit");
em = emf.createEntityManager();
// Begin transaction
em.getTransaction().begin();
em.persist(student);
em.getTransaction().commit();
// Close this EntityManager
em.close();
System.out.println("***** RECORD SAVED SUCCESSFULLY ***************");
}
catch(Exception e){
System.out.println("SOME PROBLEM DURING SAVE STUDENT :: "+e);
e.printStackTrace(); }
}
}
And change in SearchServlet.java

package com;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.entity.Student;

public class SearchServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@EJB
private ISearchBean searchBean;
public SearchServlet() {
super();
System.out.println("SearchServlet IS CALLING");
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("THIS IS SEARCH SERVLET");
int roll = Integer.parseInt(request.getParameter("roll"));
System.out.println("Roll Entered :: "+roll);
if(searchBean == null){ System.out.println("SearchBean is still null"); }
else{ System.out.println("Search Bean is working fine");
System.out.println("Result :: "+searchBean.search(roll));
Student student = new Student();
student.setRoll(150);
student.setName("Manish");
student.setCell("12345678");
searchBean.saveStudent(student);
System.out.println("******** One record of Student has been saved ********");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("THIS IS DO POST METHOD"); }
}

Now you can http://localhost:8082/SchoolWEB/search.jsp and put any roll number. Onc student record would be saveed in database.
Easy ...................... :)

2 comments:

  1. This good example for beginners.The presentation is excellent.

    ReplyDelete

You can put your comments here (Either feedback or your Question related to blog)