Jump to content

Passando ArrayList de Servlet para JSP - ERRO


geek
 Share

Recommended Posts

Boas Pessoal,

Tenho um servlet que retorna um Arraylist de um tipo generico, queria mandar o arraylist e pega-lo na minha página JSP.

Como faço?

O meu código da servlet é:

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Servlets;
import Dados_XML.CinemaLocais;
import Dados_XML.FilmesDistrito;
import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Iterator;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.ws.Dispatch;
import javax.xml.ws.Service;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
/**
*
* @author berkley blue
*/
public class cinemaExtreias extends HttpServlet {
/**
 * Processes requests for both HTTP
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	response.setContentType("text/html;charset=UTF-8");
	PrintWriter out = response.getWriter();
	try {
		/*
		 * TODO output your page here. You may use following sample code.
		 */
		String distrito = request.getParameter("distrito");
		String concelho;
		ArrayList<FilmesDistrito> listaFilmes = new ArrayList<FilmesDistrito>();
		pt.sercultur.ws.Sws service = new pt.sercultur.ws.Sws();
		QName portQName = new QName("http://ws.sercultur.pt/", "SwsSoap12");
		String req = "<CartazCinemaFilmesExt  xmlns=\"http://ws.sercultur.pt/\"><Pais></Pais><Genero></Genero><Classificacao></Classificacao><Distrito>" + distrito + "</Distrito><Concelho></Concelho><CicloFestival></CicloFestival><DiasProgramacao></DiasProgramacao><Destaques></Destaques><Opcionais></Opcionais><EspacoAcademico></EspacoAcademico></CartazCinemaFilmesExt>";
		try { // Call Web Service Operation
			Dispatch<Source> sourceDispatch = null;
			sourceDispatch = service.createDispatch(portQName, Source.class, Service.Mode.PAYLOAD);
			Source result = sourceDispatch.invoke(new StreamSource(new StringReader(req)));
			ByteOutputStream o = new ByteOutputStream();
			Result streamResult = new StreamResult(o);
			TransformerFactory.newInstance().newTransformer().transform(result, streamResult);
			// System.out.print(result);
			String s = new String(o.getBytes());
			s = s.trim();
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			InputSource is = new InputSource();
			is.setCharacterStream(new StringReader(s));
			org.w3c.dom.Document doc = db.parse(is);
			FilmesDistrito cartaz = new FilmesDistrito("", "", "");
			NodeList filmes = (NodeList) doc.getElementsByTagName("Filme");
			NodeList descricao = doc.getElementsByTagName("Descricao");
			NodeList genero = doc.getElementsByTagName("Genero");
			for (int i = 0; i < filmes.getLength(); i++) {
				Element element = (Element) filmes.item(i);
				String nome_filme = element.getFirstChild().getNodeValue();
				cartaz.setNomeFilme(nome_filme);
				out.println(nome_filme);
				Element elementDesc = (Element) descricao.item(i);
				String descricao_filme = elementDesc.getFirstChild().getNodeValue();
				cartaz.setDescFilme(descricao_filme);
				out.println(descricao_filme);
				Element elementoGenero = (Element) genero.item(i);
				String genero_filme = elementoGenero.getFirstChild().getNodeValue();
				cartaz.setGeneroFilme(genero_filme);
				out.println(genero_filme);
			}
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}


		request.setAttribute("listaFilmes", listaFilmes);
		RequestDispatcher disp = request.getRequestDispatcher("index.jsp");

		 disp.forward(request, response);
		// request.getDispatcher("index.jps").forward(request,response);

	} finally {
		out.close();
	}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
 * Handles the HTTP
 * <code>GET</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	processRequest(request, response);
}
/**
 * Handles the HTTP
 * <code>POST</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	processRequest(request, response);
}
/**
 * Returns a short description of the servlet.
 *
 * @return a String containing servlet description
 */
@Override
public String getServletInfo() {
	return "Short description";
}// </editor-fold>
}

O meu código do JSP é:

<%--
Document   : index
Created on : Jun 14, 2012, 9:31:58 PM
Author	 : berkley blue
--%>
<%@page import="java.util.ArrayList"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>JSP Page</title>
</head>
<body>

<div id="cinemas" >
	<form action="http://localhost:8080/ITIS/cinemaExtreias" method="post">
		Distrito: <input type="text" id="distrito" name="distrito"/>
		<input type="submit" value="pesquisa"/>
	</form>
</div>
	<% ArrayList employeeList =(ArrayList)request.getAttribute("listaFilmes");

	out.print(employeeList.size());

	%>


</body>
</html>

Alguém me dá uma mãozinha?

Edited by Baderous
geshi
Link to comment
Share on other sites

Bom dia,

Podes colocar a solução que deste ao problema ? É que tal como tu, mais gente pode ter dificuldades semelhantes e a solução fica disponível.

Cordiais cumprimentos,

Apocsantos

"A paciência é uma das coisas que se aprendeu na era do 48k" O respeito é como a escrita de código, uma vez perdido, dificilmente se retoma o habito"

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.