Ender Wiggin
Ender Wiggin

Reputation: 424

Design pattern for managing beans in jsp, servlet

I am involved in a jsp/servlet application. The application stores objects needed in session or request. However the same object can be injected into session or request in multiple locations. In other words, instead of writing

HomeBean homeBean = (HomeBean) request.getSession(false).getAttribute("homeBean");

I will write

HomeBean homeBean = BeanStore.getHomeBean();

Am I overthinking or overdesigning ?

Upvotes: 0

Views: 124

Answers (1)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340763

In some frameworks like or you can inject session or even some session attribute directly to your business component, something like:

@Inject
private HomeBean homeBean;

Also instead of polluting your code with HTTP session access code just fetch the object once and pass it where needed. It will make reading and testing easier.

Note that your BeanStore.getHomeBean() is really hard to write correctly if you really don't want to pass HttpSession directly. Servlet filters and ThreadLocal, here I come! Not to mention I find such static "factory" quite ugly.


Side note, in:

request.getSession(false).getAttribute("homeBean")

request.getSession(false) will often return null, leaving you with nasty NullPointerException. Prefer true or no parameters at all in this case.

Upvotes: 1

Related Questions