[Resolvido]Struts 1.3.10 + Ajax

15 respostas
C

Galera é possivel desenvolver Ajax com Struts 1.3.10??
Alguem já fez isso? Eu tenho um sistema que em algumas paginas chega a ter 4 forms. E o cliente nao quer ver o refresh das paginas toda hora que for acionar um form, por isso estou tentando aplicar Ajax pra fazer a chamada e preencher apenas o que é preciso. Porem nao estou obtendo sucesso :frowning:
A alteração de struts 1 p/ struts 2 nesta altura do campeonato é complicada e em todos os tutoriais que li em nenhum explica como posso passar os dados da mesma maneira que em forms via Ajax.

Por favor me ajudem

Abs

15 Respostas

A

cara…é possível sim usar ajax com Struts 1…
mas vc tem que fazer via JS, tipo na mão mesmo… e como vc falou que tem vários forms, é bem provavel que
fique bem trabalhoso…
vc te que fazer usando XMLHttpRequest, no site do w3schools http://www.w3schools.com/ajax/ajax_intro.asp explica…
mas procura no google ai que tem bastante coisa…
eu ja cheguei a ver algumas lib prontas… mas nunca usei… e tb não lembro onde vi…

J

Eu fiz isso em um sistema com struts 1.2, mas não foi do form inteiro somente de 1 ou 2 campos, no retorno de seus metodos voce não usa mapping.findForward(“same”) para voltar para a mesma tela.

Use o retorno do metodo em html mesmo.

response.setContentType("text/html");  
      response.setHeader("Cache-Control", "no-cache");  
      java.io.PrintWriter out = response.getWriter();  
        
      out.println("Retorno <b>HTML</b> de action do Struts");          
      out.flush();

Imagino que com o recurso serializeArray() do jquery voce consegue passas os valores da tela para o metodo java via struts e unir as 2 coisas.

R

Amigo!

Mto simples, infelizmente tenho q usar struts 1 no trampo, em projetos pessoais uso VRaptor 3.

Para fazer ajax com struts 1 é muito simples:


http://api.jquery.com/category/ajax/

Espero ter ajudado

abrazzzzzzzzzz

C

Entao cara eu vi esse exmplo e outros mais. Ta dificil heim …

Olha só meu jsp … nesses combos de select eu chamo o ajax passando a url e o nome (ja tendei o id) do form

<html:form action="/igreja" styleId="frm2">
 <input type="text" id="idIgreja" name="igreja.id" style="visibility: hidden"/>
  <tr>			
   <td><div align="right">Matriz:</div></td>																	
   <td><span id="igreja">
    <select name="igreja.matriz" id="matriz" onchange="IgrejaCombo(id); retrieveURL('http://localhost:8080/IU/IgrejaAction', 'frm2')" style="width: 200px;height: 25px">
     <option value=""></option>						
      <c:forEach var="matriz" items="${matrizes}">										
       <option value="${matriz}" <c:if test="${matriz == igreja.matriz}"> selected</c:if>>${matriz}</option>
      </c:forEach>
    </select></span>
   </td>						 
   </tr>				
  </html:form>

Aqui esta o meu JS - Ajax

function retrieveURL(url,nameOfFormToPost) {
    alert(url + " " + nameOfFormToPost);
	  //convert the url to a string
	  url=url+getFormAsString(nameOfFormToPost);
	    
	  //Do the AJAX call
	  if (window.XMLHttpRequest) { 
	     
	    // Non-IE browsers
	    req = new XMLHttpRequest();
	    req.onreadystatechange = processStateChange;
	    try {
	          req.open("GET", url, true); 
	    } catch (e) {
	      alert("Server Communication Problem\n"+e);
	    }
	    req.send(null);
	  } else if (window.ActiveXObject) {
	    // IE
	   
	    req = new ActiveXObject("Microsoft.XMLHTTP");
	    if (req) {
	      req.onreadystatechange=processStateChange;
	      req.open("GET", url, true);
	      req.send();
	    }
	  }
	}

function getFormAsString(formName){
    
	  //Setup the return String
	  returnString ="";
	        
	  //Get the form values
	  formElements=document.forms[formName].elements;
	        
	  //loop through the array, building up the url
	  //in the format '/strutsaction.do&name=value'
	 
	  for(var i=formElements.length-1;i>=0; --i ){
	        //we escape (encode) each value
	        returnString+="&" 
	        +escape(formElements[i].name)+"=" 
	        +escape(formElements[i].value);
	 }
	        
	 //return the values
	 return returnString; 
	}


