views:

47

answers:

1

What's the difference, really, between filters and interceptors? I realize that interceptors fire before and after an action, recursively, and filters can be configured to fire on actions and on certain url patterns. But how do you know when to use each one?

In the book I'm reading on Struts 2, it seems that interceptors are being pushed and I even followed a tutorial to write an Authentication Interceptor to make sure a user is logged in. However, if the user tries to access a URL that doesn't have an action associated with it, the interceptor doesn't catch it, which means I'd have to associate an action with every jsp that I want to be secure. That doesn't seem right.

I can make an Authentication Filter that handles URLs so that I don't have to do that, but then, what's the point of interceptors?

A: 

the interceptor stack fires on every request.
filters only apply to the urls for which they are defined.

edit -- you use one or the other depending on need. Lets say you need to verify a cookie is present for every request. User an interceptor. Lets say that you need to pop up an external app on some requests (driven by a url), use a filter.

I think interceptors are the more commonly used tool...

why would you have a url with no associated action?

hvgotcodes
The interceptor stack fires for only the requests that are defined in the package for which that stack is the default stack, aka I can have actions defined in other packages that the interceptor won't fire for so like a filter, it can be selective. A filter can also apply to all urls.To verify if a cookie is present I don't see why you wouldn't just use a filter for that as well.If you have a simple jsp, like an image upload form for example, there might not be any work that I need an action for. Should I be making action classes for every jsp? Even if they're empty?
JPC
no you are right, if there is no point for an action, then don't put one in. Although from what I remember an action can route to a jsp just be returning a string value.I think you'll find that there are lots of ways to do things, so the fact that there is some overlap is natural.
hvgotcodes
I guess I'm just looking for the best practice, and haven't been able to find any answers.Especially with the convention plugin now, if I have an upload form, I can access it like an action by typing "/upload-form" I don't even have to access the jsp directly. The problem is, this doesn't trigger an interceptor so a filter is the only thing that will catch this.
JPC