Mostrando postagens com marcador Eclipse. Mostrar todas as postagens
Mostrando postagens com marcador Eclipse. Mostrar todas as postagens

domingo, 16 de outubro de 2011

Exemplo CRUD Spring com JDBC Template e Servlet/JSP

Neste post, vamos estudar um dos Frameworks que é líder no mercado em aplicações JEE.
Estou falando do Spring Framework, que foi desenvolvido por Rod Johnson, e é mantido pela empresa 
Interface21. Este Framework oferece vários benefícios, possui módulos bem diversificados e pode 
ser usado em diversos cenários.
No nosso caso, vamos focar em um dos principais recursos do Spring que é o container de IoC 
(Inversion of Control), que também é conhecido como DI (Dependency Injection), a idéia da DI 
é de separar uma Interface da classe que a implementa, nos exemplos de DI deste tutorial será 
aplicado a injeção através de métodos Setter, mais também pode ser injetado com Construtor.
Através da Injeção de Dependência, facilitará em ligar a camada de persistência de dados 
com a camada de negócio e consequentemente com a camada de controller, deixando ambas as camadas 
desacopladas entre si.
Além da DI que o Spring ofere, iremos usar o JDBCTemplate para manipular os dados da camada de 
persistência, este template possui vários métodos utilitários para trabalhar com JDBC, e o mesmo 
já fica encarregado de abrir/fechar conexão, statement e result, apenas vamos precisar de um 
Data Source para trabalhar com as querys.
A camada de controller e apresentação, será feita com Servlet/JSP, mostrando assim, como o Spring 
é bem modular e que integra facilmente nossas camadas.
Para o exemplo será usado o Eclipse Indigo, TomCat 6, Banco de Dados Derby e o Spring 2.5.6,  para baixar o framework, acesse: http://www.springsource.org/download, baixe a versão full, com todos as dependências.
Ao final do post, o projeto está disponível para download, com todas as libs necessárias.


Segue o modelo da estrutura do projeto:


1. Passo: Vamos criar nossa classe modelo, que se chamará Pessoa:
 package model;  
 public class Pessoa {  
      private int id;  
      private String nome;  
      public Pessoa() {  
           super();  
      }  
      public Pessoa(String nome) {  
           super();            
           this.nome = nome;  
      }  
      public int getId() {  
           return id;  
      }  
      public void setId(int id) {  
           this.id = id;  
      }  
      public String getNome() {  
           return nome;  
      }  
      public void setNome(String nome) {  
           this.nome = nome;  
      }  
      @Override  
      public String toString() {  
           return "Pessoa [id=" + id + ", nome=" + nome + "]";  
      }  
 }  
Pessoa.java

2. Passo: Agora vamos criar a Interface DAO.
 package dao;  
 import java.util.List;  
 import model.Pessoa;  
 public interface PessoaDAO {  
      void insert(Pessoa pessoa);  
      List<Pessoa> select();   
      void delete(int id);  
 }  

PessoaDAO.java

