Issue
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
Solution
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;
}
}
Answered By - Serge Ballesta
Answer Checked By - Pedro (JavaFixing Volunteer)