views:

24

answers:

2

I have a servlet that correctly returns the data I want from the database when it's doGet() method is called. I would like the doGet() to populate a java bean, which we then reference in the product.jsf page.

I'd like call a URL like http://example.com/product.jsf?id=XXX

And have the single record returned based on the ID based in the URL. I can't figure this out.

A: 

Don't you need to declare a field of the bean with the same name as a field on the page? Most MVC engines can keep the two in sync if they follow the proper naming convention.

Kelly French
A: 

That servlet has too much responsibilities. It is tight coupled. Refactor the data access code into a separate class so that you can reuse it in both the servlet class and the JSF bean.

So, basically:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Long id = Long.valueOf(request.getParameter("id"));
    List<Product> products = productDAO.list(id);
    request.setAttribute("products", products);
    request.getRequestDispatcher("products.jsp").forward(request, response);
}

And:

@ManagedProperty(value="#{param.id}")
private Long id;
private List<Product> products; // +getter

@PostConstruct
public void init() {
    this.products = productDAO.list(id);
}

So that they can operate independently.

BalusC