public class myActorServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String name;
private String user;
private String pass;
private String given_table;
private String tid;
private String firstname;
private String lastname;
private String action;
@Override
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
// connecting to database
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
PrintWriter out = response.getWriter();
name = request.getParameter("screenName");
user = request.getParameter("username");
pass = request.getParameter("password");
tid = request.getParameter("tid");
firstname = request.getParameter("firstname");
lastname = request.getParameter("lastname");
action = request.getParameter("action");
given_table = request.getParameter("tableName");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet JDBC</title>");
out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\">");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello, " + name + " </h1>");
out.println("<h1>Servlet JDBC</h1>");
/////////////////////////
// init connection object
String sqlSelect = "SELECT * FROM `" + given_table + "`";
String sqlInsert = "INSERT INTO `" + given_table + "`(`firstName`, `lastName`) VALUES ('" + firstname + "', '" + lastname + "')";
String sqlUpdate = "UPDATE `" + given_table + "` SET `firstName`='" + firstname + "',`lastName`='" + lastname + "' WHERE `id`=" + tid + "";
String sqlDelete = "DELETE FROM `" + given_table + "` WHERE `id` = '" + tid + "'";
//////////////////////////////////////////////////////////
out.println(
"<p>Reading Table Data...Pass to JSP File...Okay<p>");
ArrayList<Actor> list = new ArrayList<Actor>();
// connecting to database
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/javabase", user, pass);
stmt = con.createStatement();
rs = stmt.executeQuery(sqlSelect);
// displaying records
while (rs.next()) {
Actor actor = new Actor();
actor.setId(rs.getInt("id"));
actor.setLastname(rs.getString("lastname"));
actor.setFirstname(rs.getString("firstname"));
list.add(actor);
}
request.setAttribute("actors", list);
RequestDispatcher view = request.getRequestDispatcher("myActors_1.jsp");
view.forward(request, response);
} catch (SQLException e) {
throw new ServletException("Servlet Could not display records.", e);
} catch (ClassNotFoundException e) {
throw new ServletException("JDBC Driver not found.", e);
} finally {
try {
if (rs != null) {
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (con != null) {
con.close();
con = null;
}
} catch (SQLException e) {
}
}
out.println("</body></html>");
out.close();
}
}