ovnia
ovnia

Reputation: 2500

Forward from servlet to servlet

Working on Front Controller for servlet-based application but cant find out how to forward from front contoller to regular controllers.

Here is my web.xml:

<servlet>
    <servlet-name>FrontServlet</servlet-name>
    <servlet-class>FrontServlet</servlet-class>
</servlet>
<servlet>
    <servlet-name>IndexServlet</servlet-name>
    <servlet-class>application.controllers.IndexServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>FrontServlet</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

FrontServlet

public class FrontServlet extends HttpServlet {
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext context= getServletContext();
        RequestDispatcher rd = context.getRequestDispatcher("IndexServlet");
        rd.forward(request, response);
    }
}

This code returns: java.lang.NullPointerException. I'm using an WebLogic server.

Upvotes: 0

Views: 2359

Answers (2)

VinayBS
VinayBS

Reputation: 409

You have not given servletMapping for the IndexServlet and requestDispatcher works on URLs.

Give a proper servletMapping in the web.xml, something like this:

<servlet>
    <servlet-name>FrontServlet</servlet-name>
    <servlet-class>FrontServlet</servlet-class>
</servlet>
<servlet>
    <servlet-name>IndexServlet</servlet-name>
    <servlet-class>application.controllers.IndexServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>FrontServlet</servlet-name>
    <url-pattern>/frontServlet.html</url-pattern>
</servlet-mapping>


<servlet-mapping>
    <servlet-name>FrontServlet</servlet-name>
    <url-pattern>/indexServlet.html</url-pattern>
</servlet-mapping>

And in your FrontServlet.java, give the url as "/indexServlet.html". It will work. NullPointerException will be thrown if the view you are forwarding is not accessible. Is your IndexServlet.java forwarding request to any jsp/html? In that case, check if the jsp/html is accessible using http://{webapp}/loginjsp.jsp.

Upvotes: 0

  1. do you have a servlet mapping for IndexServlet
  2. to send to a servlet you need path like "/IndexServlet.do"

    this.getServletContext ( ) .getRequestDispatcher ( "/IndexServlet.do" ) .forward ( request , response ) ; or response.sendRedirect ( "/IndexServlet.do" );

    assuming your mapping was like

    <servlet-mapping>
        <servlet-name>IndexServlet</servlet-name>
        <url-pattern>/IndexServlet.do</url-pattern>
    </servlet-mapping>

    I have not tried using no extension at all instead of .do or . but I would get it working with .do then experiment on changing it

Upvotes: 1

Related Questions