简体   繁体   中英

.forward() then resp.sendRedirect() with servlet

I'm using servlet in order to make a java based website. I'm sending calcul data to a server, this server is then doing it's calculation and storing the result in the database.

what I want is display a loading page, so i should get 1/form submission 2/loading page 3/result page

to do that my submission form send me on a servlet wich display the loading page then check in the database if the data is present, if it is it then redirects me over the result page.

this is my loading servle

public class AffichageChargementServlet  extends HttpServlet{

    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //recuperation de la clé de l'entité qui contiadra les resultats
        String key = req.getParameter("key");
        //affichage de la page de chargement
        try {
            getServletContext().getRequestDispatcher("/loading.html").forward(req, resp);
        } catch (ServletException e) {
            System.out.println("problemme dans la servlet AffichageChargementServlet lors du chargement de /loading.html");
            e.printStackTrace();
        }
        //verification de la disponibilité de l'entité
        Key resultatKey = KeyFactory.createKey("Resultat", key);
        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
        Entity result = null;
        while(true){
            try {
                result = datastore.get(resultatKey);
            } catch (EntityNotFoundException e) {
                System.out.println("pas encore prete");
                //ne rien faire, la data n'est pas encore disponible
            }
            if(result != null){
                System.out.println("redirection vers /affichageResults?key="+key);
                resp.sendRedirect("/affichageResults?key="+key);
            }
        }
    }

}

As I just learned, it is not possible to do multiple redirection in a servlet, so i'm getting a java.lang.IllegalStateException: Response already committed

Is there a workaround?

thanks

Response already committed means you have already write something on response and you are trying to forward or redirect.

You should use either of Forward or Redirect on the response not both, your code does both. You need to decide first whether you want to forward or redirect and then commit the response based on your decision

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM