Ajuda Struts 2 + Hibernate (INICIANTE)
Pessoal iniciei meus estudos com STRUTS + HIBERNATE, porém estou com alguns problemas, gostaria de uma ajuda:
PROBLEMA 1:
Não aparece os estados cadastrados em meu banco de dados MySQL.
PROBLEMA2:
Quando clica em Salvar aparece a seguinte mensagem:
HTTP Status 404 - /ObrasWeb/gravar
type Status report
message /ObrasWeb/gravar
description The requested resource (/ObrasWeb/gravar) is not available.
Apache Tomcat/6.0.26
PROBLEMA3:
Percebi que ao iniciar o tomcat aparece a mensagem:
02/08/2010 22:30:34 org.apache.struts2.components.Form evaluateExtraParamsServletRequest
WARNING: No configuration found for the specified action: 'gravar' in namespace: ''. Form action defaulting to 'action' attribute's literal value. Segue os Fontes: Gostaria de saber o que está errado. É um cadastro de estados bem simples. Estado package br.com.obrasweb.modelo; import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table; @Entity
@Table(name="estado")
public class Estado implements Serializable { private static final long serialVersionUID = -8767337896773261247L; private int codigo;
private String sigla; @Id
@GeneratedValue
@Column(name="codigo")
public int getCodigo() {
return codigo;
} @Column(name="sigla")
public String getSigla() {
return sigla;
} public void setCodigo(int codigo) {
this.codigo = codigo;
} public void setSigla(String sigla) {
this.sigla = sigla;
}
}
EstadoControle package br.com.obrasweb.controler; import br.com.obrasweb.modelo.Estado;
import br.com.obrasweb.util.HibernateUtil;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.classic.Session; public class EstadoControle extends HibernateUtil { // Método Gravar
public Estado gravar(Estado estado) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.save(estado);
session.getTransaction().commit();
return estado;
} // Método Apagar
public Estado apagar(int codigo) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Estado estado = (Estado) session.load(Estado.class, codigo);
if (null != estado) {
session.delete(estado);
}
session.getTransaction().commit();
return estado;
} // Método Listar
public List<Estado> list() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List<Estado> estados = null;
try {
estados = (List<Estado>) session.createQuery("from Estado").list();
} catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
session.getTransaction().commit();
return estados;
}
}
EstadoAction package br.com.obrasweb.view; import br.com.obrasweb.controler.EstadoControle;
import br.com.obrasweb.modelo.Estado;
import com.opensymphony.xwork2.ActionSupport;
import java.util.List; public class EstadoAction extends ActionSupport { private static final long serialVersionUID = 9149826260758390091L;
private Estado estado;
private List<Estado> estadoLista;
private int codigo;
private EstadoControle linkController; public EstadoAction() {
linkController = new EstadoControle();
} public String execute() {
if (null != estado) {
linkController.gravar(getEstado());
}
this.estadoLista = linkController.list();
System.out.println(estadoLista);
System.out.println(estadoLista.size());
return SUCCESS;
} public String gravar() {
System.out.println(getEstado());
try {
linkController.gravar(getEstado());
} catch (Exception e) {
e.printStackTrace();
}
return SUCCESS;
} public String apagar() {
linkController.apagar(getCodigo());
return SUCCESS;
} public Estado getEstado() {
return estado;
} public List<Estado> getEstadoLista() {
return estadoLista;
} public void setEstado(Estado estado) {
this.estado = estado;
} public void setEstadoLista(List<Estado> estadoLista) {
this.estadoLista = estadoLista;
} public int getCodigo() {
return codigo;
} public void setCodigo(int codigo) {
this.codigo = codigo;
}
} HibernateUtil package br.com.obrasweb.util; import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
} public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
hibernate.cfg.xml <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/obrasdb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.show_sql">true</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="hbm2ddl.auto">update</property>
<mapping class="br.com.obrasweb.modelo.Estado" />
</session-factory>
</hibernate-configuration> WEB.XML <?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>Struts Blank</display-name> <filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter> <filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list> </web-app> STRUTS.XML <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devMode" value="true" /> <package name="obrasweb" namespace="/" extends="struts-default"> <action name="gravar"
class="br.com.obrasweb.view.EstadoAction" method="gravar">
<result name="success" type="chain">index.jsp</result>
<result name="input" type="chain">index.jsp</result>
</action> <action name="estadoLista" class="br.com.obrasweb.view.EstadoAction"
method="estadoLista">
<result>index.jsp</result>
</action>
<action name="apagar"
class="br.com.obrasweb.view.EstadoAction" method="apagar">
<result name="success" type="chain">index.jsp</result>
<result name="input" type="chain">index.jsp</result>
</action> <action name="index"
class="br.com.obrasweb.view.EstadoAction">
<result name="success">index.jsp</result>
</action> </package> </struts>
ARQUIVO index.jsp <%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<style>
body, input{
font-family: Calibri, Arial;
}
table#contact {
border-collapse: collapse;
width:550px;
}
th {
height: 40px;
background-color: #ffee55;
}
</style>
<title>TESTE</title>
</head>
<body> <h1>Cadastro de Estado</h1>
<s:actionerror/> <s:form action="gravar" method="post">
<s:textfield name="estado.codigo" label="Código"/>
<s:textfield name="estado.descricao" label="Descrição"/>
<s:submit value="Gravar" align="center"/>
</s:form>
<h2>Estados</h2>
<table id="estado" border="1">
<tr>
<th>Código</th>
<th>Descrição</th>
<th>Ação</th> </tr>
<s:iterator value="estadoLista" id="estado">
<tr>
<td><s:property value="codigo"/></td>
<td><s:property value="descricao"/></td>
<td><a href="apagar?codigo=<s:property value="codigo"/>">Apagar</a></td>
</tr>
</s:iterator> </table>
</body>
</html> ----------------------------------------------------------------------------- Muito Obrigado! Renato
WARNING: No configuration found for the specified action: 'gravar' in namespace: ''. Form action defaulting to 'action' attribute's literal value. Segue os Fontes: Gostaria de saber o que está errado. É um cadastro de estados bem simples. Estado package br.com.obrasweb.modelo; import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table; @Entity
@Table(name="estado")
public class Estado implements Serializable { private static final long serialVersionUID = -8767337896773261247L; private int codigo;
private String sigla; @Id
@GeneratedValue
@Column(name="codigo")
public int getCodigo() {
return codigo;
} @Column(name="sigla")
public String getSigla() {
return sigla;
} public void setCodigo(int codigo) {
this.codigo = codigo;
} public void setSigla(String sigla) {
this.sigla = sigla;
}
}
EstadoControle package br.com.obrasweb.controler; import br.com.obrasweb.modelo.Estado;
import br.com.obrasweb.util.HibernateUtil;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.classic.Session; public class EstadoControle extends HibernateUtil { // Método Gravar
public Estado gravar(Estado estado) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.save(estado);
session.getTransaction().commit();
return estado;
} // Método Apagar
public Estado apagar(int codigo) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Estado estado = (Estado) session.load(Estado.class, codigo);
if (null != estado) {
session.delete(estado);
}
session.getTransaction().commit();
return estado;
} // Método Listar
public List<Estado> list() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List<Estado> estados = null;
try {
estados = (List<Estado>) session.createQuery("from Estado").list();
} catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
session.getTransaction().commit();
return estados;
}
}
EstadoAction package br.com.obrasweb.view; import br.com.obrasweb.controler.EstadoControle;
import br.com.obrasweb.modelo.Estado;
import com.opensymphony.xwork2.ActionSupport;
import java.util.List; public class EstadoAction extends ActionSupport { private static final long serialVersionUID = 9149826260758390091L;
private Estado estado;
private List<Estado> estadoLista;
private int codigo;
private EstadoControle linkController; public EstadoAction() {
linkController = new EstadoControle();
} public String execute() {
if (null != estado) {
linkController.gravar(getEstado());
}
this.estadoLista = linkController.list();
System.out.println(estadoLista);
System.out.println(estadoLista.size());
return SUCCESS;
} public String gravar() {
System.out.println(getEstado());
try {
linkController.gravar(getEstado());
} catch (Exception e) {
e.printStackTrace();
}
return SUCCESS;
} public String apagar() {
linkController.apagar(getCodigo());
return SUCCESS;
} public Estado getEstado() {
return estado;
} public List<Estado> getEstadoLista() {
return estadoLista;
} public void setEstado(Estado estado) {
this.estado = estado;
} public void setEstadoLista(List<Estado> estadoLista) {
this.estadoLista = estadoLista;
} public int getCodigo() {
return codigo;
} public void setCodigo(int codigo) {
this.codigo = codigo;
}
} HibernateUtil package br.com.obrasweb.util; import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
} public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
hibernate.cfg.xml <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/obrasdb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.show_sql">true</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="hbm2ddl.auto">update</property>
<mapping class="br.com.obrasweb.modelo.Estado" />
</session-factory>
</hibernate-configuration> WEB.XML <?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>Struts Blank</display-name> <filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter> <filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list> </web-app> STRUTS.XML <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devMode" value="true" /> <package name="obrasweb" namespace="/" extends="struts-default"> <action name="gravar"
class="br.com.obrasweb.view.EstadoAction" method="gravar">
<result name="success" type="chain">index.jsp</result>
<result name="input" type="chain">index.jsp</result>
</action> <action name="estadoLista" class="br.com.obrasweb.view.EstadoAction"
method="estadoLista">
<result>index.jsp</result>
</action>
<action name="apagar"
class="br.com.obrasweb.view.EstadoAction" method="apagar">
<result name="success" type="chain">index.jsp</result>
<result name="input" type="chain">index.jsp</result>
</action> <action name="index"
class="br.com.obrasweb.view.EstadoAction">
<result name="success">index.jsp</result>
</action> </package> </struts>
ARQUIVO index.jsp <%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<style>
body, input{
font-family: Calibri, Arial;
}
table#contact {
border-collapse: collapse;
width:550px;
}
th {
height: 40px;
background-color: #ffee55;
}
</style>
<title>TESTE</title>
</head>
<body> <h1>Cadastro de Estado</h1>
<s:actionerror/> <s:form action="gravar" method="post">
<s:textfield name="estado.codigo" label="Código"/>
<s:textfield name="estado.descricao" label="Descrição"/>
<s:submit value="Gravar" align="center"/>
</s:form>
<h2>Estados</h2>
<table id="estado" border="1">
<tr>
<th>Código</th>
<th>Descrição</th>
<th>Ação</th> </tr>
<s:iterator value="estadoLista" id="estado">
<tr>
<td><s:property value="codigo"/></td>
<td><s:property value="descricao"/></td>
<td><a href="apagar?codigo=<s:property value="codigo"/>">Apagar</a></td>
</tr>
</s:iterator> </table>
</body>
</html> ----------------------------------------------------------------------------- Muito Obrigado! Renato
Renato Vieira
Curtidas 0
Respostas
Dyego Carmo
02/08/2010
o seu pacote padrao do struts deve extender "struts-defaults" , caso não extenda a sua aplicação não vai mapear as ações de forma correta !
GOSTEI 0
Carlos Mazzi
02/08/2010
funcionou assim?
GOSTEI 0
Dyego Carmo
02/08/2010
é...
Funcionou hehehe ?
Funcionou hehehe ?
GOSTEI 0