Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In a well designed MVC approach, the JSP file should not contain any line of Java code and the servlet class should not contain any line of JDBC code.</p> <p>Assuming that you want to show a list of products in a webshop, the following code needs to be created.</p> <ul> <li><p>A <code>Product</code> class representing a real world entity of a product, it should be just a <a href="https://stackoverflow.com/questions/1727603">Javabean</a>.</p> <pre><code>public class Product { private Long id; private String name; private String description; private BigDecimal price; // Add/generate getters/setters/c'tors/equals/hashcode boilerplate. } </code></pre></li> <li><p>A <a href="http://balusc.omnifaces.org/2008/07/dao-tutorial-data-layer.html" rel="noreferrer">DAO</a> class which does all the nasty JDBC work and returns a nice <code>List&lt;Product&gt;</code>.</p> <pre><code>public class ProductDAO { private DataSource dataSource; public ProductDAO(DataSource dataSource) { this.dataSource = dataSource; } public List&lt;Product&gt; list() throws SQLException { List&lt;Product&gt; products = new ArrayList&lt;Product&gt;(); try ( Connection connection = dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT id, name, description, price FROM product"); ResultSet resultSet = statement.executeQuery(); ) { while (resultSet.next()) { Product product = new Product(); product.setId(resultSet.getLong("id")); product.setName(resultSet.getString("name")); product.setDescription(resultSet.getString("description")); product.setPrice(resultSet.getBigDecimal("price")); products.add(product); } } return products; } } </code></pre></li> <li><p>A <a href="https://stackoverflow.com/tags/servlets/info">servlet</a> class which obtains the list and puts it in the request scope.</p> <pre><code>@WebServlet("/products") public class ProductsServlet extends HttpServlet { @Resource(name="jdbc/YourDB") // For Tomcat, define as &lt;Resource&gt; in context.xml and declare as &lt;resource-ref&gt; in web.xml. private DataSource dataSource; private ProductDAO productDAO; @Override public void init() { productDAO = new ProductDAO(dataSource); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { List&lt;Product&gt; products = productDAO.list(); request.setAttribute("products", products); // Will be available as ${products} in JSP request.getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response); } catch (SQLException e) { throw new ServletException("Cannot obtain products from DB", e); } } } </code></pre></li> <li><p>Finally a <a href="https://stackoverflow.com/tags/jsp/info">JSP</a> file in <code>/WEB-INF/products.jsp</code> which uses <a href="https://stackoverflow.com/tags/jstl/info">JSTL</a> <code>&lt;c:forEach&gt;</code> to iterate over <code>List&lt;Product&gt;</code> which is made available in <a href="https://stackoverflow.com/tags/el/info">EL</a> by <code>${products}</code>, and uses JSTL <code>&lt;c:out&gt;</code> to escape string properties in order to avoid <a href="https://stackoverflow.com/questions/2658922">XSS</a> holes when it concerns user-controlled input.</p> <pre class="lang-xml prettyprint-override"><code>&lt;%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %&gt; &lt;%@ taglib uri="http://java.sun.com/jsp/jstl/format" prefix="fmt" %&gt; ... &lt;table&gt; &lt;c:forEach items="${products}" var="product"&gt; &lt;tr&gt; &lt;td&gt;${product.id}&lt;/td&gt; &lt;td&gt;&lt;c:out value="${product.name}" /&gt;&lt;/td&gt; &lt;td&gt;&lt;c:out value="${product.description}" /&gt;&lt;/td&gt; &lt;td&gt;&lt;fmt:formatNumber value="${product.price}" type="currency" currencyCode="USD" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/c:forEach&gt; &lt;/table&gt; </code></pre></li> </ul> <p>To get it to work, just call the servlet by its URL. Provided that the servlet is annotated <code>@WebServlet("/products")</code> or mapped in <code>web.xml</code> with <code>&lt;url-pattern&gt;/products&lt;/url-pattern&gt;</code>, then you can call it by <code>http://example.com/contextname/products</code></p> <h3>See also:</h3> <ul> <li><a href="https://stackoverflow.com/questions/3177733">How to avoid Java code in JSP files?</a></li> <li><a href="https://stackoverflow.com/questions/2349633">doGet and doPost in Servlets</a></li> <li><a href="https://stackoverflow.com/questions/2299469">How should I connect to JDBC database / datasource in a servlet based application?</a></li> <li><a href="https://stackoverflow.com/questions/3541077">Design Patterns web based applications</a></li> <li><a href="https://stackoverflow.com/questions/2047122/requestdispatcher-forward-vs-httpservletresponse-sendredirect/2048640#2048640">RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()</a></li> <li><a href="https://stackoverflow.com/questions/9201128/how-to-map-a-resultset-with-unknown-amount-of-columns-to-a-list-and-display-it-i">How to map a ResultSet with unknown amount of columns to a List and display it in a HTML table?</a></li> <li><a href="https://stackoverflow.com/questions/3078701/how-do-i-pass-current-item-to-java-method-by-clicking-a-hyperlink-or-button-in-j/">How do I pass current item to Java method by clicking a hyperlink or button in JSP page?</a></li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload