sendRedirect与forward跳转根路径:getRequestDispatcher报空指针的解决方法
Hey there! Let's break down why you're hitting that NullPointerException when trying to forward to the root path with request.getRequestDispatcher("/"), and how to fix it properly.
Why the NullPointerException happens
When you pass "/" to request.getRequestDispatcher(), the servlet container tries to resolve this path to a valid, existing resource. If there's no explicit mapping (like a Servlet bound to /) or a configured welcome page for the root path, the dispatcher object returned will be null. Calling forward() on a null reference is exactly what triggers that NPE.
Fixes to get the root path forward working
Here are a few reliable approaches to achieve the same root path jump without the browser round-trip:
1. Forward directly to your app's welcome file
Most web apps have a default welcome page (like index.jsp, index.html, or a controller endpoint) set up via <welcome-file-list> in web.xml or your framework's routing rules. Instead of using the vague / path, target this concrete resource directly:
// Replace with your actual welcome file/endpoint path request.getRequestDispatcher("/index.jsp").forward(request, response);
This works because you're pointing to a resource the container can definitively find, so no null dispatcher is returned.
2. Ensure the root path is mapped to a Servlet
If your root path (/) is supposed to be handled by a dedicated Servlet (e.g., using @WebServlet("/") annotation or a <servlet-mapping> entry in web.xml), double-check that the Servlet is properly registered. Once that's confirmed, using request.getRequestDispatcher("/") will work seamlessly—since the container now knows exactly which resource to route the request to.
3. Use the ServletContext's RequestDispatcher instead
Sometimes, path resolution quirks with the request-scoped dispatcher can cause issues. Try using the ServletContext's dispatcher instead, which always resolves paths relative to the web app root:
getServletContext().getRequestDispatcher("/").forward(request, response);
This approach can be more reliable for root path forwarding in certain container setups.
4. Debug to confirm the issue
If you're still stuck, add a quick check to verify whether the dispatcher is null:
RequestDispatcher dispatcher = request.getRequestDispatcher("/"); if (dispatcher == null) { // Log or print this to confirm the root cause System.out.println("No dispatcher found for root path—check welcome files or Servlet mappings!"); } else { dispatcher.forward(request, response); }
This will help you confirm if the problem is indeed a missing resource mapping for the root path.
The core idea is to make sure the servlet container has a clear, resolvable target for the / path. By targeting a specific welcome file, ensuring a Servlet is mapped to the root, or using the ServletContext dispatcher, you'll eliminate the NPE and achieve the server-side forward you want.
内容的提问来源于stack exchange,提问作者NikNik

