简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM