Lucas Batistussi
Lucas Batistussi

Reputation: 2343

Is it possible to implement JSP usebean as an annotation?

I would like implement JSP useBean taglib as a class annotation... Is possible? How If so, what is the best (easy and efficient) way to do this?

Example:

  <jsp:useBean id="p" class="beans.Person" scope="application"></jsp:useBean>

---->

  //Custom annotation goes here...
  @ManagedBean
  public class Bean {

  }

Upvotes: 1

Views: 981

Answers (1)

BalusC
BalusC

Reputation: 1108722

There's no direct way using the standard JSP facilities. The oldschool <jsp:useBean> approach is also far from MVC as there's no means of a controller. Just pick an existing MVC framework which supports JSP as View, such as Spring MVC, JSF, etc (although JSF uses since version 2.0 JSP's successor Facelets as default View technology) and use its managed bean facilities. Modern MVC frameworks supports annotations.

In this particular case, with an application scoped bean, a completely different alternative using annotations without the need for a MVC framework is to use a ServletContextListener which is annotated with @WebListener.

@WebListener
public void Config implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent event) {
        event.getServletContext().setAttribute("p", new Person());
    }

    // ...
}

(although it's only pretty strange to have something like a Person in the application scope...)

For the session scope you could implement HttpSessionListener and for the request scope the ServletRequestListener. It's only pretty clumsy this way. I'd really consider a decent MVC framework.

Upvotes: 1

Related Questions