Reputation: 56669
Currently we have all links on our site set up as /xxx/UseCase
.
We would like to now accept incoming requests with the prefix /yyy
such as /yyy/xxx/UseCase
. So we would have one servlet that accepts requests on both /yyy/xxx/UseCase
and /xxx/UseCase
.
How can we do this?
Biggest challenge here being: A number of pages redirect to other URI's using the absolute path. Ie: the Patients
servlet redirects to /xxx/Insurance
. Issue is if you're at /yyy/xxx/Patients
you shouldn't now get redirected to /xxx/Insurance
- you should get redirected to /yyy/xxx/Insurance
Upvotes: 0
Views: 1959
Reputation: 1108712
You can just map a servlet on more than one URL pattern:
<servlet-mapping>
<servlet-name>fooServlet</servlet-name>
<url-pattern>/xxx/*</url-pattern>
<url-pattern>/yyy/*</url-pattern>
</servlet-mapping>
Or when you're already on Servlet 3.0:
@WebServlet(urlPatterns={"/xxx/*", "/yyy/*"})
public class FooServlet extends HttpServlet {
// ...
}
You can if necessary use /yyy/xxx/*
instead of /yyy/*
.
Or if you intend to untouch the servlet mapping, you could also create a Filter
which forwards requests on /yyy/xxx/*
to /xxx/*
. Something like this (basic checks omitted):
@WebFilter("/yyy/xxx/*")
public class FooFilter implements Filter {
// ...
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
HttpServletRequest req = (HttpServletRequest) request;
String oldURI = req.getRequestURI().substring(req.getContextPath().length() + 1);
String newURI = oldURI.substring(oldURI.indexOf("/"));
req.getRequestDispatcher(newURI).forward(request, response);
}
// ...
}
If you intend to change the URL in the browser address bar from /yyy/xxx/*
to /xxx/*
, then you need to use HttpServletResponse#sendRedirect()
instead of RequestDispatcher#forward()
:
// ...
HttpServletResponse res = (HttpServletResponse) response;
res.sendRedirect(newURI);
Upvotes: 4
Reputation: 6179
I don't think the problem is with your servlet mapping. I think it is with how you're doing your redirects. Try this for your redirect logic...
response.sendRedirect(request.getRequestURI().replace("Patients", "Insurance"));
This way you don't have to mess with if statements as it should work in both situations.
Upvotes: 1