I have problem with RequestDispatcher in Java Servlet, it didn't forward to the specific url if the servlet path is not in root path
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userPath=request.getServletPath();
String view = null;
if(userPath.equals("/admin")) //it's okay, forwarded
{
view="admin";
}
else if(userPath.equals("/admin/tambahArtikel")) //it's not forwarded
{
view="tambahArtikel";
}
else if(userPath.equals("/kategori")) //it's okay, forwarded
{
view="kategori";
}
String url="WEB-INF/view/"+ view +".jsp";
request.getRequestDispatcher(url).forward(request, response);
}
and this is my web.xml
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>ServletController</servlet-name>
<servlet-class>com.agung.webhakakses.servlet.ServletController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletController</servlet-name>
<url-pattern>/admin</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ServletController</servlet-name>
<url-pattern>/admin/tambahArtikel</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ServletController</servlet-name>
<url-pattern>/kategori</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
i think the problem is in the path but i'm not sure
From the ServletRequest#getRequestDispatcher javadoc:
The pathname specified may be relative, although it cannot extend outside the current servlet context. If the path begins with a "/" it is interpreted as relative to the current context root. This method returns null if the servlet container cannot return a RequestDispatcher.
In your code, you build the url this way:
String url="WEB-INF/view/"+ view +".jsp";
So, as the javadoc also says:
The difference between this method and ServletContext#getRequestDispatcher is that this method can take a relative path.
So if your request URI is "/admin/tambahArtikel"
and your forwarding URI does not start with a "/"
then it will be relative, so the forward is sended to "/admin/" + "WEB-INF/view/"+ view +".jsp"
If you need to forward to a resource in the WEB-INF
directory start your URI with a "/" so the path will be relative to the context root.