CheckBox Values into Database By Servlets


SUBMITTED BY: anilkumarsomasi

DATE: May 2, 2016, 7:12 p.m.

FORMAT: Text only

SIZE: 2.6 kB

HITS: 7133

  1. CheckBox Values into Database By Servlets
  2. o By this Example you will know the following things.
  3.  How to Access Checkbox values into Servlet
  4.  How to Convert Array Values into Single Object
  5.  How to Append String Values to String Builder
  6.  Convert StringBuilder Object to String Value
  7. Example:
  8. HTML Code:
  9. <body>
  10. <FORM ACTION="send">
  11. Favourite Colors
  12. <input type="checkbox" name="colors" value="RED"checked="checked">RED
  13. <input type="checkbox" name="colors" value="GREEN" >GREEN
  14. <input type="checkbox" name="colors" value="YELLOW" >YELLOW
  15. <input type="checkbox" name="colors" value="BLUE" >BLUE <br>
  16. <input type="submit" value="Submit" >
  17. </FORM>
  18. </body>
  19. Java Servlet Code:
  20. import java.io.IOException;
  21. import java.sql.Connection;
  22. import java.sql.DriverManager;
  23. import java.sql.PreparedStatement;
  24. import javax.servlet.ServletException;
  25. import javax.servlet.annotation.WebServlet;
  26. import javax.servlet.http.HttpServlet;
  27. import javax.servlet.http.HttpServletRequest;
  28. import javax.servlet.http.HttpServletResponse;
  29. @WebServlet("/send")
  30. public class MyServlet extends HttpServlet {
  31. private static final long serialVersionUID = 1L;
  32. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  33. throws ServletException, IOException {
  34. doProceed(request, response);
  35. }
  36. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  37. throws ServletException, IOException {
  38. doProceed(request, response);
  39. }
  40. protected void doProceed(HttpServletRequest request, HttpServletResponse response)
  41. throws ServletException, IOException {
  42. // 1.getting values from html and assign to array
  43. String colors[] = request.getParameterValues("colors");
  44. // 2. creating StringBuilder Object
  45. StringBuilder color = new StringBuilder();
  46. // 3. Appending Selected Values to StrinBuilder
  47. for (String str : colors) {
  48. color.append(str + " ");
  49. }
  50. Connection conn = null;
  51. try {
  52. Class.forName("com.mysql.jdbc.Driver");
  53. conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "root");
  54. PreparedStatement pstmt = conn.prepareStatement("insert into colors values (?);");
  55. //4. Converting StringBuilder Object to String
  56. pstmt.setString(1, color.toString());
  57. pstmt.executeUpdate();
  58. } catch (Exception e) {
  59. e.printStackTrace();
  60. }
  61. }
  62. }
  63. Output:
  64. 1 H.N0 15-20/677/8
  65. 2 Madahapur
  66. 3 Hitech City
  67. 4 Hyderabad
  68. 5 Telangana

comments powered by Disqus