Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Spring MVC Controller with Inheritance

Can I do the following in Spring MVC

Suppose I have the Base GenericController as follows with one request mapping "/list"

@Controller
public class GenericController<T>{

    @RequestMapping(method = RequestMethod.GET, value = "/list")
    public @ResponseBody List<T> getMyPage(){
        // returns list of T
    }

}

Below are my two controllers

@Controller(value = "/page1")
public class Page1Controller extends GenericController<Page1>{

}

@Controller(value = "/page2")
public class Page2Controller extends GenericController<Page2>{

}

Now will i be able to access the url "/page1/list" and "/page2/list" where first goes to Page1Controller and second goes to Page2Controller.

like image 550
zdesam Avatar asked Mar 13 '13 10:03

zdesam


1 Answers

That's not possible and was already rejected, see SPR-10089. I think this would be somewhat confusing and in addition, it is very unlikely that those method behave exactly the same besides the different mapping. But you can use delegation instead:

public class BaseController<T> {
    public List<T> getPageList(){
        // returns list of T
    }
}

@Controller(value = "/page1")
public class Page1Controller extends BaseController<Page1>{
    @RequestMapping(method = RequestMethod.GET, value = "/list")
    public @ResponseBody List<Page1> getMyPage() {
      return super.getPageList();
    }    
}

@Controller(value = "/page2")
public class Page2Controller extends BaseController<Page2>{
    @RequestMapping(method = RequestMethod.GET, value = "/list")
    public @ResponseBody List<Page2> getMyPage() {
      return super.getPageList();
    }
}
like image 186
Robin Avatar answered Sep 21 '22 12:09

Robin