Olá Pessoal,
Continuando nosso projeto em EJB2, neste post, vamos criar dois tipos de Client, o primeiro será um projeto web, que vai usar Servlet, o segundo será uma aplicação em Swing, ambos os projetos irão acessar nosso EJB2 por meio do recurso de JNDI.
Uma das grandes vantagens do EJB, é o reuso do código, assim, nossa camada de negócio, poderá ser usada, em diversos tipo de Client.
Ao final deste post, deixarei o projeto completo para download.
1. Passo: Vamos criar um projeto web chamado ExemploEJB-web, nesse projeto, crie um Servlet chamado HelloServlet, lembrando que é necessário adicionar o projeto ExemploEJB2 em Project References, e não esqueça de adionar este projeto como módulo Web no arquivo application.xml que está no projeto EAR.
package com.blogpost.jabesfelipe.servlets;
import java.io.IOException;import java.io.PrintWriter;import javax.ejb.CreateException;import javax.naming.Context;import javax.naming.InitialContext;import javax.naming.NamingException;import javax.rmi.PortableRemoteObject;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.blogpost.jabesfelipe.service.Hello;import com.blogpost.jabesfelipe.service.HelloHome;
public class HelloServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Context initial = new InitialContext(); Object objref = initial.lookup("HelloBean"); HelloHome home = (HelloHome) PortableRemoteObject.narrow(objref, HelloHome.class); Hello remote = home.create();
PrintWriter out = response.getWriter(); out.println(remote.showName("Jabes Felipe"));
} catch (NamingException e) { e.printStackTrace(); } catch (CreateException e) { e.printStackTrace(); } } }HelloServlet.java
Para poder testar nossa aplicação, digite a seguinte URL http://localhost:8080/ExemploEJB2-web/HelloServlet.
2. Passo: Vamos agora, criar um projeto java, chamado ExemploEJB2-swing, crie uma classe HelloSwing, nessa classe, temos um simples JFrame, composto por um campo Texto e Botão, na ação deste botão, vamos chamar nosso método no EJB e ele retornará um valor em String em um componente JOptionPane.
Lembrando que é necessário adicionar o projeto ExemploEJB2 em Project References.
package com.blogpost.jabesfelipe.swing;
import java.rmi.RemoteException;import java.util.Properties;import javax.ejb.CreateException;import javax.naming.Context;import javax.naming.InitialContext;import javax.naming.NamingException;import javax.rmi.PortableRemoteObject;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JTextField;import com.blogpost.jabesfelipe.service.Hello;import com.blogpost.jabesfelipe.service.HelloHome;
public class HelloSwing extends JFrame {
public HelloSwing() { initComponents(); }
public static void main(String[] args) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new HelloSwing().setVisible(true); } }); }
private void initService() { try {
Properties t = new Properties(); t.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory"); t.put(Context.PROVIDER_URL, "jnp://localhost:1099"); Context context = new InitialContext(t); Object objref = context.lookup("HelloBean"); HelloHome home = (HelloHome) PortableRemoteObject.narrow(objref, HelloHome.class); Hello remote = home.create();
JOptionPane.showMessageDialog(null, remote.showName(jTxtFldName.getText().toString()));
} catch (NamingException e) { e.printStackTrace(); } catch (CreateException e) { e.printStackTrace(); } catch (RemoteException e) { e.printStackTrace(); } }
private void jBtOKActionPerformed(java.awt.event.ActionEvent evt) { initService(); }
private void initComponents() {
jLblName = new javax.swing.JLabel(); jTxtFldName = new javax.swing.JTextField(); jBtOK = new javax.swing.JButton(); jLblTitle = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLblName.setText("Informe seu Nome: ");
jBtOK.setText("OK"); jBtOK.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBtOKActionPerformed(evt); } });
jLblTitle.setFont(new java.awt.Font("Courier 10 Pitch", 1, 18)); // NOI18N jLblTitle.setText("Exemplo - Chamando Serviço EJB2 em Swing");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout( getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup( layout.createSequentialGroup() .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING) .addGroup( layout.createSequentialGroup() .addGap(25, 25, 25) .addComponent( jLblName) .addGap(1, 1, 1) .addComponent( jTxtFldName, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent( jBtOK)) .addGroup( layout.createSequentialGroup() .addContainerGap() .addComponent( jLblTitle))) .addContainerGap( javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))); layout.setVerticalGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup( javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(jLblTitle) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE) .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLblName) .addComponent( jTxtFldName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jBtOK)) .addGap(24, 24, 24))); pack(); }
private JButton jBtOK; private JLabel jLblName; private JLabel jLblTitle; private JTextField jTxtFldName;
}Agora só testar nosso projeto, veja como ficou:
Bom galera, enfim, terminamos nosso projeto, que na primeira parte, criamos nosso camada de EJB2 e na segunda criamos um projeto web e Swing para acessar o EJB.
Para quem quiser baixar todos os projeto desenvolvidos, clique aqui.
Qualque dúvida, crítica ou sugestão, fico à disposição.
10:26
Jabes Felipe




