Damien Cooke
Damien Cooke

Reputation: 713

injecting EJB into JSP

I have been using EJBs with servlets for many years, but I need to use them in a JSP page and I am struggling. I am using Glassfish 4.1

I have an entity something like this:

public class Address implements Serializable, EntityToJson {
  private static final long serialVersionUID = 1L;

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;

  @Column(name="addressType")
  @Enumerated(EnumType.ORDINAL)
  private AddressType addressType;

  @Column(name="streetLineOne")
  private String streetLineOne;

  @Column(name="city")
  private String city;

  @Column(name="adState")
  private String state;

  ...

and the interface like this:

public interface AddressService {
  public Address createAddress(final JsonObject addressPayload) throws AddressException;
  ...    
}

So in my Servlet I would do something like:

@EJB AddressService addressService;

and use it like this

Address address = addressService.createAddress(addressJson);

How do I do this in JSP? Everything I try doesn't seem to be working.

Upvotes: 0

Views: 1385

Answers (2)

gergelymolnarpro
gergelymolnarpro

Reputation: 21

You can do it via servlet: https://github.com/readonlynetwork/sandbox/tree/master/jsp-and-ejb

request.setAttribute("ejbObj", ejbObj);     
request.getRequestDispatcher("/page.jsp").forward(request, response);

Upvotes: 0

Maksym
Maksym

Reputation: 4574

It's bad idea from design point, but anyway you can get it via lockup in jndi.

Like:

AddressService addressService = (AddressService) new InitialContext().lookup("java:comp/env/AddressService");

Upvotes: 2

Related Questions