开发者

Display single record from database in JSP page through Java Servlet based on GET parameter, how?

开发者 https://www.devze.com 2023-01-09 13:08 出处:网络
I have a servlet that correctly returns the data I want from the database when it\'s doGet() method is called.I would开发者_StackOverflow like the doGet() to populate a java bean, which we then refere

I have a servlet that correctly returns the data I want from the database when it's doGet() method is called. I would开发者_StackOverflow 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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消