0

If I have two servlets:

@WebServlet (urlPatterns = {"/s1"})
public class Servlet1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
    throws ServletException, IOException {

        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("A", 100);
        map.put("B", 200);
        map.put("C", 300);

        req.setAttribute("map", map);
        getServletContext().getRequestDispatcher("Servlet2").forward(req, resp);
    }
}

public class Servlet2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
    throws ServletException, IOException {
        Map map = (Map) req.getAttribute("map");

        for (Object o : map.values()) {
            System.out.println(o);
        }
    }
}

How can I make redirect between them? And which path I need to use in my getRequestDispatcher method? And one more condition - Servlet2 must be without any mapping in annotations or in web.xml.

user3163426
  • 187
  • 1
  • 1
  • 7
  • Mapping is mandatory for a servlet... – Alexandre Lavoie Jan 06 '14 at 20:35
  • But I need Servlet2 invisible for user. It cannot access from browser. If I use mapping user can access to the servlet. – user3163426 Jan 06 '14 at 20:38
  • Are you sure you want Servlet instead of lets say JSP (which is kind of servlet and will not have any annotation or address set in web.xml)? – Pshemo Jan 06 '14 at 20:38
  • To bad, because by placing your JSP in `WEB-INF/yourJspFile.jsp` you could dispatch request to it via request dispatcher. Also it would hide this JSP "address" from browsers. – Pshemo Jan 06 '14 at 20:44

1 Answers1

3

Servlet2 must be without any mapping in annotations or in web.xml.

Then you cannot use HttpServletRequest#getRequestDispatcher(String), which is a container managed method that checks those mappings.

That condition is ridiculous and makes no sense. If you aren't going to use the Servlet container, don't make a Servlet. Make a service class that performs the actions you need. You don't need to make everything a Servlet.

Your only (ridiculous) alternative is to instantiate Servlet2 and explicitly invoke its doGet method.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724