Foros del Web

Foros del Web (http://www.forosdelweb.com/)
-   Java (http://www.forosdelweb.com/f45/)
-   -   Problema: Servlets, sendRedirect() e includes (http://www.forosdelweb.com/f45/problema-servlets-sendredirect-e-includes-552246/)

Efernand 28/01/2008 12:34

Problema: Servlets, sendRedirect() e includes
 
Desde el index.jsp es desde donde hago la publicación de la noticia, así como la visualización de las mismas.

El caso es que despues de actualizar la base de datos con la nueva noticia publicada el servlet hace un response.sendRedirect("index.jsp") que redirecciona al index.jsp con lo que el noticias.jsp que está incluido en el index.jsp debería estar actualizado mostrando la nueva noticia publicada. El problema reside en que esto no sucede y para visualizarle he de refrescar el navegador.

Únicamente estaba trasteando con el código, se que podría estar mejor estructurado

Gracias de antemano,

Código del index.jsp:

Código:

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%--
The taglib directive below imports the JSTL library. If you uncomment it,
you must also add the JSTL library to the project. The Add Library... action
on Libraries node in Projects view can be used to add the JSTL 1.1 library.
--%>
<%--
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
--%>

<!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=UTF-8">
        <title>Ejercicio 01 - Registro, Login y Publicacion</title>
    </head>
    <body>
        <%//=session.getAttribute("Usuario")%>
        <div>
            <% if(session.getAttribute("Usuario") == null){ %>
            <form method="POST" action="Validacion">
                Usuario: <input type="text" name="user" size="12">&nbsp; Contraseña: <input type="password" name="password" size="9"> <input type="submit" value="Ok!" name="btnLogIn">
            </form>
            <% }else{ %>
                Bienvenido <%= session.getAttribute("Usuario") %>,
            <% } %>
        </div>
        <br>
        <br>
        <div>
            <%@ include file="noticias.jsp" %>
        </div>
        <div>
            <% if(session.getAttribute("Usuario") != null){ %>
            <form method="POST" action="PublicarNoticia">
                Título:
                <br>
                <input type="text" name="titulo" size="50">
                <br>
                Cuerpo:
                <br>
                <textarea name="cuerpo" rows="4" cols="37">
                </textarea>
                <br>
                <input type="submit" value="Publicar" name="btnPublicar">
            </form>
            <% } %>
        </div>
    </body>
</html>

Código del noticias.jsp:

Código:

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>


<%!
    Connection canal;
    Statement select;
    ResultSet retorno;
    String rutabd= "C:\\Documents and Settings\\Enrique\\Ejercicio01\\bd1.mdb";
    String strconnect = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + rutabd;
%>
<%         
    try{
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        canal = DriverManager.getConnection(strconnect);
    }catch(Exception e){
        out.println(e.getMessage());
    };
   
    try{
        select = canal.createStatement();
        retorno = select.executeQuery("SELECT * FROM Noticias");
               
        if(retorno.next()){
            do{
                out.println(retorno.getString("Titulo"));
                out.println("<br>");
                out.println(retorno.getString("Cuerpo"));
                out.println("<br>");
                out.println(retorno.getString("Autor"));
                out.println("<br><br>");
            }while(retorno.next());
        }
    }catch(Exception e){
        out.println(e.getMessage());
    }
     
%>

Código del Servlet PublicarNoticia:

Código:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        try{
                select = canal.createStatement();
                select.execute("INSERT INTO Noticias(Titulo, Cuerpo, Autor) VALUES ('" + request.getParameter("titulo")+ "', '" + request.getParameter("cuerpo") + "', '" + request.getSession().getAttribute("Usuario") + "')");
        }catch(Exception e){
                out.println(e.getMessage());
        };
       
        for(int i = 0; i<10000000; i++){
           
        }
       
        response.sendRedirect("index.jsp");
       
        out.close();
    }


gustavoh10 29/01/2008 04:30

Re: Problema: Servlets, sendRedirect() e includes
 
Hola, lo unico que se me ocurre es probar usar en vez de

Código PHP:

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

http://java.sun.com/products/jsp/tag...ref11.fm6.html

Código PHP:

<jsp:include page="relative URL" flush="true"/> 

http://java.sun.com/products/jsp/tag...fm11.html#8828

pero la verdad no se si eso cambia algo.
Probaste debbugiar el método que trae las noticias?

Si tenes que dar Actualizar para cargar la nueva noticia puede ser que el problema este en el sendRedirect, la verdad no se.

Podes probar en vez de response.sendRedirect();

RequestDispacher rd = request.getRequestDispatcher("index.jsp);
rd.forward(request,response);

saludos

GreenEyed 29/01/2008 14:24

Re: Problema: Servlets, sendRedirect() e includes
 
El que te esta guardando la pagina es el navegador. El explorer es muy "perro" con esas cosas y le gusta cachear mucho las paginas.

Revisa este enlace a ver si te da ideas:
http://www.webexperto.com/articulos/...del-navegador/

S!

gustavoh10 30/01/2008 04:17

Re: Problema: Servlets, sendRedirect() e includes
 
Cita:

Iniciado por GreenEyed (Mensaje 2267238)
El que te esta guardando la pagina es el navegador. El explorer es muy "perro" con esas cosas y le gusta cachear mucho las paginas.

Revisa este enlace a ver si te da ideas:
http://www.webexperto.com/articulos/...del-navegador/

S!

Hola, te consulto.. agregando los tags que menciona el post, se consigue el mismo resultado q haciendo esto:
En Internet Explorer 6, tengo un problema (a veces no se actualizan las páginas) en una aplicación que se soluciona llendo a
Herramientas -> Opciones de Internet -> Configuración (Tab General) -> Comprobar si hay nuevas act.. de las páginas -> Opción: Cada vez que se visita la página.

Si esto es así sería la solución a muchos problemas, por lo menos para mi.

Gracias!


La zona horaria es GMT -6. Ahora son las 08:00.

Desarrollado por vBulletin® Versión 3.8.7
Derechos de Autor ©2000 - 2026, Jelsoft Enterprises Ltd.