20 de dez. de 2007

Quem quer dinheiro???

A info divulgou agora em Dezembro uma pesquisa um tanto interessante, com dados da Manager Assessoria em Recursos Humanos. Eu acho que você merece um aumento! Confira aqui

12 de dez. de 2007

Curso Struts - Aula 03

tiles-defs.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE tiles-definitions PUBLIC  
        "-//Apache Software Foundation//DTD Tiles Configuration 1.3//EN"  
        "http://struts.apache.org/dtds/tiles-config_1_3.dtd">

<tiles-definitions>
 <definition name="homepage" template="/jsp/layouts/layout.jsp">
  <put name="title" value="Livraria Web" />
  <put name="header" value="/jsp/layouts/banner.jsp" />
  <put name="menu" value="/jsp/layouts/common_menu.jsp" />
  <put name="body" value="/jsp/layouts/home_body.jsp" />
  <put name="footer" value="/jsp/layouts/credits.jsp" />
 </definition>

 <!-- Livros -->
 <definition name="listarLivros" extends="homepage">
  <put name="body" value="/jsp/livro/listar.jsp" />
 </definition>

 <definition name="formularioLivros" extends="homepage">
  <put name="body" value="/jsp/livro/criar.jsp" />
 </definition>

 <!-- Usuarios -->
 <definition name="listarUsuarios" extends="homepage">
  <put name="body" value="/jsp/usuario/listar.jsp" />
 </definition>

 <definition name="formularioUsuarios" extends="homepage">
  <put name="body" value="/jsp/usuario/formulario.jsp" />
 </definition>

 <!-- Login -->
 <definition name="loginUsuario" extends="homepage">
  <put name="body" value="/jsp/login/login.jsp" />
 </definition>
</tiles-definitions>
/jsp/layouts/layout.jsp
<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
<head>
  <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
  <title><tiles:getAsString name="title" /></title>
  <link rel="stylesheet" type="text/css" href="<%=request.getContextPath() %>/stylesheets/scaffold.css"/>

</head>
<body>
    <div id="page">
        <div id="header">
         <tiles:insert name="header" />
        </div>
        <hr class="hidden" />
      <div id="main">
        <div id="content-wrapper">
          <div id="content">
             <tiles:insert name="body" />
          </div>
        </div>
        <div id="sidebar-wrapper">
         <tiles:insert name="menu" />
        </div>
      </div>
        <hr class="hidden" />
        <div id="footer">
         <tiles:insert name="footer" />
        </div>
    </div>
  </body>
</html>
struts-config.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
          "http://struts.apache.org/dtds/struts-config_1_3.dtd">

<struts-config>

 <!-- Definicao dos Formulario de Beans -->
 <form-beans>
  <form-bean name="livroForm"
   type="br.com.livrariaweb.controle.LivroForm" />
  <form-bean name="usuarioForm"
   type="br.com.livrariaweb.controle.UsuarioForm" />
 </form-beans>

 <!-- Definicao de Excecoes Globais -->
 <global-exceptions></global-exceptions>

 <!-- Definicao de Redirecionamento Global -->
 <global-forwards>
  <forward name="homepage" path="/homepage.do" />
 </global-forwards>

 <!-- Mapeamento de Acoes -->
 <action-mappings>

  <action path="/homepage"
   type="br.com.livrariaweb.controle.HomeAction">
   <forward name="homepage" path="homepage" />
  </action>

  <!-- Cadastro de Livros -->
  <action path="/formularioLivros" forward="formularioLivros" />

  <action path="/salvarLivro"
   type="br.com.livrariaweb.controle.LivroSalvarAction" name="livroForm"
   scope="request" input="formularioLivros">
   <forward name="listar" path="/listarLivros.do"
    redirect="true" />
  </action>

  <action path="/listarLivros"
   type="br.com.livrariaweb.controle.LivroAction">
   <forward name="listar" path="listarLivros" />
  </action>

  <!-- Cadastro de Usuários -->
  <action path="/formularioUsuarios" forward="formularioUsuarios" />

  <action path="/listarUsuarios"
   type="br.com.livrariaweb.controle.UsuarioAction" name="usuarioForm"
   scope="request" input="formularioUsuarios" parameter="metodo"
   validate="true">
   <forward name="listar" path="listarUsuarios" />
   <forward name="formulario" path="formularioUsuarios" />
  </action>

  <!-- Login e Logout -->
  <action path="/login" forward="loginUsuario" />

  <action path="/autenticar"
   type="br.com.livrariaweb.controle.LoginAction" name="usuarioForm"
   scope="request" input="loginUsuario" validate="true">
   <forward name="homepage" path="/homepage.do" />
  </action>

  <action path="/sair"
   type="br.com.livrariaweb.controle.LogoutAction" scope="request">
   <forward name="homepage" path="homepage" />
  </action>

  <!-- Comprar -->
  <action path="/comprar"
   type="br.com.livrariaweb.controle.ComprarAction">
   <forward name="homepage" path="homepage" />
  </action>
 </action-mappings>

 <!-- Arquivo de Definicao de Mensagens -->
 <message-resources parameter="mensagem" />

 <plug-in className="org.apache.struts.tiles.TilesPlugin">
  <set-property property="definitions-config"
   value="/WEB-INF/tiles-defs.xml" />
 </plug-in>

