1

I'm writing a servlet-filter as the solution of this question:

Is it a good idea to filter inside a JSF template?

now, the idea is to create a big filter to check all privilegies and give the access or not to a certain user. I create a Map to contains all privilegies for all sub applications and it has the sub application's id (a Long value) as Key and for the value another Map that contains other important informations. The controller classes are named class1Controller, class2Controller ecc and the subapplications are stored in many folder named class1, class2 ecc... The last thing that I must say is that all classes have a parameter called applicationID that is the same key of the Map that I mentioned previously. So, what I would do? I can retrieve the subapplication visited by the user using getRequestURI() method from HttpServletRequest, the problem is that I should take the application id from the class linked to that application, so I wrote this code:



    Long id= ((Class.forName(packageName+applicationName+"Controller"))session.getAttribute(applicationName+"Controller")).getApplicationId();

The problem is that the compiler returns that it can't find method getApplicationId()! Can I do something to resolve this problem? Or I must find another way to do that?

Community
  • 1
  • 1
Filippo1980
  • 2,745
  • 5
  • 30
  • 44

2 Answers2

1

The last thing that I must say is that all classes have a parameter called applicationID

It sounds like you want an interface with the getApplicationId method in; make all the controllers implement that interface, and then all you need to do is cast to that interface.

// TODO: Work out a better interface name than "Application" :)
Object attribute = session.getAttribute(applicationName+"Controller");
Long id = ((Application) attribute).getApplicationId();

(You might want to use an abstract base class as described by BalusC - they're variations on the same theme, really.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

You're calling getApplicationId() on a Class instance, but it does not have that method at all.

The normal approach is to let all those classes extend some common base abstract class or an interface which has the method definied and then cast to that base abstract class or interface instead.

E.g. with a base abstract class:

public class FooController extends BaseController {}
public class BarController extends BaseController {}

etc..

Where the base abstract class look like this:

public abstract class BaseController {

    public Long getApplicationId() {
        return applicationId;
    }

}

Then you can get it as follows:

Long id = ((BaseController) session.getAttribute(applicationName + "Controller")).getApplicationId();
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • thanks... I have already that Abstract class and it contains already that parameter but I didn't think to use it... – Filippo1980 Apr 03 '12 at 14:26