Writing Filters to intercept request.
Ok, I am writing a filter to intercept all request to jsp, servlets to check if the user has login.
But I have a problem, I wanted a better control like if this user is not allow to go servlet A. the filter will intercept him. But based on /* mapping. I can't control which servlet the user wish to go. Please advise
[330 byte] By [
liangtehza] at [2007-11-27 11:56:09]

# 1
private void checkPrivileges(ServletRequest req, ServletResponse res,
FilterChain chain )
{
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)res;
try
{
// Grant all request to index.jsp
if (request.getRequestURI().endsWith("index.jsp"))
{
chain.doFilter(req, res);
}
else
{
HttpSession session = request.getSession();
String username = (String)session.getAttribute("username");
// Never login goto homepage
if (username == null)
{
response.sendRedirect("index.jsp");
}
else
{
chain.doFilter(req, res); // Permission granted
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
This is my code to intercept all request to my application. So far I am able to block out all request to jsp if he/she does not login.
But my problem is only certain group of users are allow to access Servlet A. But I am unable to know the user is heading to which servlet..
# 2
> But based on /* mapping. I can't control which servlet the user wish to go.
If *all* servlets are mapped on /*, then you'd better to write this servlet-specific-user-blocking logic in the servlet itself.
By the way, that endsWith("index.jsp") is really a weak control. What if the user calls index.jsp?foo=bar ?
# 3
index.jsp is my web application login page. no no query string will be pass in.
As for servlet access control. Example I only want User A to access Servlet A,B only and User B access Servlet C & D. My doing /* I can effectively block out all request to my web application(jsp, servlets) and my images also get filter out.
So I use filter to map each servlets individually.
# 4
> index.jsp is my web application login page. no no
> query string will be pass in.
Never trust user input.
> As for servlet access control. Example I only want
> User A to access Servlet A,B only and User B access
> Servlet C & D. My doing /* I can effectively block
> out all request to my web application(jsp, servlets)
> and my images also get filter out.
>
> So I use filter to map each servlets individually.
Yes, I understand that. Like I said, if all servlets are mapped on /*, you need to implement the user-block logic in the servlet itself.
# 5
Ok, I get what you mean. I will do the appropriate check at each servlet. 1 more question by blocking /* url. My images for the webapp also got filter out. How do I exclude the directories like /image , /css for my webapps?
# 6
If you want to keep the filter mapping on /*, then you need to exclude the images inside the filter by checking the requestURI.