</struts-config>

9 de dez. de 2007

Curso Struts - Aula 02

Para essa nova aula precisamos de uma nova biblioteca: struts-extras-1.3.8.jar br.com.livrariaweb.entidades.Usuario
package br.com.livrariaweb.entidades;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Usuario {

 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 private Integer id;

 @Column(nullable = false)
 private String login;

 @Column(nullable = false)
 private String nome;

 @Column(nullable = false)
 private String senha;

       //gets e sets
br.com.livrariaweb.servico.UsuarioServico
package br.com.livrariaweb.servico;

import java.util.List;

import org.hibernate.Session;

import br.com.livrariaweb.entidades.Usuario;
import br.com.livrariaweb.util.HibernateUtil;

public class UsuarioServico {

 public List listar() {
  return HibernateUtil.getSession().createCriteria(Usuario.class).list();
 }

 public Usuario carregar(Integer id) {
  return (Usuario) HibernateUtil.getSession().load(Usuario.class, id);
 }

 public void salvar(Usuario usuario) {
  Session s = HibernateUtil.getSession();
  s.beginTransaction();
  if (usuario.getId() == 0)
   s.save(usuario);
  else
   s.update(usuario);
  s.getTransaction().commit();
  s.close();
 }

 public void excluir(Usuario usuario) {
  Session s = HibernateUtil.getSession();
  s.beginTransaction();
  s.delete(usuario);
  s.getTransaction().commit();
  s.close();
 }
}
br.com.livrariaweb.util.HibernateUtil
package br.com.livrariaweb.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {

 private static final SessionFactory sessionFactory;

 static {
  try {
   // Criando a SessionFactory apartir no hibernate.cfg.xml
   sessionFactory = new AnnotationConfiguration().configure()
     .buildSessionFactory();
  } catch (Throwable ex) {
   System.err.println("Não foi possivel criar a SessionFactory." + ex);
   throw new ExceptionInInitializerError(ex);
  }
 }

 public static Session getSession() {
  return sessionFactory.openSession();
 }

}
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>

 <session-factory>

       <!-- Database connection settings -->
       <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
       <property name="connection.url">jdbc:mysql://localhost/livrariaweb</property>
       <property name="connection.username">root</property>
       <property name="connection.password">root</property>
       <property name="connection.pool_size">1</property>

       <!-- SQL dialect -->
       <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

       <property name="show_sql">true</property>

       <property name="hbm2ddl.auto">update</property>

  <mapping class="br.com.livrariaweb.entidades.Livro"/>
  <mapping class="br.com.livrariaweb.entidades.Usuario"/>
  
 </session-factory>

</hibernate-configuration>
br.com.livrariaweb.controle.UsuarioAction
package br.com.livrariaweb.controle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import br.com.livrariaweb.entidades.Usuario;
import br.com.livrariaweb.servico.UsuarioServico;

public class UsuarioAction extends DispatchAction {

 private UsuarioServico servico = new UsuarioServico();

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

  request.setAttribute("usuarios", servico.listar());

  return mapping.findForward("listar");
 }

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

  Usuario u = ((UsuarioForm) form).getUsuario();
  servico.salvar(u);

  request.setAttribute("usuarios", servico.listar());

  return mapping.findForward("listar");
 }

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

  Integer id = Integer.valueOf(request.getParameter("idUsuario"));
  Usuario u = servico.carregar(id);

  ((UsuarioForm) form).setUsuario(u);

  return mapping.findForward("formulario");
 }

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

  Integer id = Integer.valueOf(request.getParameter("idUsuario"));
  Usuario u = servico.carregar(id);
  servico.excluir(u);

  request.setAttribute("usuarios", servico.listar());

  return mapping.findForward("listar");
 }
}
br.com.livrariaweb.controle.UsuarioForm
package br.com.livrariaweb.controle;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import br.com.livrariaweb.entidades.Usuario;

