1 2 Previous Next 20 Replies Latest reply on Sep 16, 2010 11:57 PM by EJP

    HTTP error 302: response.sendRedirect()

    843842
      Hi everybody,

      I have a first servlet (AGSenderServlet) sending a file to a second one (AGReceiverServlet). This second servlet I'm receiving a file and then redirect to a JSP page. But I'm getting the following exception:
      13-Sep-2010 13:20:42 org.apache.catalina.core.StandardWrapperValve invoke
      SEVERE: Servlet.service() for servlet AGSenderServlet threw exception
      java.io.IOException: Received HTTP status code 302
              at AGSenderServlet.doGet(AGSenderServlet.java:43)
              at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
              at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
              at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
              at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
      
      ....
      I've looked on internet and apparently the error 302 is linked to response.sendRedirect().

      Here is my code:
      public class AGReceiverServlet extends HttpServlet {
           public void doGet(HttpServletRequest request,
                  HttpServletResponse response)
           throws ServletException, IOException {
               // Create a factory for disk-based file items
                DiskFileItemFactory factory = new DiskFileItemFactory();
      
               // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload(factory);
                String realPath = this.getServletContext().getRealPath("sync/in");
                List items = null;
                          try {
                               items = upload.parseRequest(request);
                          } catch (FileUploadException e) {
                               e.printStackTrace();
                          }
                          // Process the uploaded items
                          Iterator iter = items.iterator();
      
                          try {
                               String fileName = "blabla";
                               while (iter.hasNext()) {
                                    FileItem item = (FileItem) iter.next();
                                    // Process a file upload
                                    if (!item.isFormField()) {                         
                                         fileName = item.getName();
                                         long sizeInBytes = item.getSize();
                                         //Write to File
                                         if (fileName != null) {
                                            fileName = FilenameUtils.getName(fileName);
                                        }
                                         File uploadedFile = new File(realPath);
                                         if (!uploadedFile.exists())
                                              uploadedFile.mkdirs();
                                         uploadedFile = new File(realPath+"/"+fileName);
                                         
                                         item.write(uploadedFile);
                                    }
                               }
      
                               System.out.println("http://"+request.getServerName()+':'+request.getServerPort()+"/upTool/filereceived.jsp?filename="+fileName);
                               String redirectURL = "http://"+request.getServerName()+':'+request.getServerPort()+"/upTool/filereceived.jsp?filename="+fileName;
                               response.sendRedirect(redirectURL);                         
                               
                          } catch (Exception e) {
                               e.printStackTrace();
                          }                                        
           }
           
           public void doPost(HttpServletRequest request,
                  HttpServletResponse response)
           throws ServletException, IOException {
                     doGet(request, response);
           }
      }
      The file received is saved properly and is ok.
      Using print out I have discovered that it was the running the whole code but not the code in filereceived.jsp (the JSP of the sendRedirect() ).
      I have tried the url used in the sendRedirect() and it works ok.

      Any idea?


      Cheers.
        • 1. Re: HTTP error 302: response.sendRedirect()
          800387
          The redirect looks ok to me. However, what does AGSenderServlet (specifically line 43) look like? If you are sending yourself a redirect, then you should handle it. :^)

          - Saish
          • 2. Re: HTTP error 302: response.sendRedirect()
            843842
            The AGSenderServlet is sending a file to the AGReceiverServlet using multipart and Postmethod object. Here is the code.
            public class AGSenderServlet extends HttpServlet {
                 public void doGet(HttpServletRequest request,
                        HttpServletResponse response)
                 throws ServletException, IOException {
                      String filename = request.getParameter("filename");
                      String ext = request.getParameter("ext");
                      String serverName = request.getParameter("serverName");
                      String port = request.getParameter("port");
                      String path = null;
                      String uri = "http://"+serverName+":"+port+"/AGReceiverServlet";
                      
                      File file = new File((this.getServletContext().getRealPath("/sync/out"))+"\\"+filename+'.'+ext);
                      System.out.println("Test = "+file.getAbsolutePath());
                      PostMethod post = new PostMethod(uri);
                    Part[] parts = new Part[] {
                        new FilePart(file.getName(), file) // File you want to upload
                    };
                    post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
             
                    // Now perform the POST and check for errors
                    HttpClient http = new HttpClient();
                    int status = http.executeMethod(post);
                    if (status != HttpStatus.SC_OK) {
                        throw new IOException("Received HTTP status code " + status);
                    }          
                 }
                 
                 public void doPost(HttpServletRequest request,
                        HttpServletResponse response)
                 throws ServletException, IOException {
                           doGet(request, response);
                 }
            }
            Line 43 is just
            throw new IOException("Received HTTP status code " + status);
            What do you mean by " then you should handle it." ? I think I handle it. It redirects to the JSP filereceived.jsp which is hosted and available on the server (tried to access it directly by entering the url and it works).

            Edited by: Foobrother on Sep 13, 2010 7:38 AM
            • 3. Re: HTTP error 302: response.sendRedirect()
              843842
              I'm just thinking. Is it possible that at the end (just after doing the redirect) of the second servlet (AGReceiverServlet) it returns a response to the 1st one which is not HttpStatus.SC_OK (but still not an error status) and this throws an exception and stops the whole process before beeing able to run the content of the JSP (as I'm doing the test on the same server)?!
              • 4. Re: HTTP error 302: response.sendRedirect()
                800387
                You are sending a HttpRequest to your own Servlet. That Servlet is responding with 302. Your sending Servlet is looking for 200, finding 302, and throwing your own exception. This error is 100% of your own making. See?

                - Saish
                • 5. Re: HTTP error 302: response.sendRedirect()
                  843842
                  I see indeed. I assumed "HttpStatus.SC_OK" represented all "non-error" status.

                  So in fact when it throws the exception it stops the process (the JSP is not processed). Because at the moment it doesn't run the code in the JSP.
                  I'll remove this status test to see what happens.
                  • 6. Re: HTTP error 302: response.sendRedirect()
                    843842
                    After removing the status test it doesn't throw any error now but it still doesn't run the JSP file.
                    I have also tried to change the redirect with response.sendRedirect("http://www.google.com"); but it didn't change anything.
                    However I do a println just after the response.sendRedirect() and it's printed.
                    • 7. Re: HTTP error 302: response.sendRedirect()
                      800387
                      I suggest you read the documentation on redirects for HttpClient found here. The API handles redirects within the same domain, but requires additional steps if the domain changes.

                      - Saish
                      • 8. Re: HTTP error 302: response.sendRedirect()
                        843842
                        Indeed, I didn't know it didn't handle different domains. It explains maybe why it doesn't work with Google. But it should work with my JSP which is hosted on exactly the same server?!
                        • 9. Re: HTTP error 302: response.sendRedirect()
                          843842
                          I've looked at your link. But I don't understand. It's speaking about the redirect in HttpClient. But I'm using the redirect of HttpServletResponse and I have found few code examples using sendRedirect with other domains (Google, etc...).
                          • 10. Re: HTTP error 302: response.sendRedirect()
                            800387
                            Take it apart step by step. You yourself wrote code that checks for HTTP status 200. You yourself wrote code that is redirecting and resulting in a status 302. You are throwing the IOException you posted earlier in the thread.

                            The docs for HttpClient indicate that if it receives a 302 response (remember, at this point it is the sender and not the responder that is at issue), it will seamlessly handle the redirect if in the same domain. If not in the same domain, you have to write additional code as demonstrated in the link I sent you.

                            After removing the check for status code 200, what happens?

                            - Saish
                            • 11. Re: HTTP error 302: response.sendRedirect()
                              843842
                              Ok so if I have well understood the response.sendRedirect() from the receiver is just sending a redirect request to the sender?!
                              So if a client calls Sender on ServerA, it will call Receiver on ServerB. Then Sender gets the redirect response from Receiver and calls the JSP file on ServerB. Am I right?!

                              But if it works like that, I don't understand how you get the location/URL to redirect from Sender servlet to JSP file.
                              Basically:

                              - Sender (ServerA) ==> Receiver (ServerB) done via PostMethod object (post) and HttpClient object (http) and this line "int status = http.executeMethod(post);"
                              - Receiver (ServerB ==> Sender (ServerA) done via response.sendRedirect(redirectURL); which makes a request on the Sender servlet to redirect to redirectURL ?!
                              - Sender (ServerA) ==> JSP file (ServerB) done via ???

                              If I apply the code of your link, it will get the location from the PostMethod object which is a URL to Receiver?!
                              And then to redirect to the location found in the header I need to do a reponse.sendRedirect() ?!

                              I'm totally confused.

                              Anyway, after removing the check for status code 200 nothing happens. No error, no exception but also not redirection to my JSP file (not code from the page run)

                              Here is my current code:
                              - AGSenderServlet » [http://pastebin.com/vW0YxGcE]
                              - AGReceiverServlet » [http://pastebin.com/nV39JKS1]
                              • 12. Re: HTTP error 302: response.sendRedirect()
                                843842
                                I have just tried to change my reponse.sendRedirect() with a dispatcher.forward(), but it didn't change the result :(
                                String redirectURL = "http://"+request.getServerName()+':'+request.getServerPort()+"/upTool/filereceived.jsp?filename="+fileName;
                                //response.sendRedirect(redirectURL);
                                RequestDispatcher dispatcher = request.getRequestDispatcher(redirectURL);
                                dispatcher.forward(request, response);
                                • 13. Re: HTTP error 302: response.sendRedirect()
                                  800387
                                  Ok. Let's make it simpler: client and server. Your client is initiating a HTTP post request. The server is responding with a HTTP 302 (found, redirect), that is returned the the client. The client should then issue another HTTP post request to the new redirected URL. The server then receives the second request which is handled, presumably by a JSP.

                                  You should be able to see this exact behavior in a browser. What happens when you do so? Meaning, rather than using your client, use a browser. Does the redirect occur properly?

                                  - Saish
                                  • 14. Re: HTTP error 302: response.sendRedirect()
                                    843842
                                    Actually I never used my client to test it but only my browser. I use this URL to start testing: [http://localhost:8080/AGSenderServlet?filename=defacto&ext=zip&serverName=localhost&port=8080]
                                    (parameter serverName should be different I was using 2 different servers)

                                    When I load that servlet, my printouts from the 1st and 2nd servlet are displayed in my Tomcat (not the ones of the JSP) console but nothing changes on the browser. No redirection to another servlet or the JSP page. I just have a blank page.

                                    Edited by: Foobrother on Sep 14, 2010 5:54 AM
                                    1 2 Previous Next