Spring MVC : too much attributes in the model

2019-07-30 03:38发布

I have a very basic question on spring-mvc (Model). I was working on a project in which we were setting so many addributes in Model(i.e. model.addAttribute(..). My question is that Is there any design-patterns that i can use to avoid so many addAttributes?

I know that I can create a bean/ form and inside it I can create respective setters/getters also but I am just looking for any other option if available.

Please suggest.

2条回答
别忘想泡老子
2楼-- · 2019-07-30 04:21

If you want to use a design pattern to solve a problem you really need to look at how all of them interact. Have you looked up different design patterns? Have you considered making more Objects so you can split them up and generalize them, template method if you know design patterns.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-07-30 04:31

There is no special design pattern, just some Spring or general techniques to avoid too much addAttribute calls inside a given controller.

If you have attributes that you will always need in your view (like a particular object, a list, booleans such as "isXXXActivated" or "showThis", etc.), you could just add methods of the sort in your controller :

@ModelAttribute("isXXXActivated")
public boolean isXXXActivated(){
    return isXXXActivated;
}

This will add "isXXXActivated" in your model everytime your controller is called.

If you add the same attributes accross all your controllers, you could consider adding them in a super controller (a spring @Controller can extend another @Controller without problems).

Finally, if some attributes belong to a group, you can group them as fields of an object. Then you just add this object as an attribute. Example : grouping display conditions into a Display class.

查看更多
登录 后发表回答