public class UsuarioForm extends ActionForm {

 private Usuario usuario = new Usuario();

 public Usuario getUsuario() {
  return usuario;
 }

 public void setUsuario(Usuario usuario) {
  this.usuario = usuario;
 }

 @Override
 public ActionErrors validate(ActionMapping mapping,
   HttpServletRequest request) {

  ActionErrors erros = new ActionErrors();
  if (usuario.getLogin() != null
    && usuario.getLogin().trim().length() == 0) {
   erros.add("usuario.login", new ActionMessage(
     "form.campoObrigatorio", "Login"));
  }
  if (usuario.getNome() != null && usuario.getNome().trim().length() == 0) {
   erros.add("usuario.nome", new ActionMessage(
     "form.campoObrigatorio", "Nome"));
  }
  if (usuario.getSenha() != null
    && usuario.getSenha().length() == 0) {
   erros.add("usuario.senha", new ActionMessage(
     "form.campoObrigatorio", "Senha"));
  }
  return erros;
 }

}
mensagem.properties
form.campoObrigatorio={0}: Campo Obrigatório
form.salvar=salvar
struts-config.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE struts-config PUBLIC
         "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
         "http://struts.apache.org/dtds/struts-config_1_3.dtd">

<struts-config>

 <!-- Definicao dos Formulario de Beans -->
 <form-beans>
  <form-bean name="livroForm"
   type="br.com.livrariaweb.controle.LivroForm" />
  <form-bean name="usuarioForm"
   type="br.com.livrariaweb.controle.UsuarioForm" />
 </form-beans>

 <!-- Definicao de Excecoes Globais -->
 <global-exceptions></global-exceptions>

 <!-- Definicao de Redirecionamento Global -->
 <global-forwards>
  <forward name="inicio" path="/Inicio.do" />
 </global-forwards>

 <!-- Mapeamento de Acoes -->
 <action-mappings>
  <action path="/Inicio" forward="/jsp/inicio.jsp" />

  <action path="/Livros"
   type="br.com.livrariaweb.controle.LivroAction">
   <forward name="listar" path="/jsp/livro/listar.jsp" />
  </action>

  <action path="/LivroSalvar"
   type="br.com.livrariaweb.controle.LivroSalvarAction" name="livroForm"
   scope="request" input="/jsp/livro/criar.jsp">
   <forward name="listar" path="/Livros.do" redirect="true" />
  </action>

  <action path="/usuario"
   type="br.com.livrariaweb.controle.UsuarioAction" name="usuarioForm"
   scope="request" input="/jsp/usuario/formulario.jsp"
   parameter="metodo" validate="true">
   <forward name="listar" path="/jsp/usuario/listar.jsp" />
   <forward name="formulario" path="/jsp/usuario/formulario.jsp" />
  </action>

 </action-mappings>

 <!-- Arquivo de Definicao de Mensagens -->
 <message-resources parameter="mensagem" />

</struts-config>
jsp/usuario/listar.jsp
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
<%@ taglib uri="http://struts.apache.org/tags-nested" prefix="nested"%>

