0

Suppose I want to have path look like this /Servlet1?id=34/Servlet2

I want to access Servlet2 depending on the id parameter received in Servlet1, but when I try to do so system access service methods of Servlet1 only and do not go to Servlet2

I just want to skip the code for Servlet1 and move to Servlet2 when my path is /Servlet1?id=34/Servlet2 otherwise run code in Servlet 1 when path is /Servlet1?id=34

I am not sure when such approach is to be used, where you access a Servlet which is like a descendent to another servlet. If I am taking any concept wrong kindly correct or else suggest some solution to make it work

EDIT: If user enters /Servlet1?id=34 then it shows an entirely different page and when user enters /Servlet1?id=34/Servlet2 I want to show a different page based on the id specified in Servlet1.

Problem is that the URI that I get in Servlet1 when user enter path /Servlet1?id=34/Servlet2 is only /Servlet1 i.e. Servlet2 is nowhere in URI so how do I identify which Servlet user is looking for?

1
  • Keep a check in Servlet1 if (id == 34) then redirect to servlet2. Commented Apr 19, 2012 at 5:05

1 Answer 1

0

Use RequestDispatcher("\servlet2")'s forward(req,res) method from Servlet1 to forward the control to Sertvlet2.

Edit:

public class Servlet1 extends HttpServlet{

protected void doPost(HttpServletRequest request, HttpServletResponse response)   throws ServletException, IOException {

    String id= request.getParameter("id");
    /*
     * You can do any processing here. 
     * We will simply output the value of name parameter on server console.
     * 
     */


         if(id.equals("32")){
      RequestDispatcher rd =
          getServletContext().getRequestDispatcher("\Servlet2");
          rd.forward(request, response);
        }
}

}

Sign up to request clarification or add additional context in comments.

7 Comments

But how will I identify when user want to access Servlet2 and when he wants to access Servlet1. Because the URI that I receive in Servlet1 is /Servlet1 when my path is /Servlet1/Servlet2
you have to set some parameters in jsp/html page and send it to a Servlet say servlet1. Retrieve the parameter in servlet1 and according to the parameter value you can forward the control to either Servlet2 or Servlet3.
it means there is no way in servlet itself to identify whether the user wants to access the same servlet or any servlet situated down under it?
you can also map the path "/servlet1/servlet2" in web.xml to servlet2 class.
see your path /Servlet1?id=34/Servlet2 .in your url-pattern /Servlet1/Servlet2 there is no id attribute. try to append id at the end of path like /Servlet1/Servlet2?id=34
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.