servlet having problem with getRequestDispatcher

Discussions

Web tier: servlets, JSP, Web frameworks: servlet having problem with getRequestDispatcher

  1. Hi,

    Here is my situation.

    The path of the web apps

    /usr/local/jakartatomcat/webapps/myapps/*.jsp
    /usr/local/jakartatomcat/webapps/myapps/user
    /usr/local/jakartatomcat/webapps/myapps/Mydocs
    /usr/local/jakartatomcat/webapps/myapps/WEB-INF\classes\*.java

    Now in servlet I have following

    Step 1 Get filename parameter
    filename = req.getParameter("filetoopen");

    Note: filename here will be something like this http://localhost:8080/myapps/Mydocs/folder/file1.pdf

    Step 2 Get database connection and insert into DB
    dconn = new DBConnect();
    ret = insertqry(filename);

    step 3 open the pdf file
    RequestDispatcher rd =
    getServletContext().getRequestDispatcher("http://localhost:8080/myapps/Mydocs/folder/file1.pdf");
    rd.forward(req, res);

    This is not working I am getting a exception error that pathname does not start with "/"

    I am new to jsp/servlet.

    My aim here is to open the pdf file that I have passed to the servlet. Please Help.

    Thanks
    rawar.

    Threaded Messages (8)

  2. Use context relative path[ Go to top ]

    The approach you are using nostly used in roundtrip sendredirect
  3. Thanks[ Go to top ]

    Can you please send me some sample code. That will really help me a lot to understand the flow.

    Thank in advance.
  4. try this[ Go to top ]

    RequestDispatcher rd =
    getServletContext().getRequestDispatcher("/Mydocs/folder/file1.pdf");
    rd.forward(req, res);
  5. Thanks[ Go to top ]

    when I try with forward (your sample code) I get blank page. Also in your earlier reply you said this can be done with sendredirect. Is this true? If yes can you send me simple sample code.

    Thanks
    rawar
  6. response.sendRedirect[ Go to top ]

    response.sendRedirect("http://localhost:8080/myapps/Mydocs/folder/file1.pdf");
  7. RequestDispatcher[ Go to top ]

    You could use sendRedirect too, but it creates another request HTTP on your server. With RequestDispacther the pathname to the resource must begin with a "/" and is interpreted as relative to the current context root.

    Look at this:

    getRequestDispatcher

    Rafael Naufal.
  8. Thanks for the help guys[ Go to top ]

    Thanks for the help guys. Its working now.
  9. I think you can use getRequestDispatcher in your current ServletContext to redirect to a relative URL only, like
    context.getRequestDispatcher("/Mydocs/folder/file1.pdf");
    As the documentation of this method states "The pathname must begin with a "/" and is interpreted as relative to the current context root." In order to dispatch to an absolute URL on the server you must call getContext before, like
    ServletContext newContext = context.getContext("/otherpath"); newContext.getRequestDispatcher("/otherfile.pdf");
    HTH Thorsten