<html:html>
<body>
<h1>Usuário</h1>
<table border="1" cellpadding="1">
 <tr>
  <th>Login</th>
  <th>Nome</th>
  <th>Senha</th>
 </tr>
 <logic:iterate id="u" name="usuarios">
  <tr>
   <td><bean:write name="u" property="login" /></td>
   <td><bean:write name="u" property="nome" /></td>
   <td><bean:write name="u" property="senha" /></td>
   <td><html:link action="/usuario.do">
    Editar
    <html:param name="idUsuario">
     <bean:write name="u" property="id" />
    </html:param>
    <html:param name="metodo">carregar</html:param>
   </html:link></td>
   <td><html:link action="/usuario.do">
    Excluir
    <html:param name="idUsuario">
     <bean:write name="u" property="id" />
    </html:param>
    <html:param name="metodo">excluir</html:param>
   </html:link></td>
  </tr>
 </logic:iterate>
</table>
<p><html:link href="jsp/usuario/formulario.jsp">Novo Usuário</html:link></p>
</body>
</html:html>
jsp/usuario/formulario.jsp
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
<%@ taglib uri="http://struts.apache.org/tags-nested" prefix="nested"%>

<html:html>
<body>
<h3 style="color: red;">
 <html:messages id="erro">
  <li><bean:write name="erro" /></li>
 </html:messages>
</h3>
<html:form action="/usuario.do" focus="usuario.login">
 <logic:present name="usuario">
  <h1>Editar Usuário</h1>
 </logic:present>
 <logic:notPresent name="usuario">
  <h1>Criar Usuário</h1>
 </logic:notPresent>
 <html:hidden property="usuario.id" />
 <p><b>Login:</b><br>
 <html:text property="usuario.login" /></p>
 <p><b>Nome:</b><br>
 <html:text property="usuario.nome" /></p>
 <p><b>Senha:</b><br>
 <html:password property="usuario.senha" /></p>

 <html:submit property="metodo">
  <bean:message key="form.salvar"/>
 </html:submit>
</html:form>
</body>
</html:html>

2 de dez. de 2007

Curso Struts - Aula 01

LivroAction.java
package br.com.livrariaweb.controle;

import java.util.List;

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 br.com.livrariaweb.entidades.Livro;
import br.com.livrariaweb.servico.LivroServico;

public class LivroAction extends Action {

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

 LivroServico servico = new LivroServico();
 List l = servico.listar();
 request.setAttribute("livros", l);
 return mapping.findForward("listar");
}
}
LivroAction.java
package br.com.livrariaweb.controle;

import org.apache.struts.action.ActionForm;

public class LivroForm extends ActionForm{

private static final long serialVersionUID = 1L;

private Integer id;

private String titulo;

private String autor;

private Integer nroEdicao;

private Double valor;

       // gets e sets
}
LivroSalvarAction.java
package br.com.livrariaweb.controle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
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 br.com.livrariaweb.entidades.Livro;
import br.com.livrariaweb.servico.LivroServico;

public class LivroSalvarAction extends Action {

public ActionForward execute(ActionMapping mapping, ActionForm form,
  HttpServletRequest request, HttpServletResponse response)
  throws Exception {
 Livro l = new Livro();
 BeanUtils.copyProperties(l, (LivroForm) form);
 LivroServico s = new LivroServico();
 s.salvar(l);
 return mapping.findForward("listar");
}
}
LivroAction.java
package br.com.livrariaweb.entidades;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Livro implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;

private String titulo;

private String autor;

private Integer nroEdicao;

private Double valor;

       // gets e sets
}
LivroServico.java
package br.com.livrariaweb.servico;

import java.util.List;

import org.hibernate.Session;

import br.com.livrariaweb.entidades.Livro;
import br.com.livrariaweb.util.HibernateUtil;

public class LivroServico {

public Livro salvar(Livro livro) {
 Session s = HibernateUtil.getSessionFactory().openSession();
 s.beginTransaction();
 s.save(livro);
 s.getTransaction().commit();
 s.close();
 return livro;
}

@SuppressWarnings("unchecked")
public List listar() {
 Session s = HibernateUtil.getSessionFactory().openSession();
 s.beginTransaction();
 List l = s.createCriteria(Livro.class).list();
 s.getTransaction().commit();
 s.close();
 return l;
}
}
HibernateUtil.java
package br.com.livrariaweb.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {

private static final SessionFactory sessionFactory;

static {
 try {
  // Criando a SessionFactory apartir no hibernate.cfg.xml
  sessionFactory = new AnnotationConfiguration().configure()
    .buildSessionFactory();
 } catch (Throwable ex) {
  System.err.println("Não foi possivel criar a SessionFactory." + ex);
  throw new ExceptionInInitializerError(ex);
 }
}

public static SessionFactory getSessionFactory() {
 return sessionFactory;
}

}
criar.jsp
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
<%@ taglib uri="http://struts.apache.org/tags-nested" prefix="nested"%>

