Struts 2 não funciona!

Olá… estou estudando sobre o Struts 2 e preciso de um help… faço com o Struts 1, mas agora quero entender o 2 (sei q eh td diferente, WebWork etc…)

Bom, fiz o mapeamento no Struts.xml, coloquei ele na raiz das minhas classes (default package), fiz o listener no web.xml e escrevi os jsp’s de cadastro e saídas usando a taglib … pois bem, quando aperto no submit não funciona. Diz como se não encontrasse a classe action.

HTTP Status 404 - /ExStruts2/forms/clienteAction

type Status report

message /ExStruts2/forms/clienteAction

description The requested resource (/ExStruts2/forms/clienteAction) is not available.
Apache Tomcat/6.0.16

Verifiquei que ele pega forms/clienteAction… não estou entendendo… será que é a ordem dentro do projeto?

Aqui vão meus cods:
WEB.XML:

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" 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>ExStrtus2</display-name>
    
    <!-- Localiza o Resource application.properties  -->
    <context-param>
        <param-name>
            javax.servlet.jsp.jstl.fmt.localizationContext
        </param-name>
        <param-value>application</param-value>
    </context-param>
    
    <!-- Filtros necessários para o Struts 2  -->
    <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>

    <!-- Em caso de erro volta para principal  -->
    <error-page>
        <exception-type>java.lang.SecurityException</exception-type>
        <location>/forms/cadastro.jsp</location>
    </error-page>
    
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    
    <security-constraint>
        <display-name>Previnindo acesso direto a paginas JSP</display-name>
        <web-resource-collection>
            <web-resource-name>Raw-JSF-JSP-Pages</web-resource-name>
	     <!-- Adicione o caminho para cada arquivo .jsp  -->
            <url-pattern>/pages/ErrorPage.jsp</url-pattern>
            <url-pattern>/pages/SucessPage.jsp</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <description>Sem regras, apenas bloqueio acesso direto aos JSPs</description>
        </auth-constraint>
    </security-constraint>
</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>
    <!-- configs iniciais padrão do Struts 2 -->
    <constant name="struts.enable.DynamicMethodInvocation" value="true" />
    <constant name="struts.devMode" value="false" />

    <!-- mapeamento de minhas classes e respostas (forwards) -->
    <package name="jopss" namespace="/jopss" extends="struts-default">
        
        <action name="clienteAction" class="actions.ClienteAction">
            <result name="sucess">/pages/SucessPage.jsp</result>
            <result name="error">/pages/ErrorPage.jsp</result>
        </action>
        
    </package>
    
</struts>

IMPORT.JSP:

<%@ 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">
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

INDEX.JSP:

<%@include file="imports.jsp"%>

<html>
    <head>
        <META HTTP-EQUIV="Refresh" CONTENT="0;URL=forms/cadastro.jsp">
    </head>
    <body>
        <p>Loading ...</p>
        
    </body>
</html>

CADASTRO.JSP:

<%@include file="../imports.jsp"%>

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title><fmt:message key="form.title" /></title>
    </head>
    <body>
        <s:form action="clienteAction" method="post">
            
            <table>
                <tr>
                    <th colspan="2">
                        <fmt:message key="form.title" />
                    </th>
                </tr>
                <tr>
                    <td align="right"><fmt:message key="form.nomePrompt" />:</td>
                    <td align="left"><s:textfield name="nome" /></td>
                </tr>
                <tr>
                    <td align="right"><fmt:message key="form.enderecoPrompt" />:</td>
                    <td align="left"><s:textfield name="endereco" /></td>
                </tr>
                <tr>
                    <td align="right"><fmt:message key="form.telefonePrompt" />:</td>
                    <td align="left"><s:textfield name="telefone" /></td>
                </tr>
                <tr>
                    <td colspan="2" align="center">
                        <s:submit name="action" key="Enviar" method="gravar" />
                    </td>
                </tr>
            </table>
        </s:form>
    </body>
</html>

ERRORPAGE:

<%@include file="../imports.jsp"%>

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title><fmt:message key="error.title"/></title>
    </head>
    <body>
        
        <h2>
            <fmt:message key="error.title"/>
        </h2>
        
        <fmt:message key="error.subtitle"/><BR><BR>
        <fmt:message key="form.nomePrompt"/>: <s:property value="nome"/><BR>
        <fmt:message key="form.enderecoPrompt"/>: <s:property value="endereco"/><BR>
        <fmt:message key="form.telefonePrompt"/>: <s:property value="telefone"/><BR>
        <BR>
        
        <!-- <html:link forward="cadastro">Voutá</html:link> -->
    </body>
</html>

SUCESSPAGE:

<%@include file="../imports.jsp"%>

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title> <fmt:message key="sucess.title" /> </title>
    </head>
    <body>
        <h3>
            <fmt:message key="sucess.title"/>
        </h3>
        
        <fmt:message key="sucess.subtitle"/><BR><BR>
        <fmt:message key="form.nomePrompt"/>: <s:property value="nome"/><BR>
        <fmt:message key="form.enderecoPrompt"/>: <s:property value="endereco"/><BR>
        <fmt:message key="form.telefonePrompt"/>: <s:property value="telefone"/><BR>
        <BR>
        
        <!-- <html:link page="/ClienteAction.porco?operacao=limparVoltar">Nouvo Cadrasto</html:link>  -->
    </body>
</html>

CLIENTEACTION

package actions;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;
import beans.Cliente;
import com.opensymphony.xwork2.ActionSupport;

public class ClienteAction extends ActionSupport implements ServletRequestAware {

        private static final long serialVersionUID = 1L;
        
	private HttpServletRequest request;
	private Cliente cliente;
	
	public Cliente getCliente() {
		return cliente;
	}
	public void setCliente(Cliente cliente) {
		this.cliente = cliente;
	}

	public String gravar() throws Exception {

		if(cliente.getNome()!=null){
			if(cliente.getNome().trim().equals("")){
				return ERROR;
			}
		}
		if(cliente.getEndereco()!=null){
			if(cliente.getEndereco().trim().equals("")){
				return ERROR;
			}
		}
		if(cliente.getTelefone()!=null){
			if(cliente.getTelefone().trim().equals("")){
				return ERROR;
			}
		}

		System.out.println("Gravoooooooo...");

		return SUCCESS;
	}
	
	//retorna o request, se precisar usar
	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

}

CLIENTE:

package beans;

import java.io.Serializable;

public class Cliente implements Serializable{
    
        private static final long serialVersionUID = 1L;
	private String nome;
	private String endereco;
	private String telefone;

	public String getNome() {
		return nome;
	}
	public void setNome(String nome) {
		this.nome = nome;
	}
	public String getEndereco() {
		return endereco;
	}
	public void setEndereco(String endereco) {
		this.endereco = endereco;
	}
	public String getTelefone() {
		return telefone;
	}
	public void setTelefone(String telefone) {
		this.telefone = telefone;
	}
 
}

Já tentei e td geito e nao achei o erro. Baixei um exemplo CRUD do Struts2 e estou seguindo ele… parece que está igual. Tanto que pego as libs de lá tbm… está no classpath normal e não ocorre erros.

Gostaria de solucionar estes problemas:
– fazer funcionar!! :lol:
– como faço para redirecionar do index para minha pag principal com strus 2 ?? (forward do struts 1) Como podem ver faço por html mesmo…
– como faço para redirecionar para meu cadastro quando aparecer a pagina de erros ou sucesso? Note que está comentado o link do struts 1 que fazia isso, como faço com struts 2 ??

Abraços e peço-lhes um help…

jopss

Tente sobreescrever o método “execute” em sua action só para testar.

É algo como:

public String execute() throws Exception{
   return SUCCESS;
}

Olá… fiz oq disse e ocorre o mesmo erro 404… deixei secão:

package actions;

import com.opensymphony.xwork2.ActionSupport;

public class ClienteAction extends ActionSupport {