3. Passo: Nesta classe, vamos implementar os métodos de contrato da Interface, além disto, teremos um método que será responsável por criar a tabela PESSOA, no banco de dados Derby, (as configurações do banco, data source, etc..., será explicada daqui alguns instantes.). Deve-se ressaltar, que o atributo jdbcTemplate do tipo JdbcTemplate, é responsável por manipular os dados nessa camada de persistência, observe-se que não instanciamos o objeto com new, apenas teremos que ter o método setter deste atributo, para que o container do Spring, posso se encarregar de fazer a injeção de dependência.
 package dao;  
 import java.util.ArrayList;  
 import java.util.List;  
 import java.util.Map;  
 import model.Pessoa;  
 import org.springframework.dao.DataAccessException;  
 import org.springframework.jdbc.core.JdbcTemplate;  
 public class PessoaDAOImp implements PessoaDAO {  
      private JdbcTemplate jdbcTemplate;  
      @SuppressWarnings("unused")  
      private void init() {  
           StringBuilder sb = new StringBuilder();  
           sb.append("CREATE TABLE pessoa (");  
           sb.append("id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (");  
           sb.append("START WITH 1, INCREMENT BY 1),");  
           sb.append(" nome VARCHAR(50),");  
           sb.append(" CONSTRAINT primary_key PRIMARY KEY (id))");  
           try {  
                jdbcTemplate.execute(sb.toString());  
                insert(new Pessoa("Jabes Felipe"));  
           } catch (DataAccessException e) {                 
 //               jdbcTemplate.execute("drop table autor ");  
                e.printStackTrace();  
           }  
      }  
      @Override  
      public void insert(Pessoa pessoa) {  
           jdbcTemplate.update("INSERT INTO pessoa (nome) VALUES (?) ", new Object[]{pessoa.getNome()});  
      }  
      @SuppressWarnings("unchecked")  
      @Override  
      public List<Pessoa> select() {                      
           List<Map<String, Object>> list = jdbcTemplate.queryForList("SELECT id, nome FROM pessoa");  
           List<Pessoa> pessoas = new ArrayList<Pessoa>(list.size());  
           for (Map<String, Object> map : list) {                 
                Pessoa pessoa = new Pessoa();  
                pessoa.setId(Integer.parseInt(map.get("ID").toString()));  
                pessoa.setNome(map.get("NOME").toString());  
                pessoas.add(pessoa);  
           }  
           return pessoas;  
      }  
      @Override  
      public void delete(int id) {  
           jdbcTemplate.update("DELETE FROM pessoa WHERE id=?", new Object[]{id});            
      }  
      public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {  
           this.jdbcTemplate = jdbcTemplate;  
      }       
 }  

PessoaDAOImp.java


4. Passo: Vamos criar a camada de serviço, definimos a Interface.
 package service;  
 import java.util.List;  
 import model.Pessoa;  
 public interface PessoaService {  
      void insert(Pessoa pessoa);  
      List<Pessoa> select();  
      void delete(int id);  
 }  

PessoaService.java


5. Passo: Classe que implementa a Interface de serviço, vale apena ressaltar, que a referência PessoaDAO que um atributo pessoaDAO, será injetado pelo Spring através do método Setter que criamos.

 package service;  
 import java.util.List;  
 import model.Pessoa;  
 import dao.PessoaDAO;  
 public class PessoaServiceImp implements PessoaService {  
      private PessoaDAO pessoaDAO;  
      @Override  
      public void insert(Pessoa pessoa) {  
           pessoaDAO.insert(pessoa);  
      }  
      @Override  
      public List<Pessoa> select() {  
           return pessoaDAO.select();  
      }  
      @Override  
      public void delete(int id) {  
           pessoaDAO.delete(id);            
      }  
      public void setPessoaDAO(PessoaDAO pessoaDAO) {  
           this.pessoaDAO = pessoaDAO;  
      }  
 }  

PessoaServiceImp.java


6. Passo: Já criamos nossa camada de persistência e de serviço, agora vamos criar um Servlet que será nosso controller da camada de tela e serviço.
 package servlets;  
 import java.io.IOException;  
 import javax.servlet.ServletException;  
 import javax.servlet.http.HttpServlet;  
 import javax.servlet.http.HttpServletRequest;  
 import javax.servlet.http.HttpServletResponse;  
 import model.Pessoa;  
 import org.springframework.beans.factory.annotation.Autowired;  
 import org.springframework.web.context.support.SpringBeanAutowiringSupport;  
 import service.PessoaService;  
 import service.PessoaServiceImp;  
 public class PessoaServlet extends HttpServlet {  
      private static final long serialVersionUID = 1L;  
      @Autowired   
      private PessoaService pessoaService;  
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
           SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);  
           String acao = request.getParameter("acao");  
           if ("salvar".equals(acao)) {  
                Pessoa pessoa = new Pessoa();  
                pessoa.setNome(request.getParameter("nome"));  
                pessoaService.insert(pessoa);  
           } else if ("excluir".equals(acao)) {  
                int id = Integer.parseInt(request.getParameter("id"));  
                pessoaService.delete(id);  
           }  
           request.setAttribute("pessoas", pessoaService.select());  
           getServletConfig().getServletContext().getRequestDispatcher("/home.jsp").forward(request,response);  
      }  
      public void setAutorService(PessoaServiceImp pessoaService) {  
           this.pessoaService = pessoaService;  
      }  
 }  

PessoaServlet.java

