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 setsbr.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 Listbr.com.livrariaweb.util.HibernateUtillistar() { 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(); } }
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=salvarstruts-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>
Nenhum comentário:
Postar um comentário