<html:html>
<body>
<html:form action="/LivroSalvar.do" focus="titulo">
<h1>Criar Livro</h1>

<p><b>Título</b><br>
<html:text property="titulo"></html:text></p>
<p><b>Autor</b><br>
<html:text property="autor"></html:text></p>
<p><b>Número da Edição</b><br>
<html:text property="nroEdicao"></html:text></p>
<p><b>Valor</b><br>
<html:text property="valor"></html:text></p>
<html:submit>Salvar</html:submit>
</html:form>
</body>
</html:html>
listar.jsp
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
<%@ taglib uri="http://struts.apache.org/tags-nested" prefix="nested"%>

<html:html>
<body>
<h1>Livros</h1>
<table border="1" cellpadding="1">
<tr>
 <th>Titulo</th>
 <th>Autor</th>
 <th>Valor</th>
</tr>
<logic:iterate id="l" name="livros">
 <tr>
  <td><bean:write name="l" property="titulo" /></td>
  <td><bean:write name="l" property="autor" /></td>
  <td><bean:write name="l" property="valor" /></td>
 </tr>
</logic:iterate>
</table>
<p><html:link href="jsp/livro/criar.jsp" >Criar Livro</html:link></p>
</body>
</html:html>
inicio.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
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>Aplicacao Struts</title>
</head>
<body>
 Aplicacao Struts no Ar!
 <br>
 <a href="<%=request.getContextPath()%>/Livros.do">Livros</a>
</body>
</html>
index.jsp
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
<logic:redirect forward="inicio"/>
struts-config.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE struts-config PUBLIC
         "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
         "http://struts.apache.org/dtds/struts-config_1_3.dtd">

<struts-config>

<!-- Definicao dos Formulario de Beans -->
<form-beans>
 <form-bean name="livroForm"
  type="br.com.livrariaweb.controle.LivroForm" />
</form-beans>

<!-- Definicao de Excecoes Globais -->
<global-exceptions></global-exceptions>

<!-- Definicao de Redirecionamento Global -->
<global-forwards>
 <forward name="inicio" path="/Inicio.do" />
</global-forwards>

<!-- Mapeamento de Acoes -->
<action-mappings>
 <action path="/Inicio" forward="/jsp/inicio.jsp" />

 <action path="/Livros"
  type="br.com.livrariaweb.controle.LivroAction">
  <forward name="listar" path="/jsp/livro/listar.jsp" />
 </action>

 <action path="/LivroSalvar"
  type="br.com.livrariaweb.controle.LivroSalvarAction" name="livroForm"
  scope="request" input="/jsp/livro/criar.jsp">
  <forward name="listar" path="/Livros.do" redirect="true"/>
 </action>
</action-mappings>

<!-- Arquivo de Definicao de Mensagens -->
<message-resources parameter="MessageResources" />

</struts-config>
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<display-name>Aplicacao Struts</display-name>

<!-- Configuracoes do Strtuts -->
<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>2</load-on-startup>
</servlet>

<servlet-mapping>
 <servlet-name>action</servlet-name>
 <url-pattern>*.do</url-pattern>
</servlet-mapping>

<!-- Pagina Inicial -->
<welcome-file-list>
 <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

Resposta ao comentário do Renan:
Renan, esse é um assunto que iremos tratar na próxima aula. Até agora as nossas classes de ação elas herdam de "Action" mas temos uma outra classe também do struts que é chamada de "DispatchAction". Essa nova classe permite implementarmos diversos métodos dentro de uma única classe de ação. A assinatura do método vai ser a mesma para o método "execute".
Por exemplo:
public final class UsuarioAction extends DispatchAction {
public ActionForward novo (ActionMapping mapping, ActionForm form, 
            HttpServletRequest request, HttpServletResponse response) 
            throws Exception { 
        // sua acao... 
    } 
 
public ActionForward salva (ActionMapping mapping, ActionForm form, 
            HttpServletRequest request, HttpServletResponse response) 
           throws Exception { 
        // // sua acao... 
    } 
 
