Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top