java - Spring MVC parent template model component -
i'm using spring mvc 4 , i'm building site template requires several common components across pages, such login status, cart status, etc. example of controller function this:
@requestmapping( path = {"/"}, method=requestmethod.get) public modelandview index() { modelandview mav = new modelandview("index"); mav.addobject("listproducts", products ); mav.addobject("listcategories", menucategoriasutils.obtaincategories()); return mav; }
what way/pattern feed these elements not belong controller calling don't repeat on , on unrelated operations in every method of every controller?
thanks!
there several approaches show common data in views. 1 of them using of @modelattributte
annotation.
lets say, have user login, needed shown on every page. also, have security service, security information current login. have create parent class controllers, add common information.
public class commoncontroller{ @autowired private securityservice securityservice; @modelattribute public void addsecurityattributes(model model){ user user = securityservice.getcurrentuser(); model.addattribute("currentlogin", user.getlogin()); //... add other attributes need show } }
note, don't need mark commoncontroller
@controller
annotation. because you'll never use controller directly. other controllers have inherited commoncontroller
:
@controller public class productcontroller extends commoncontroller{ //... controller methods }
now should nothing add currentlogin
model attributes. added every model automatically. , can access user login in views:
... <body> <span>current login: ${currentlogin}</span> </body>
more details usage of @modelattribute
annotation can find here in documentation.
Comments
Post a Comment