    private static final long serialVersionUID = 1L;

    public String execute() throws Exception {
        return SUCCESS;
    }
}

e nada… aff faz 3 dias q to nessa…

jopss :x

Olá,

Tente tirar o namespace do seu struts.xml (namespace="/jopss") ou entao coloca-la em seu link/form.

[]´s

Coloca mais uma action chamando a pagina de cadastro que vai funcionar…

   [code] &lt;action name="clienteAction" class="actions.ClienteAction"&gt;
        &lt;result name="sucess"&gt;/pages/SucessPage.jsp&lt;/result&gt;
        &lt;result name="error"&gt;/pages/ErrorPage.jsp&lt;/result&gt;
    &lt;/action&gt;
    
      &lt;action name="cadastro"&gt;
        &lt;result&gt;/forms/cadastro.jsp&lt;/result&gt;
    &lt;/action&gt;[/code]

depois chama ela …
cadastro.action

este problema foi resolvido?

estou tendo o mesmo problema…

eu tbm estou com o mesmo problema e pelo jeito não foi resolvido!!! Estou começando agora com struts, primeiro contato até com o struts 2.

Estou usando Eclipse Ganymede. com o plugin sysdeo para o tomcat e rodo a aplicação do eclipse com o run->> server…

Estou seguindo o tutorial do http://struts.apache.org/2.0.11.2/docs/bootstrap.html

com o mesmo web.xml , struts.xml na pasta src, HelloWorld.java no pacote tutorial, HelloWorld.jsp. Coloquei os .Jar na pasta do projeto e fiz o buid path no eclipse.

Olha meus arquivos

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" 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>
	Struts2</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
	<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>
</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><!-- Configuration for the default package. -->
	<package name="default" extends="struts-default"></package>
	<package name="tutorial" extends="struts-defaut">
		<action  name="HelloWorld" class="tutorial.HelloWorld">
            <result>/HelloWorld.jsp</result>
        </action>
	</package>
</struts>

HelloWorld.java

<?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><!-- Configuration for the default package. -->
	<package name="default" extends="struts-default"></package>
	<package name="tutorial" extends="struts-defaut">
		<action  name="HelloWorld" class="tutorial.HelloWorld">
            <result>/HelloWorld.jsp</result>
        </action>
	</package>
</struts>

HelloWorld.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!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>The Simple Hello World</title>
</head>
<body>
 <h2><s:property value="message" /></h2>
</body>
</html>

Alguém pode me ajudar?

só pra constar.

Refiz todo o tutorial do inicio e funcionou!

Não me pergunte o que foi que tinha dado errado! :lol: :wink:

msmo assim vlw!

leanblanh,

eu fiz igual você… só que o meu ainda não funcionou… eu achei estranho você deixars os arquivos nas pastas como você citou. Sua mensagem: com o mesmo web.xml , struts.xml na pasta src, HelloWorld.java no pacote tutorial, HelloWorld.jsp. Coloquei os .Jar na pasta do projeto e fiz o buid path no eclipse.

O web.xml e o struts ficam dentro de web-inf, certo?
Que .jar você disse que colocou na pasta do projeto? do struts eu já coloquei…
Você pode me ajudar?

joca faz o seguinte

Segue este tutorial aki http://struts.apache.org/2.0.11.2/docs/simple-setup.html

e vê o que dá qualquer coisa posta aki denovo vlw?

Cara esqueci de te dizer!! roda um blank do struts primeiro

Baixa aki: http://ftp.unicamp.br/pub/apache/struts/examples/struts2-blank-2.0.14.war

copia o War no teu tomCat em ->> \webapps

Agora vc abre localhost:8080/struts2-blank-2.0.11.2

vai aparecer um loading… e depois pra vc escolher entre english e spanish… PRONTO!!!

agora segue o primeiro link que te passei!! e todo o tutorial até o helloworld http://struts.apache.org/2.0.11.2/docs/hello-world.html

qualquer coisa e só dizer

O arquivo struts-blank coloco no diretório web-app do tomcat?