Ahmad Nabi
Ahmad Nabi

Reputation: 43

Forward A servlet request to a .html file in java?

Basically I have servlet named forward. When a request is made to it, it forwards the request to a .html file like this:

@WebServlet("/forward")
public class forward extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/videos/forward.html").forward(request, response);
        return;
    }
}

The problem is that when I test this on eclipse when a request is made to this servlet, it responds with the link as localhost/videos/forward.html

But then when I deployed it with name com.war Now when a request is made to it, it responds with localhost/com/videos/forward.html

How can I make the requestDispatcher to respond with localhost/videos/forward.html and not as localhost/com/videos/forward.html

Upvotes: 0

Views: 3178

Answers (3)

vishwa
vishwa

Reputation: 74

Yes, u can. use:

RequestDispatcher r = req.getRequestDispatcher(String arg);

Upvotes: 0

Akshay Pawar
Akshay Pawar

Reputation: 85

Just write response.sendRedirect(pagename.html)

Upvotes: 0

Serge Ballesta
Serge Ballesta

Reputation: 149185

No you cannot. Forwarding is a request made to the servlet container to pass control to another servlet in same servlet context. A JSP page in indeed implemented as a servlet, but a HTML is just a ressource, so you cannot forward to it.

But you can redirect to it. A redirection works by sending a special response telling the browser that it should go to that other URL. As it works at browser level, you can redirect to a HTML page or even to a completely different site.

You can use the sendRedirect method from HttpServletResponse to initiate a redirection from a servlet:

@WebServlet("/forward")
public class forward extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.sendRedirect("/videos/forward.html");
        return;
    }
}

Upvotes: 2

Related Questions