Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company.app.logic;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- public class Item {
- private int itemId;
- private String itemName;
- public Item(ResultSet rs) {
- try {
- this.itemId = rs.getInt(1);
- this.itemName = rs.getString(2);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- public String getItemName() {
- return itemName;
- }
- public int getItemId() {
- return itemId;
- }
- public String toString() {
- return itemName;
- }
- }
- package com.company.app.logic;
- import java.sql.*;
- import java.util.*;
- public class Main {
- private static Main instance = new Main();
- private static Connection connection;
- private Main() {
- try {
- Class.forName("com.mysql.jdbc.Driver");
- String url = "jdbc:mysql://localhost:3306/maindb";
- connection = DriverManager.getConnection(url, "root", "root");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public static Main getInstance() {
- return instance;
- }
- public List<Item> getItems() {
- List<Item> items = new ArrayList<>();
- Statement statement = null;
- ResultSet rs = null;
- try {
- statement = connection.createStatement();
- rs = statement.executeQuery("SELECT * FROM items");
- while (rs.next()) {
- Item g = new Item(rs);
- items.add(g);
- }
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- try {
- if (rs != null) {
- rs.close();
- }
- if (statement != null) {
- statement.close();
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- return items;
- }
- }
- package com.company.app.web;
- import com.company.app.logic.Item;
- import com.company.app.logic.Main;
- import javax.servlet.ServletException;
- import javax.servlet.annotation.WebServlet;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.util.List;
- @WebServlet("/items")
- public class MainServlet extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- resp.setContentType("text/html;charset=utf-8");
- PrintWriter pw = resp.getWriter();
- pw.println("<table border=1>");
- try {
- List<Item> l = Main.getInstance().getItems();
- for (Item item : l) {
- pw.println("<tr>");
- pw.println("<td>" + item.getItemId() + "</td>");
- pw.println("<td>" +item.getItemName() + "</td>");
- pw.println("</tr>");
- }
- } catch (Exception e) {
- throw new ServletException(e);
- }
- pw.println("</table>");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement