在设计良好的MVC方法中,JSP文件不应包含任何Java代码行,并且servlet类不应包含任何行的JDBC代码。
假设您想在网上商店中显示产品列表,需要创建以下代码。
>一个产品类代表一个产品的真实世界实体,它应该只是一个Javabean。
public class Product {
private Long id;
private String name;
private String description;
private BigDecimal price;
// Add/generate getters/setters/c'tors/equals/hashcode boilerplate.
}
>一个DAO类,它做所有讨厌的JDBC工作,并返回一个不错的List< Product>。
public class ProductDAO {
private DataSource dataSource;
public ProductDAO(DataSource dataSource) {
this.dataSource = dataSource;
}
public List list() throws SQLException {
List products = new ArrayList();
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;
}
}
> A servlet类,它获取列表并将其放入请求范围。
@WebServlet("/products")
public class ProductsServlet extends HttpServlet {
@Resource("jdbc/YourDB") // For Tomcat, define as in context.xml and declare as 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 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);
}
}
}
>最后在/WEB-INF/products.jsp中使用一个JSP文件,它使用JSTL< c:forEach>迭代List< Product>其由$ {products}在EL中提供,并且使用JSTL< c:out>以逃避字符串属性,以避免XSS孔时,它涉及用户控制的输入。
...
${product.id} |
要使其工作,只需通过其URL调用servlet。如果servlet已注释为@WebServlet(“/ products”)或已在< url-pattern> / products< / url-pattern>下的web.xml中注释,则可以通过http://example.com/上下文名/产品
也可以看看: