user1097505
user1097505

Reputation: 21

servlet url mapping

I have two servlets (MainServlet and LoginServlet) and MainServlet process all request and its mapped to /* . LoginServlet process request and it is mapped to /login. I have one html file /html/login.html. Now I want to show this html file when I hit http://localhost:8080/app/login .

In LoginServlet doGet method I am doing httpServletRequest.getRequestDispatcher("login/login.html").include(httpServletRequest, httpServletResponse);

but this redirect request to MainServlet. I can't change url mapping of MainSerlvet from /* to something else.

Any Idea how I can achieve above? PS: If question is not clear please tell me.

Upvotes: 2

Views: 681

Answers (1)

BalusC
BalusC

Reputation: 1108722

You've mapped the MainServlet on a global URL pattern /* which is a pretty poor practice for servlets (this also covers static resources like CSS/JS/images/etc!). This will also intercept on all forwarded and included requests. You need to map the MainServlet on a more specific URL pattern, e.g. /main/*, /app/* or something like that and create a Filter which is mapped on /* and forwards all non-/login requests to the MainServlet.

String uri = ((HttpServletRequest) request).getRequestURI();

if (uri.startsWith("/login/")) {
    // Just continue to login servlet.
    chain.doFilter(request, response);
} else {
    // Forward to main servlet.
    request.getRequestDispatcher("/main" + uri).forward(request, response);
}

By the way, using RequestDispatcher#include() to display the view is not entirely correct as well. You should be using RequestDispatcher#forward() for this instead.

Upvotes: 1

Related Questions