DbSQLServlet.java 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package hello;
  2. import java.io.IOException;
  3. import java.sql.Connection;
  4. import java.sql.PreparedStatement;
  5. import java.sql.ResultSet;
  6. import java.sql.SQLException;
  7. import java.util.Random;
  8. import java.util.concurrent.ThreadLocalRandom;
  9. import javax.annotation.Resource;
  10. import javax.servlet.ServletException;
  11. import javax.servlet.http.HttpServlet;
  12. import javax.servlet.http.HttpServletRequest;
  13. import javax.servlet.http.HttpServletResponse;
  14. import javax.sql.DataSource;
  15. /**
  16. * Handles the single-query database test using a SQL database with a
  17. * Servlet-container managed pool.
  18. */
  19. @SuppressWarnings("serial")
  20. public class DbSQLServlet extends HttpServlet {
  21. // Database details.
  22. private static final String DB_QUERY = "SELECT * FROM World WHERE id = ?";
  23. // Database connection pool.
  24. @Resource(name = "jdbc/hello_world")
  25. private DataSource dataSource;
  26. @Override
  27. protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
  28. IOException {
  29. World world = null;
  30. // Fetch some rows from the database.
  31. try (Connection conn = dataSource.getConnection()) {
  32. Common.modifySQLConnectionSettings(conn);
  33. try (PreparedStatement statement = conn.prepareStatement(DB_QUERY,
  34. ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) {
  35. statement.setInt(1, Common.getRandom());
  36. try (ResultSet results = statement.executeQuery()) {
  37. results.next(); // Here the expectation is ONLY only one
  38. // result row
  39. world = new World(results.getInt("id"), results.getInt("randomNumber"));
  40. }
  41. }
  42. } catch (SQLException sqlex) {
  43. throw new ServletException(sqlex);
  44. }
  45. // Set content type to JSON
  46. res.setHeader(Common.HEADER_CONTENT_TYPE, Common.CONTENT_TYPE_JSON);
  47. // Write JSON encoded message to the response.
  48. Common.MAPPER.writeValue(res.getOutputStream(), world);
  49. }
  50. }