function processStateChange() {
	  
	  if (req.readyState == 4) { // Complete
	    if (req.status == 200) { // OK response
	        
	    //Split the text response into Span elements
	    spanElements = 
	        splitTextIntoSpan(req.responseText);
	    
	    //Use these span elements to update the page
	    replaceExistingWithNewHtml(spanElements);
	    
	    } else {
	      alert("Problem with server response:\n " 
	        + req.statusText);
	    }
	  }
	}

function replaceExistingWithNewHtml (newTextElements){
	//loop through newTextElements
	for(var i=newTextElements.length-1;i>=0;--i){
	
	//check that this begins with <span
		if(newTextElements[i].indexOf("<span")>-1){
		                
			//get the span name - sits
			// between the 1st and 2nd quote mark
			//Make sure your spans are in the format
			//<span id="someName">NewContent</span>
			startNamePos=newTextElements[i].indexOf('"')+1;
			endNamePos=newTextElements[i].indexOf('"',startNamePos);
			name=newTextElements[i].substring(startNamePos,endNamePos);	                
			//get the content - everything 
			// after the first > mark
			startContentPos=newTextElements[i].indexOf('>')+1; 
			content=newTextElements[i].substring(startContentPos);	                
			//Now update the existing Document 
			//with this element, checking that 
			//this element exists in the document
			if(document.getElementById(name)){
		        document.getElementById(name).innerHTML = content;
			}
		}
	}
}

function splitTextIntoSpan(textToSplit){	 
	//Split the document
	returnElements=textToSplit.split("</span>");	        
	//Process each of the elements        
	for(var i=returnElements.length-1;i>=0;--i){	                
	    //Remove everything before the 1st span
	    spanPos = returnElements[i].indexOf("<span");                
	    //if we find a match, take out 
	    //everything before the span
	    if(spanPos>0){
	          subString=returnElements[i].substring(spanPos);
	          returnElements[i]=subString;
	    } 
	}
	return returnElements;
}

no struts config … aquele form esta configurado pra ir pra classe IgrejaAction … porem nao to nem conseguindo chegar lá … ta dando o seguinte erro:
Problem with Server response: Not found

alguem consegue me ajudar??

A

cara… acho que é mais facil vc partir para o jQueri que o rodrigo.lopes indicou…
acho que é menos trabahoso…

C

Galera … valeu pela ajuda … o negocio ta dificil aqui … Vou dar uma olhada no Jquery e tentar implementar do jeito que o Joao me passou.
Se der certo eu posto a solução aqui pra quem tiver o mesmo problema … se nao volto a perdir Socorro!!!

Espero postar a solução :slight_smile:

abs

R

Com o jquery vc pode fazer requisicoes get ou post direto para um metodo de uma action, passar parametros e receber o retorno num js.

exemplo, chamar action, passar parametros e tratar retorno

$.post('suaAction.do', {param1: 1, param2: 2}, 
		function(data) {
			$("#algumaDiv").html('<font face="verdana" color="#FFFFFF" size="2"><strong>Obrigado por responder!</strong></font>');
		}
	);
C

Deixa eu ver se entendi

digamos que a action que esta configurada pra mim no struts-config é path="/igreja" minha action que esta no meu pacote action é IgrejaAction.java pra montar o proximo select teria que passar como parametro igreja.regional Entao ficaria assim?

.jsp

<select name="igreja.regional" id="regional" onchange="teste(this, id)">
 <option value=""></option>
</select>

.js

function teste(value ,id){
	alert(value.value+" - "+ id);		
	$.post('igreja', {param1: value, param2: id},   
			function(data) {  
				$("#"+id).html('<font face="verdana" color="#FFFFFF" size="2"><strong>Obrigado por responder!</strong></font>');  
				}  
	); 
}

Porque desse jeito acabei de testar e nao esta funcionando

R

No meu caso:

struts-config.xml:

<form-bean type="br.com.abril.sac.clube.presentation.controller.RSVPForm" name="rsvpForm"/>
<action name="rsvpForm" scope="request" type="br.com.abril.sac.clube.presentation.action.RSVPAction" parameter="action" validate="false" path="/rsvp"/>

Action:

protected ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		RSVPForm frm = (RSVPForm) form;
		
		// Faco alguma logica
		
		return //algo para usar na funcao javascript pode ser uma string, xml ou json;
	}

JSP:

<a href="#" onclick="javascript:responderRSVP('<bean:write name="msgRSVP" property="pk.codPessoa" />',
				        									 '<bean:write name="msgRSVP" property="pk.codEvento" />',
				        									 '<bean:write name="msgRSVP" property="pk.datSessao" />', 'S', 1)">

