-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClickerResponseServlet.java
More file actions
63 lines (55 loc) · 2.82 KB
/
ClickerResponseServlet.java
File metadata and controls
63 lines (55 loc) · 2.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import java.io.*;
import java.sql.*;
import jakarta.servlet.*; // Tomcat 10 (Jakarta EE 9)
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
//import javax.servlet.*; // Tomcat 9 (Java EE 8 / Jakarta EE 8)
//import javax.servlet.http.*;
//import javax.servlet.annotation.*;
@WebServlet("/select") // Configure the request URL for this servlet (Tomcat 7/Servlet 3.0 upwards)
public class ClickerResponseServlet extends HttpServlet {
// The doGet() runs once per HTTP GET request to this servlet.
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set the MIME type for the response message
response.setContentType("text/html");
// Get a output writer to write the response message into the network socket
PrintWriter out = response.getWriter();
// Print an HTML page as the output of the query
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head><title>Query Response</title></head>");
out.println("<body>");
try (
// Step 1: Allocate a database 'Connection' object
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/clicker?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC",
"myuser", "xxxx"); // For MySQL
// The format is: "jdbc:mysql://hostname:port/databaseName", "username", "password"
// Step 2: Allocate a 'Statement' object in the Connection
Statement stmt = conn.createStatement();
) {
// Step 3 & 4 of the database servlet
// Assume that the URL is http://ip-addr:port/clicker/select?choice=x
// Assume that the questionNo is 8 String choice = request.getParameter("choice");
String[] choice = request.getParameterValues("choice");
if (choice != null) {
// Prepare SQL statement to insert the choice into the responses table
String sqlStr = "INSERT INTO responses (questionNo, choice) VALUES (8, '" + choice + "')";
out.println("<p>SQL: " + sqlStr + "</p>"); // For debugging
// Execute the SQL INSERT statement
int count = stmt.executeUpdate(sqlStr);
} else {
// No choice was provided
out.println("<h3>Error: No choice was selected.</h3>");
}
} catch(SQLException ex) {
out.println("<p>Error: " + ex.getMessage() + "</p>");
out.println("<p>Check Tomcat console for details.</p>");
ex.printStackTrace();
} // Step 5: Close conn and stmt - Done automatically by try-with-resources (JDK 7)
out.println("</body></html>");
out.close();
}
}