I'm checking the login status of a user (permissions) and I would like to redirect him to another page if he hasn't the correct permissions to visit a particular .jsp page.
The canonical approach is to use a servlet Filter
for this. You need to group those restricted pages behind a common URL pattern, e.g. /app/*
, /secured/*
, /private/*
or whatever and then map the Filter
on exactly that URL pattern which does roughly the following in the doFilter()
method (assuming that you're storing the logged-in user in the session the usual way).
@WebFilter("/app/*")
public class AuthenticationFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
if (req.getSession().getAttribute("user") != null) {
// User is logged in, so just continue request.
chain.doFilter(request, response);
} else {
// User is not logged in, so redirect to some index/login page.
res.sendRedirect(req.getContextPath() + "/login.jsp");
}
}
// ...
}
This keeps the JSPs free from copypasted clutter and workarounds to prevent the response from being committed before the redirect.