    public ActionForward edita (ActionMapping mapping, ActionForm form, 
            HttpServletRequest request, HttpServletResponse response) 
            throws Exception { 
        // // sua acao... 
    } 
 
} 

Só tem um detalhe o mapeamento da sua action vai precisar de mais um parametro, o "parameter":
<action path="/Usuario"
type="br.com.loteriaweb.controle.UsuarioAction"
name="usuarioForm"
scope="request"
input="/jsp/usuario/cria.jsp"
parameter="submit"/>

ele corresponde ao método que você vai acessar. Ou seja. no seu formulario vc precisa ter um campo hidden com nome de submit que informa a ação que será executada. Vc pode utilizar um javascript para controlar essa decisão. Não fico muito feliz quando tenho que utilizar javascript então na aula eu mostro uma dica boa.

1 de dez. de 2007

Struts – Aula01 – Tutorial de Configuração Básica

Configurando o ambiente

1. Copie e descompacte o eclipse-jee-europa-fall2-win32.zip no seu diretório de trabalho. http://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/20071103/eclipse-jee-europa-fall2-win32.zip 2. Copie e descompacte o apache-tomcat-5.5.25 em seu diretório de trabalho. http://mirrors.uol.com.br/pub/apache/tomcat/tomcat-5/v5.5.25/bin/apache-tomcat-5.5.25.zip 3. Copie e descompacte o struts-1.3.8 em seu diretório de trabalho. http://ftp.unicamp.br/pub/apache/struts/binaries/struts-1.3.8-all.zip

Configurando o Projeto

4. Inicie o eclipse e crie um novo projeto. File >> New >> Other >> Selecione Web >> Selecione >> Dynamic Web Project >> Next. Defina o nome do projeto e clique em Finish

5. Copie os arquivos abaixo para a pasta web\WEB-INF\lib do seu projeto struts-1.3.8\lib\antlr-2.7.2.jar struts-1.3.8\lib\commons-beanutils-1.7.0.jar struts-1.3.8\lib\commons-chain-1.1.jar struts-1.3.8\lib\commons-digester-1.8.jar struts-1.3.8\lib\commons-logging-1.0.4.jar struts-1.3.8\lib\commons-validator-1.3.1.jar struts-1.3.8\lib\oro-2.0.8.jar struts-1.3.8\lib\struts-core-1.3.8.jar struts-1.3.8\lib\struts-taglib-1.3.8.jar struts-1.3.8\lib\struts-tiles-1.3.8.jar

6. Crie o arquivo struts-config.xml em web\WEB-INF e insira o seguinte conteúdo: <?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd"> <struts-config> <!-- Definicao dos Formulario de Beans --> <form-beans></form-beans> <!-- Definicao de Excecoes Globais --> <global-exceptions></global-exceptions> <!-- Definicao de Redirecionamento Global --> <global-forwards> <forward name="inicio" path="/Inicio.do"/> </global-forwards> <!-- Mapeamento de Acoes --> <action-mappings> <action path="/Inicio" forward="/jsp/inicio.jsp"/> </action-mappings> <!-- Arquivo de Definicao de Mensagens --> <message-resources parameter="MessageResources" /> </struts-config>

7. Altere o arquivo web\WEB-INF\web.xml para que fique com as configurações do struts: <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <display-name>Aplicacao Struts</display-name> <!-- Configuracoes do Strtuts --> <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>2</load-on-startup> </servlet> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- Pagina Inicial --> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>

8. Crie o arquivo web\index.jsp com o seguinte conteúdo: <%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %> <logic:redirect forward="inicio"/>

9. Crie o arquivo web\jsp\index.jsp com o seguinte conteúdo: <%@ 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=UTF-8"> <title>Aplicacao Struts</title> </head> <body> Aplicacao Struts no Ar! </body> </html>

Executando

10. Selecione o projeto, no menu superior clique em Run >> Run As >> Run on Server Configure o TomCat indicando o local onde foi descompactado e execute a aplicação. Acesse o browser em HTTP://localhost:8080/seuprojeto/

Google