Por defecto el calendario en Primefaces y a su vez todos sus componentes vienen en English, la forma que tenemos para cambiar las locales a nuestro lenguajes es sencilla:
1: en el archivo .xhtml donde se esta trabajando dentro del <h:head><h:/head> vamos a crear un script javascrip y alli colocamos el siguiente codigo, tener en cuenta que el codigo lo vamos a colocar dentro delas etiquetas <script></script> como se muestra a continuacion
<script>
PrimeFaces.locales['es'] = {
closeText: 'Cerrar',
prevText: 'Anterior',
nextText: 'Siguiente',
monthNames: ['Enero','Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
monthNamesShort: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun','Jul','Ago','Sep','Oct','Nov','Dic'],
dayNames: ['Domingo','Lunes','Martes','Miércoles','Jueves','Viernes','Sábado'],
dayNamesShort: ['Dom','Lun', 'Mar', 'Mie', 'Jue', 'Vie', 'Sab'],
dayNamesMin: ['D','L','M','M','J','V','S'],
weekHeader: 'Semana',
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: '',
timeOnlyTitle: 'Sólo hora',
timeText: 'Tiempo',
hourText: 'Hora',
minuteText: 'Minuto',
secondText: 'Segundo',
currentText: 'Fecha actual',
ampm: false,
month: 'Mes',
week: 'Semana',
day: 'Día',
allDayText : 'Todo el día'
};
</script>
Luego donde tengamos el componente Calendar vamos a colocar locale="es", que es el nombre que habiamos definido anteriormente, como se muestra enseguida.
<p:calendar value="#{managedbeanCentinela.date1}" pattern="yyyy-MM-dd" locale="es" />
Wednesday, October 28, 2015
Monday, October 26, 2015
Manejo de fechas 1 en JPA
Cuando se esta trabajando con Fechas en JPA, si creamos un campo de tipo Date, jpa por defecto asumira que es un campo datetime y si no necesitamos las horas, minutos y segundos es un perdidad de tiempo almacenar este tipo de dato con esta caracteristica, para evitar este proceso cuando estemos en las entidades que vallamos a crear el campo fecha de tipo Date lo definimos asi
@Temporal(TemporalType.DATE)
private Date fecha;
de esta manera las fechas que creemos con
Date date = Calendar.getInstance().getTime();
seran solo "yyyy-MM-dd", ahora cuando realizasmo las consultas, no debemos de olvidar colocar siempre como parametro en la fecha que vamos a enviar el parametro TemporalType.DATE asi:
There are 3 values for @Temporal
If the column annotated with @Temporal(TemporalType.DATE) like this:
The record in database after update will look like:
If the column annotatedwith @Temporal(TemporalType.TIME) like this:
The record in database after update will look like:
If the column annotated with @Temporal(TemporalType.TIMESTAMP) like this:
The record in database after update will look like:
@Temporal(TemporalType.DATE)
private Date fecha;
de esta manera las fechas que creemos con
Date date = Calendar.getInstance().getTime();
seran solo "yyyy-MM-dd", ahora cuando realizasmo las consultas, no debemos de olvidar colocar siempre como parametro en la fecha que vamos a enviar el parametro TemporalType.DATE asi:
Query q = em.createQuery("select o from LoadFileHistory o where o.finishDate > :today ");
q.setParameter("today",todaysDateObject,TemporalType.DATE);
q.getResultList();
Ejemplo mas completo:
@Override
public void getNumerosporusuario(String usuario) {
Date date = Calendar.getInstance().getTime();
List<NumerosAsignados> numeros;
Query query = em.createQuery("Select numeros from NumerosAsignados numeros where numeros.usuarios.cedula=:id and numeros.fecha=:time");
query.setParameter("id", usuario);
query.setParameter("time", date,TemporalType.DATE);
numeros = query.getResultList();
System.out.println("we are here ..");
for(NumerosAsignados str: numeros ){
System.out.println("Getting.."+str.getNumero());
}
//return null;
}
The annotation @Temporal in official javadoc is described like below:
This annotation must be specified for persistent fields or properties of type java.util.Date and java.util.Calendar.So when the field variable is a java.util.Date or java.util.Calendar, it MUST be annotated by @Temporal.
There are 3 values for @Temporal
- TemporalType.DATE
- TemporalType.TIME
- TemporalType.TIMESTAMP
1
2
3
4
5
| import java.util.Date;//...// MyEntity is the JPA entity, em is EntityManager contextMyEntity e = em.find(MyEntity.class, 1L); //get the row with id=1e.setLastUpdateTime(new Date()); |
TemporalType.DATE
If the column annotated with @Temporal(TemporalType.DATE) like this:
1
2
3
| @Temporal(TemporalType.DATE)@Column(name="LAST_UPDATE_TIME")private Date lastUpdateTime; |
The record in database after update will look like:
TemporalType.TIME
If the column annotatedwith @Temporal(TemporalType.TIME) like this:
1
2
3
| @Temporal(TemporalType.TIME)@Column(name="LAST_UPDATE_TIME")private Date lastUpdateTime; |
The record in database after update will look like:
TemporalType.TIMESTAMP
If the column annotated with @Temporal(TemporalType.TIMESTAMP) like this:
1
2
3
| @Temporal(TemporalType.TIMESTAMP)@Column(name="LAST_UPDATE_TIME")private Date lastUpdateTime; |
The record in database after update will look like:
Accessing values of a JSF managed bean in another managed bean SETTERS AND GETTERS
//Para poder enviar o extraer informacion de un Managed bean a otro, debemos de setear siempre un
nombre por lo menos al@ManagedBean(name="que deseamos enviar o recivir informacion, de no hacerlo arrojara un error en")bean1
tiempo de compilacion
@ManagedBean(name="") @ApplicationScopedbean1
public class Bean1{
public void metodo(String a, String b){
//logica del metodo...
}
}
//De esta manera estamos desde un Managedbean de @Sessionscoped alimentando a un ManagedBean @ApplicationScoped
//POdemos enviar y recivir cualquier tipo de tipo de dato, desde un array de objetos, hasta una variable cuaqluiera
@ManagedBean
@SessionScoped public class Bean2{ @ManagedProperty(value = "#{}")//this is EL name of your bean private Bean1 injectedBean;bean1
//setters & getters of bean1
//se deben siempre definir los getter y setters de esa instansiacion de ese objeto que se va a llamar
publicgetInjectedBean() { return injectedBean;Bean1
}
public void setInjectedBean(injectedBean) { this.injectedBean = injectedBean;Bean1
}
public void envia_datos(){
.injectedBeanmetodo("Valor 1","Valor 2");
}
}
//--***************************************************************************************--//
Saturday, October 24, 2015
Creating JSF View Backed By Managed Bean
To start we are going to create a class called StudentMB, and mark it with @ManagedBean annotation to make it a managed bean, and also we are going to mark it @ViewScoped this will make this bean scope to the view presentation. Now we need to define some fields and their getter setters. At last we need to define the methods which will do the Object creation and EJB method invocation.
Note: There are three scopes in managed beans viz session scope, request scope and view scope. These scope have different meanings as Session scope is valid for the whole session until you close the window. Request scope is valid only until a response is received for the request. View scope is valid until a view exist or is not closed.
package com.em.managedbeans;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import com.em.ejb.beans.interfaces.StudentDAOLocal;
import com.em.jpa.entity.Student;
@ViewScoped
@ManagedBean
public class StudentMB {
@EJB
private StudentDAOLocal studentDAOLocal;
private int id;
private String firstName;
private String lastName;
private String standerd;
public StudentMB() {
}
public void createStudent(){
Student student = new Student();
student.setFirstName("ExamsMyantraRemote");
student.setLastName("TutorialsRemote");
student.setStanderd("X");
studentDAOLocal.create(student);
}
public void updateStudent(){
Student student = new Student();
student.setId(id);
student.setFirstName(firstName);
student.setLastName(lastName);
student.setStanderd(standerd);
studentDAOLocal.update(student);
}
public void getStudent(int id){
Student student = studentDAOLocal.getStudent(id);
this.id = student.getId();
firstName = student.getFirstName();
lastName = student.getLastName();
standerd = student.getStanderd();
}
public void deleteStudent(int id){
studentDAOLocal.remove(id);
}
public List<Student> getAllStudents(){
return studentDAOLocal.getAllStudents();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getStanderd() {
return standerd;
}
public void setStanderd(String standerd) {
this.standerd = standerd;
}
}
In this class we have created four fields corresponding to four fields
of the Student entity. then we have created 5 methods which corresponds
to the 5 methods of the StudentDAO EJB we created in the previous section of this tutorial series(EJB Implementation using Local Interface). createStudent() creates a student object from the values from the form we are going to create on XHTML page and pass it on to the create() method of the EJB. similarly the updateStudent() object work to call update() method of EJB. getStudent()
populate the form when we want to edit an already existing Student
record, and Delete will invoke the remove method of the EJB. At last we
create the the getAllStudent() method which help us to retrieve all the values from database to create a table on the XHTML page.Next we are going to create an XHTML page which will use this Managed bean to let user operate on the student entity. For this we are creating an XHTML page by the name Student.xhtml. We will start by creating a blank xhtml template and add standard core library to the xml name space.
We have created the xhtml page and a form. In form there are three fields which corresponds to the fields of the JPA entity of the Student(Creating Entity using JPA+Hibernate). Next we have used the choose tags from the core library of JSTL to determine if this is new entry creation or current entry update. So we check if there is an already existing Id then display update button which on click invoke the updateStudent() entity. On the other end if this is new entry then invoke createStudent() on button click.



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<h:head>Students</h:head>
<h:body>
<h:form>
<div>
<h:outputLabel value="First Name" />
<h:inputText value="#{studentMB.firstName}" />
</div>
<div>
<h:outputLabel value="Last Name" />
<h:inputText value="#{studentMB.lastName}" />
</div>
<div>
<h:outputLabel value="Standerd" />
<h:inputText value="#{studentMB.standerd}" />
</div>
<div>
<c:choose>
<c:when test="#{studentMB.id > 0}">
<h:inputHidden value="#{studentMB.id}" />
<h:commandButton action="#{studentMB.updateStudent()}" value="Update" />
</c:when>
<c:otherwise>
<h:commandButton action="#{studentMB.createStudent()}" value="Create" />
</c:otherwise>
</c:choose>
</div>
</h:form>
<table border="solid" cellpadding="2" cellspacing="3">
<thead>
<th>Name</th>
<th>Standerd</th>
<th></th>
<th></th>
</thead>
<tbody>
<ui:repeat var="stud" value="#{studentMB.getAllStudents()}">
<tr>
<td>#{stud.firstName} #{stud.lastName}</td>
<td>#{stud.standerd}</td>
<td>
<h:form>
<h:commandLink action="#{studentMB.getStudent(stud.id)}" value="Edit" />
</h:form>
</td>
<td>
<h:form>
<h:commandLink action="#{studentMB.deleteStudent(stud.id)}" value="Delete" />
</h:form>
</td>
</tr>
</ui:repeat>
</tbody>
</table>
</h:body>
</html>
We are all set for the deployment and performing the CRUD operations on student entity.


EJB with Remote Interface Implementation
In this tutorial we will use the Remote Interface we created in last
tutorial, it is simple the structure of the remote Interface and class
that implements it is as follows.
As demonstrated in the article EJB with Local Interface Implementation,
the Injection does not work on the RemoteInterface implementation, Also
Remote EJB may be hosted on a different JVM than the JVM with the web
client. So there is requirement of the Context lookup. There is proper
tutorial for this lookup on the documentation of JBoss.
This tutorial is also based on the documentation tutorial on the Official JBoss Remote EJB lookup. The process is in two steps.
appName is the name of the ear file without .ear extension. This is the deployed name of the application. The moduleName is the name of the EJB module which contains the EJB classes and interfaces. The distinctName is the mapped name of the interface but if not specified in the code it may be left blank. Finally the Class name and the Interface name is in the last two values, it is to be noted that the fully classified class name is used for the Remote interface.
Next we need to create the properties file and add it to the application client classpath. In eclipse it can be created by right clicking the Web application and selecting Other then searching for the properties.
Here you need to specify the location for the property file, it is to
be noted that the property is to be added to the classpath of the client
class(ManagedBean). The name of the file should be jboss-ejb-client.properties The structure of the file is as follows:
Finally everything is set now we are creating a ManagedBean(Actually we are changing the managed bean class created in previous article of series).
package com.em.ejb.beans.interfaces;
import java.util.List;
import javax.ejb.Remote;
import com.em.jpa.entity.Student;
@Remote
public interface StudentDAORemote {
public Student create(Student student);
public Student update(Student student);
public void remove(int id);
public Student getStudent(int id);
public List<Student> getAllStudents();
}
package com.em.ejb.beans;
import java.util.List;
import com.em.ejb.beans.interfaces.StudentDAOLocal;
import com.em.ejb.beans.interfaces.StudentDAORemote;
import com.em.jpa.entity.Student;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
* Session Bean implementation class StudentDAO
*/
@Stateless
public class StudentDAO implements StudentDAORemote, StudentDAOLocal {
@PersistenceContext
private EntityManager em;
/**
* Default constructor.
*/
public StudentDAO() {
}
@Override
public Student create(Student student) {
em.persist(student);
return student;
}
@Override
public Student update(Student student) {
em.merge(student);
return student;
}
@Override
public void remove(int id) {
em.remove(getStudent(id));
}
@Override
public Student getStudent(int id) {
return em.find(Student.class, id);
}
@Override
public List<Student> getAllStudents() {
return em.createNamedQuery("Student.getAll", Student.class).getResultList();
}
}
When you will deploy this application you will notice that this class
and Interface are exposed with the JNDI, here is a sample of this
exposure of JNDI.java:global/DemoProject/DemoEJB/StudentDAO!com.em.ejb.beans.interfaces.StudentDAORemote java:app/DemoEJB/StudentDAO!com.em.ejb.beans.interfaces.StudentDAORemote java:module/StudentDAO!com.em.ejb.beans.interfaces.StudentDAORemote java:jboss/exported/DemoProject/DemoEJB/StudentDAO!com.em.ejb.beans.interfaces.StudentDAORemotePlease note that, when you declare an interface as remote and implement it in a class, that should be listed in the JNDI java:exported section of the wildfly.

This tutorial is also based on the documentation tutorial on the Official JBoss Remote EJB lookup. The process is in two steps.
- Create a Lookup method to perform EJB lookup using NamingContext.
- Set up a jboss-ejb-client properties. which holds the context properties.
package com.em.utils;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.em.ejb.beans.StudentDAO;
import com.em.ejb.beans.interfaces.StudentDAORemote;
public class Utils {
public static StudentDAORemote doLookup() throws NamingException{
final Hashtable jndiProperties = new Hashtable();
jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
final Context context = new InitialContext(jndiProperties);
final String appName = "DemoProject";
final String moduleName = "DemoEJB";
final String distinctName = "";
final String beanName = StudentDAO.class.getSimpleName();
final String viewClassName = StudentDAORemote.class.getName();
return (StudentDAORemote) context.lookup("ejb:" + appName + "/" + moduleName + "/" + distinctName + "/" + beanName + "!" + viewClassName);
}
}
So with this code we have completed first step. This is notable step.
Please note the first line of the doLookup() after declaration of a
hashtable. The first property put in the hashtable is URL_PKG_PREFIXES
and as a parameter the client naming is passed. This is to tell the
lookup to use the naming proxy for the EJB lookup and to use the naming
context properties in order to perform the lookup.appName is the name of the ear file without .ear extension. This is the deployed name of the application. The moduleName is the name of the EJB module which contains the EJB classes and interfaces. The distinctName is the mapped name of the interface but if not specified in the code it may be left blank. Finally the Class name and the Interface name is in the last two values, it is to be noted that the fully classified class name is used for the Remote interface.


remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED=false remote.connections=default remote.connection.default.host=localhost remote.connection.default.port = 8080 remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false remote.connection.default.username=administrator remote.connection.default.password=secureIn the properties and values the first entry tells if secure port is to be used. Second connection tells the number of remote connections. then the host and port where the EJB is hosted and then if the security policy is enforced or not, followed by the username and password for the remote access authentication.
Finally everything is set now we are creating a ManagedBean(Actually we are changing the managed bean class created in previous article of series).
package com.em.managedbeans;
import java.util.List;
import com.em.utils.Utils;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import com.em.ejb.beans.interfaces.StudentDAORemote;
import com.em.jpa.entity.Student;
@ViewScoped
@ManagedBean
public class StudentMB {
public StudentMB() {
}
public void createStudent(){
StudentDAORemote studentDAORemote = Utils.doLookup();
Student student = new Student();
student.setFirstName("ExamsMyantraRemote");
student.setLastName("TutorialsRemote");
student.setStanderd("X");
studentDAORemote.create(student);
}
}
In this we have used the static method from Utils class to obtain the
lookup and on the basis of that we are invoking the create(Student
student) method from StudentDAO class. To demonstrate the working of the
Bean we are invoking the method from the index.xhtml.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head></h:head>
<h:body>
Hello World!
#{studentMB.createStudent()}
</h:body>
</html>
This is how we can use the Remote EJB lookup to work with the EJBs. In
the next tutorial we are going to create a working view for CRUD of the
Student entities. We will use Entity, EJB, ManagedBean and JSF view to
achieve the result.
EJB with Local Interface Implementation
In this part we are going to create stateless Session Bean.
And we are going to implement two Interfaces, Local and Remote, these
Interfaces are used to provide a client side implementation of the EJB.
To create Stateless Session bean, you can annotate the class with @Stateless annotation and the Interfaces with @Local and @Remote as per required implementation.
Eclipse Provide an easy way to automate the process. For this, right click the EJB Project and New > Session Bean. This opens up an wizard here, enter the Class name and package name. Then uncheck no interface view and check Local and Remote.
You can specify the Name of interfaces here if required, otherwise
system provide the default name for these interfaces. In our case these
names were.
Package Name: com.em.ejb.beans
Class Name: StudentDAO
Package Name for Interfaces: com.em.ejb.beans.interfaces
Local Interface: StudentDAOLocal
Remote Interface: StudentDAORemote
Now before populating the bean class we need to populate the Interface, later on we will implement these methods in the bean class. so In the interfaces we are declaring curd methods for Student entity. The interfaces looks like this.
Now we are going to define the client side for the EJB access. We are going to use injection of EJB Local into the Managed Bean and we'll use managed beans to use the StudentDAO methods we define. And because we are only demonstrating the access of EJB we will only create a test method to test the working on EJB. So we create a Java class and annotate it with the @ManagedBean and @ViewScoped annotation. We are using the @EJB annotation to inject StudentDAOLocal interface and obtain a reference to StudentDAO. the test bean looks like this.
Note:@EJB injection is a post construct injection, if you try to access it inside the constructor, it will not work, as the StudentDAOLocal will remain null at that time, so it will throw NullPointerException.
Following is the code of our index.xhtml page which is only invoking the method. This will invoke the createStudent() method which will add an entry in the database.



Class Name: StudentDAO
Package Name for Interfaces: com.em.ejb.beans.interfaces
Local Interface: StudentDAOLocal
Remote Interface: StudentDAORemote
Now before populating the bean class we need to populate the Interface, later on we will implement these methods in the bean class. so In the interfaces we are declaring curd methods for Student entity. The interfaces looks like this.
package com.em.ejb.beans.interfaces;
import java.util.List;
import javax.ejb.Local;
import com.em.jpa.entity.Student;
@Local
public interface StudentDAOLocal {
public Student create(Student student);
public Student update(Student student);
public void remove(int id);
public Student getStudent(int id);
public List<Student> getAllStudents();
}
package com.em.ejb.beans.interfaces;
import java.util.List;
import javax.ejb.Remote;
import com.em.jpa.entity.Student;
@Remote
public interface StudentDAORemote {
public Student create(Student student);
public Student update(Student student);
public void remove(int id);
public Student getStudent(int id);
public List<Student> getAllStudents();
}
Now we are ready to define the StudentDAO class, in
this class we will implement both these interfaces, but in this tutorial
we will use only Local Interface, Remote interface we will use in next
part. the StudentDAO structure is implemented like this.
package com.em.ejb.beans;
import java.util.List;
import com.em.ejb.beans.interfaces.StudentDAOLocal;
import com.em.ejb.beans.interfaces.StudentDAORemote;
import com.em.jpa.entity.Student;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
* Session Bean implementation class StudentDAO
*/
@Stateless
public class StudentDAO implements StudentDAORemote, StudentDAOLocal {
@PersistenceContext
private EntityManager em;
/**
* Default constructor.
*/
public StudentDAO() {
}
@Override
public Student create(Student student) {
em.persist(student);
return student;
}
@Override
public Student update(Student student) {
em.merge(student);
return student;
}
@Override
public void remove(int id) {
em.remove(getStudent(id));
}
@Override
public Student getStudent(int id) {
return em.find(Student.class, id);
}
@Override
public List<Student> getAllStudents() {
return em.createNamedQuery("Student.getAll", Student.class).getResultList();
}
}
As you can see in the code above we have used the reference of the EntityManager with annotation @PersistenceContext, this enables us to use the container managed transaction easily. We have defined the interface method to perform the CRUD operations. Please not that in the last method we have used the NamedQuery that we defined in JPA entity, this makes easy to get all entries from student database.Now we are going to define the client side for the EJB access. We are going to use injection of EJB Local into the Managed Bean and we'll use managed beans to use the StudentDAO methods we define. And because we are only demonstrating the access of EJB we will only create a test method to test the working on EJB. So we create a Java class and annotate it with the @ManagedBean and @ViewScoped annotation. We are using the @EJB annotation to inject StudentDAOLocal interface and obtain a reference to StudentDAO. the test bean looks like this.
package com.em.managedbeans;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import com.em.ejb.beans.interfaces.StudentDAOLocal;
import com.em.jpa.entity.Student;
@ViewScoped
@ManagedBean
public class StudentMB {
@EJB
private StudentDAOLocal studentDAOLocal;
public StudentMB() {
}
public void createStudent(){
Student student = new Student();
student.setFirstName("ExamsMyantraLocal");
student.setLastName("TutorialsLocal");
student.setStanderd("X");
studentDAOLocal.create(student);
}
}
We have our test method createStudent() and we have
created a Student object and filled it with sample values, and now we
are going to use studentDAOLocal refrence to invoke the create method of
StudentDAO and this will persist our sample Student object into the
database. But to invoke the mehtod in managed bean we need a jsf page.
we are not going to use our defualt index.xhtml page because we are not doing much except invoking a method.Note:@EJB injection is a post construct injection, if you try to access it inside the constructor, it will not work, as the StudentDAOLocal will remain null at that time, so it will throw NullPointerException.
Following is the code of our index.xhtml page which is only invoking the method. This will invoke the createStudent() method which will add an entry in the database.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head></h:head>
<h:body>
Hello World!
#{studentMB.createStudent()}
</h:body>
</html>
This will not output anything on the page, but will add the entity in
the database. This is it for this part. In next part of this tutorial we
will come back with the detailed and step by step way of how you can
operate with the Remote interface implementation. We will demonstrate
the JNDI based lookup operation on RemoteInterface.