简体   繁体   English

通过基于GET参数的Java Servlet在JSP页面中显示数据库中的单个记录,怎么办?

[英]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. 我有一个servlet,当它的doGet()方法被调用时,它可以正确地从数据库中返回我想要的数据。 I would like the doGet() to populate a java bean, which we then reference in the product.jsf page. 我希望doGet()填充一个Java bean,然后在product.jsf页面中进行引用。

I'd like call a URL like http://example.com/product.jsf?id=XXX 我想呼叫类似http://example.com/product.jsf?id=XXX的URL

And have the single record returned based on the ID based in the URL. 并根据URL中的ID返回单个记录。 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? 您是否不需要声明与该页面上的字段同名的bean的字段? Most MVC engines can keep the two in sync if they follow the proper naming convention. 如果大多数MVC引擎遵循正确的命名约定,则可以使两者保持同步。

That servlet has too much responsibilities. 该servlet承担太多责任。 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. 重构数据访问代码到一个单独的类,这样就可以同时在servlet类和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. 使它们可以独立运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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