Java Servlet RequestDispatcher didn't forward the url

社会主义新天地 提交于 2019-12-12 11:17:12

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/13216145/java-servlet-requestdispatcher-didnt-forward-the-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!