JS:

function responderRSVP(cPessoa, cEvento, dSessao, resp, posicao) {
	
	$("#conteudoRSVP"+posicao).html('<font face="verdana" color="#FFFFFF" size="2"><strong>enviando...</strong></font>');

	// A resposta do usuário é enviada via Ajax
	$.post('rsvp.do', {codPessoa: cPessoa, codEvento: cEvento, datSessao: dSessao, resposta: resp}, 
		function(data) {
			$("#conteudoRSVP"+posicao).html('<font face="verdana" color="#FFFFFF" size="2"><strong>Obrigado por responder!</strong></font>');
		}
	);
}

detalhe que o valor do parametros ja sao injetados automaticamente nos atributos do Form, quando chegar na action so trabalho com o frm.

Form:

public class RSVPForm extends ActionForm {

	private static final long serialVersionUID = 4705492301012339047L;
	
	private Long codPessoa;
	private Integer codEvento;
	private String datSessao;
	private Boolean confirmado;
	private String resposta;
      
        // get e set
}

espero ter ajudado abas

C

Pow galera valeu pela ajuda … pelo menos já consegui acionar o meu action … o unico problema é que eu nao to conseguindo popular o form … ele ta chegando null na action
é praticamente igualzinho como o colega acima ta fazendo …

$("#matriz").html('<font face="verdana" color="red size="2"><strong>Aguarde...</strong></font>');	      
	     $.post('igreja.do', {matriz: mt.value, id: document.getElementById("idIgreja").value},   
	         function(data) {  
	             $("#matriz").html('<font face="verdana" color="#FFFFFF" size="2"><strong>Obrigado por responder!</strong></font>');  
	         }  
	     );  
	}

Alguem sabe me dizer o que pode estar acontecendo??

abs

R

no seu form tem os atributos matriz e id?

vc possui converters necessarios para os tipos deles no form?

tem ctz q os valores passados nos parametros sao diferentes de null?

C

E ai rodrigo blz? valeus pela ajuda

Entao eu tenho uma camada de modelo

private String matriz, regional, endereco, cod_igreja, id;
...
//get's and setter's
...
	}

e ai o forms

public class IgrejaForm extends ActionForm {
	
	private static final long serialVersionUID = 1L;
	private Igreja igreja = new Igreja();

	public Igreja getIgreja() {
		return igreja;
	}
}

Pra ter certeza que os parametros a serem enviados sao diferentes de null eu dei um alert nos dois no JavaScript e até entao ta tudo certinho

Agora eu nao entendi direito o que vc quis dizer com converters … seria o form do meu metodo execute na action??

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

IgrejaForm formulario = (IgrejaForm) form;
Igreja igreja = formulario.getIgreja();

mais uma vez obrigado pela ajuda

R

Cara ja sei oq é…

vc tem que setar o atributo da objeto igreja.

algo assim: igreja.id, igreja.matriz

isso deve funcionar,

caso nao, crie os atributos id e matriz no form pra ve se chega certinho

abs

C

Nossa cara … vc estava certissimo … agora eu realmente nao entendi o porque … a unica coisa que fiz foi incluir os caras no form. Porem no form eu tava criando uma instancia do meu objeto modelo … ou seja … eles estavam lá o tempo todo!!!
Enfim … muito obrigado pela ajuda … agora é ver como eu trato esses objetos de volta

abs

C

Galera … como faço agora pra poder pegar no JavaScript os valores que seriam populados na JSP?
antes eu tinha isso aqui na JSP

<select name="igreja.regional" id="regional" onchange="IgrejaCombo(id); javascript:teste())">
 <option value=""></option>
 <span id="regional"></span>
</select>

Porem agora como implementei o AJax com Jquery preciso popular o select no JavaScript, tentei isso

function teste() {	
	$.post('igreja.do', {	matriz: document.getElementById("matriz").value, 
					id: document.getElementById("idIgreja").value,
					regional:document.getElementById("regional").value,
					igreja: document.getElementById("endereco").value},
		function(data) {  
			$("#regional").html("<c:forEach var='regional' items='${regional}'><option value='${regional}' <c:if test='${regional == igreja.regional}'> selected</c:if>>${regional}</option></c:forEach>");
							}  
			);  
}

porem nao esta funcionando

Criado 8 de julho de 2010
Ultima resposta 12 de jul. de 2010
Respostas 15
Participantes 4