7. Passo: Agora vamos configurar as definições necessárias do Spring no arquivo 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>Spring</display-name>  
  <welcome-file-list>    
   <welcome-file>index.jsp</welcome-file>    
  </welcome-file-list>  
  <!-- Define os arquivos de configuracoes XML para o contexto Spring -->  
  <context-param>  
   <param-name>contextConfigLocation</param-name>  
   <param-value>/WEB-INF/applicationContext.xml</param-value>  
  </context-param>  
  <!-- Inicializa o Spring Web Application Context -->  
  <listener>  
   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  </listener>  
  <!-- Ativa os escopos web para os beans no Spring -->  
  <listener>  
   <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>  
  </listener>  
  <servlet>  
   <description></description>  
   <display-name>PessoaServlet</display-name>  
   <servlet-name>PessoaServlet</servlet-name>  
   <servlet-class>servlets.PessoaServlet</servlet-class>  
  </servlet>  
  <servlet-mapping>  
   <servlet-name>PessoaServlet</servlet-name>  
   <url-pattern>/PessoaServlet</url-pattern>  
  </servlet-mapping>  
 </web-app>  

web.xml

8. Passo: Agora chegou, a parte mais importante, que é o arquivo de configuração dos beans, contexto e datasource do Spring. Neste arquivo está configurado o Data Source que contém as informações do banco, o jdbcTemplate que contém uma referência ao dataSource, também configuramos os properties do banco e por fim, temos a definição de pessoaDAO e pessoaService.
 <?xml version="1.0" encoding="UTF-8"?>  
 <!--  
  - Application context definition for JPetStore's business layer.  
  - Contains bean references to the transaction manager and to the DAOs in  
  - dataAccessContext-local/jta.xml (see web.xml's "contextConfigLocation").  
  -->  
 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
           xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"  
           xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee"  
           xmlns:tx="http://www.springframework.org/schema/tx"  
           xsi:schemaLocation="  
                http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd  
                http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd  
                http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd  
                http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">  
      <bean id="pessoaService" class="service.PessoaServiceImp" lazy-init="false" scope="singleton">  
           <property name="pessoaDAO" ref="pessoaDAO" />  
      </bean>  
      <bean id="pessoaDAO" class="dao.PessoaDAOImp" init-method="init" lazy-init="false" scope="singleton">  
           <property name="jdbcTemplate" ref="jdbcTemplate" />  
      </bean>  
      <!-- arquivo properties -->  
      <context:property-placeholder location="classpath:resources/jdbc.properties" />  
      <!-- Config. datasource -->  
      <bean id="dataSource"   
            class="org.apache.commons.dbcp.BasicDataSource"   
            destroy-method="close"  
            p:driverClassName="${jdbc.driverClassName}"   
            p:url="${jdbc.url}"   
            p:username="${jdbc.username}"  
            p:password="${jdbc.password}" />  
      <!-- Transaction manager for a single JDBC DataSource (alternative to JTA) -->  
      <bean id="transactionManager"   
         class="org.springframework.jdbc.datasource.DataSourceTransactionManager"  
            p:dataSource-ref="dataSource"/>  
      <!-- JDBC template -->  
      <bean  
           id="jdbcTemplate"  
           class="org.springframework.jdbc.core.JdbcTemplate"  
           lazy-init="false">  
                <property name="dataSource" ref="dataSource" />  
                <property name="lazyInit" value="false" />  
      </bean>  
 </beans>  

applicationContext.xml


9. Passo: Segue informações do banco de dados Derby, que estão contidas em um arquivo de properties.
 # Properties file with JDBC settings.  
 #  
 # Applied by <context:property-placeholder location="jdbc.properties"/> from  
 # various application context XML files (e.g., "applicationContext-*.xml").  
 # Targeted at system administrators, to avoid touching the context XML files.  
 #-------------------------------------------------------------------------------  
 jdbc.driverClassName=org.apache.derby.jdbc.EmbeddedDriver  
 jdbc.hostname=localhost  
 jdbc.database=spring  
 jdbc.username=spring  
 jdbc.password=spring  
 jdbc.port=3306  
 jdbc.url=jdbc\:derby\:directory\:${jdbc.database}ExemploDB;create\=true  


10. Passo: Segue as telas jsp.
 <% response.sendRedirect("./PessoaServlet"); %>  

index.jsp

 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  
 <%@ 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>SPRING</title>  
 <script type="text/javascript">  
 function validar() {  
      var nome = document.getElementById("nome");  
      if (nome == null || nome.value == '') {  
           alert("Nome obrigatorio!");   
           return false;            
      } else {            
            return true;  
      }  
 }  
 </script>  
 </head>  
 <body>  
      <form action="./PessoaServlet" method="get" onsubmit="return validar();">  
           <table>  
                <tr>  
                     <td>Nome:</td>  
                     <td><input id="nome" name="nome" type="text"></td>  
                </tr>  
                <tr>  
                     <td colspan="2"><input name="acao" type="hidden" value="salvar" />  
                          <input type="submit" value="salvar" />  
                     </td>  
                </tr>  
           </table>  
           <br />  
           <table>  
                <tr>  
                     <td>ID</td>  
                     <td>Nome</td>  
                     <td>Excluir</td>  
                </tr>  
                <c:forEach var="pessoa" items="${pessoas}">  
                     <tr>  
                          <td><c:out value="${pessoa.id}" /></td>  
                          <td><c:out value="${pessoa.nome}" /></td>  
                          <td><a href="./PessoaServlet?acao=excluir&id=${pessoa.id}">Excluir</a>  
                          </td>  
                     </tr>  
                </c:forEach>  
           </table>  
      </form>  
 </body>  
 </html>  

home.jsp

Exemplo da tela:



Para quem quiser baixar o projeto desenvolvido, clique aqui.
Qualquer dúvida, crítica ou sugestão, fico à disposição.

domingo, 15 de maio de 2011

Utilizando EJB2 com Client Servlet e Swing (Parte 2)

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.

domingo, 17 de abril de 2011

Utilizando EJB2 com Client Servlet e Swing (Parte 1)

Olá Pessoal,

Com a chegada do EJB3, ficou bem mais simples, desenvolver aplicações que usam Session Bean e Entity, devido a utilização das Annotations, evitando de ficar configurando arquivos XMLs. Entretanto, existe várias aplicações no mercado que utilizam o uso de EJB2, por este motivo, resolvi criar este post, que tem como objetivo, mostrar, como que desenvolve uma aplicação em EJB2 que servirá como nosso modelo, e para utilizar este serviço, iremos usar 2 maneiras, uma usando Servlet e a outra Swing para acessar o EJB2.
Este post terá 2 partes, essa primeira, será o desenvolvimento da camada EJB2 e a segunda parte, criaremos um Client Servlet e Swing. Para o desenvolvimento do projeto, irei utilizar Java 1.6, Eclipse e o JBoss 4.

1. Passo: Vejamos a estrutura da camada de EJB:



2. Passo: Crie um projeto chamado ExemploEJB2 do tipo EJB no Eclipse, neste projeto vamos criar duas Interfaces (Remote e Home) e um SessionBean.

Primeiro criamos a Interface Remote e declaramos nosso método de serviço, neste exemplo é bem simples, teremos um método para mostrar o nome de uma Pessoa.

package com.blogpost.jabesfelipe.service;

import java.rmi.RemoteException;
import javax.ejb.EJBObject;

public interface Hello extends EJBObject {

public String showName(String name) throws RemoteException;

}
Hello.java

Criamos a Interface Home:

package com.blogpost.jabesfelipe.service;

import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome

public interface HelloHome extends EJBHome {

public Hello create() throws RemoteException, CreateException;

}
HelloHome.java

Agora criamos nosso SessionBean e iremos implementar nosso método que foi declarado na Interface:

package com.blogpost.jabesfelipe.service;

import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;

public class HelloBean implements SessionBean {

public String showName(String name) {
return "Meu nome é " + name + "!";
}

public void ejbCreate() throws CreateException {
System.out.println("Bean criado");
}

@Override
public void ejbActivate() throws EJBException, RemoteException {
System.out.println("Bean ativado");
}

@Override
public void ejbPassivate() throws EJBException, RemoteException {
System.out.println("Bean desativado");
}

@Override
public void ejbRemove() throws EJBException, RemoteException {
System.out.println("Bean removido");
}

@Override
public void setSessionContext(SessionContext arg0) throws EJBException,
RemoteException {}

}
HelloBean.java

3. Passo: Agora vamos configurar (name, state, etc...) do EJB no arquivo ejb-jar.xml que fica dentro da pasta META-INF.
O arquivo vai ficar conforme o modelo abaixo:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
<ejb-jar id="ejb-jar_ID">
<display-name>ExemploEJB2</display-name>

<enterprise-beans>
<session>
<display-name>HelloBean</display-name>
<ejb-name>HelloBean</ejb-name>
<home>com.blogpost.jabesfelipe.service.HelloHome</home>
<remote>com.blogpost.jabesfelipe.service.Hello</remote>
<ejb-class>com.blogpost.jabesfelipe.service.HelloBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Bean</transaction-type>
</session>
</enterprise-beans>

</ejb-jar>
ejb-jar.xml

4. Passo: Vamos criar um arquivo jboss.xml dentra da pasta META-INF, e neste arquivo definimos o nome da JNDI que irá acessar o EJB.

<?xml version='1.0' encoding='UTF-8' ?>
<jboss>

<enterprise-beans>
<session>
<ejb-name>HelloBean</ejb-name>
<jndi-name>HelloBean</jndi-name>
</session>
</enterprise-beans>

</jboss>
jboss.xml

5. Passo: O nosso EJB está pronto, agora crie um projeto chamado ExemploEJB2-ear do tipo EAR, e vamos configurar o módulo EJB no arquivo application.xml que fica dentro da pasta META-INF.

<?xml version="1.0" encoding="UTF-8"?>
<application xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:application="http://java.sun.com/xml/ns/javaee/application_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_5.xsd" id="Application_ID" version="5">
<display-name>ExemploEJB2-ear</display-name>
<module>
<ejb>ExemploEJB2.jar</ejb>
</module>
</application>

Bom galera, nossa camada de EJB, está pronta, e na próxima parte do tutorial, vamos testa-lá, usando Servlet e Swing.
Qualquer dúvida, crítica ou segestão, fico à disposição.

sábado, 27 de novembro de 2010

Simples Exemplo Struts

Olá Pessoal,

Depois de um bom tempo, sem publicar um post, irei mostrar, como criar uma simples aplicação web, usando o FrameWork Struts 1.3. Para quem não conhece, o Struts é um framework open-source do projeto Jakarta, ele possibilita o desenvolvimento de aplicacões web, atuando como um Controller no padrão MVC e também oferece suporte na camada View, para a construção de páginas JSP através de custom tags.
O exemplo deste post é simples, teremos um formulário para preencher os dados de uma Pessoa, se a idade desta pessoa for maior de 18 anos, encaminhamos para uma página de sucesso, caso contrário, encaminhamos para uma página de falha. O projeto foi desenvolvido, usando o Eclipse + JBoss.
O Struts pode ser baixado no site http://struts.apache.org/download.cgi.
Ao final do post, o projeto será disponibilizado para download, com as libs, já inclusa.
1. Passo: Estrutura do projeto:


2. Passo: Crie uma Classe, chamada Pessoa:
package com.blogspot.jabesfelipe.struts.bean;

public class Pessoa {

private String nome;
private int idade;
private float altura;
private char sexo;

public String getNome() {
return nome;
}

public void setNome(String nome) {
this.nome = nome;
}

public int getIdade() {
return idade;
}

public void setIdade(int idade) {
this.idade = idade;
}

public float getAltura() {
return altura;
}

public void setAltura(float altura) {
this.altura = altura;
}

public char getSexo() {
return sexo;
}

public void setSexo(char sexo) {
this.sexo = sexo;
}

}
Pessoa.java

3. Passo: Crie uma Classe, chamada PessoaFormBean, ela vai extender da Classe ActionForm, os form-beans se integram a um formulário de entrada de dados.
package com.blogspot.jabesfelipe.struts.formbean;

import org.apache.struts.action.ActionForm;
import com.blogspot.jabesfelipe.struts.bean.Pessoa;

public class PessoaFormBean extends ActionForm {

/**
*
*/
private static final long serialVersionUID = -759773695806534156L;
private Pessoa pessoa = new Pessoa();

public Pessoa getPessoa() {
return pessoa;
}

}
PessoaFormBean.java

4. Passo: Crie uma Classe, chamada PessoaAction, ela vai extender da Classe Action, e vamos sobrescrever o método execute, que funciona como um método main, esta Classe irá funcionar como o nosso Controller, o método execute, irá retornar um ActionForward, o mapeamento, será configurado no arquivo struts-config.xml.
package com.blogspot.jabesfelipe.struts.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.blogspot.jabesfelipe.struts.bean.Pessoa;
import com.blogspot.jabesfelipe.struts.formbean.PessoaFormBean;

public class PessoaAction extends Action {

public static final String SUCESSO = "sucesso";
public static final String FALHA = "falha";
public static final String PESSOA = "pessoa";

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {

Pessoa pessoa = ((Pessoa) ((PessoaFormBean) form).getPessoa());
boolean podeEntrar = false;

if (pessoa.getIdade() >= 18) {
podeEntrar = true;
}
request.setAttribute(PESSOA, pessoa);

return podeEntrar ? mapping.findForward(SUCESSO) : mapping.findForward(FALHA);
}

}
PessoaAction.java

5. Passo: Vamos criar nossas páginas JSPs, crie uma página index.jsp:
<%@taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>

<logic:forward name="index" />
index.jsp

6. Passo: Crie um JSP, para o formulário:
<%@taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html:html>
<head>
<html:base/>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Simples Exemplo Struts</title>
</head>
<body>
<html:form focus="pessoa.nome" action="/PessoaAction.do" method="POST">
Nome: <html:text property="pessoa.nome" /><br />
Idade: <html:text property="pessoa.idade" /><br />
Altura: <html:text property="pessoa.altura" /><br />
Sexo: <html:radio property="pessoa.sexo" value="M" />Masculino
<html:radio property="pessoa.sexo" value="F" />Feminino<br /><br />
<html:submit value="Ok"/>
</html:form>
</body>
</html:html>
formulario.jsp

7. Passo: Crie, agora a página de sucesso:
<%@taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html:html>
<head>
<html:base/>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Simples Exemplo Struts</title>
</head>
<body>
<bean:define id="pessoa" name="pessoa" scope="request" />
Olá <bean:write name="pessoa" property="nome"/>, SEJA BEM VINDO!!! <br />
Sexo:
<logic:equal value="M" name="pessoa" property="sexo">Masculino</logic:equal>
<logic:equal value="F" name="pessoa" property="sexo">Feminino</logic:equal>
<br /><br />
<br />
<html:link action="/Index.do">sair...</html:link>
</body>
</html:html>
sucesso.jsp

8. Passo: Crie, agora a página de falha:
<%@taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html:html>
<head>
<html:base />
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Simples Exemplo Struts</title>
</head>
<body>
<bean:define id="pessoa" scope="request" name="pessoa" />
Olá <bean:write name="pessoa" property="nome" />.
<br />
<br />
VOCÊ É MENOR DE IDADE E NÃO PODE ENTRAR!!!
<br />
<html:link action="/Index.do">voltar...</html:link>
</body>
</html:html>
falha.jsp

9. Passo: Agora, precisamos configurar o struts no arquivo 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>struts-exemplo</display-name>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

</web-app>
web.xml

10. Passo: A configuração do arquivo struts-config, incluindo as as definições dos beans,
e os mapeamento das actions:
<?xml version="1.0" encoding="UTF-8"?>

<struts-config>
<!-- FORWARDS GLOBAL -->
<global-forwards>
<forward name="index" path="/Index.do" />
</global-forwards>

<form-beans>

<!-- FORM PESSOA -->
<form-bean name="PessoaFormBean" type="com.blogspot.jabesfelipe.struts.formbean.PessoaFormBean" />

</form-beans>


<action-mappings>

<!-- PAGINA INICIAL -->
<action path="/Index" include="/formulario.jsp" scope="request" />
<action name="PessoaFormBean" type="com.blogspot.jabesfelipe.struts.action.PessoaAction"
path="/PessoaAction" scope="request">
<forward name="sucesso" path="/sucesso.jsp"/>
<forward name="falha" path="/falha.jsp"/>
</action>

</action-mappings>

</struts-config>
struts-config.xml

11. Passo: A aplicação rodando, preenchendo o formulário:

Caso seja sucesso:
Se for falha:

Bom galera, este foi um exemplo de como criar uma simples aplicação web com FrameWork Struts.
Para quem quiser baixar o exemplo, clique aqui.
Qualquer dúvida, crítica ou sugestão, fico à disposição.

Jabes Felipe RSS Feed Jabes Felipe