CheckBox Values into Database By Servlets
o By this Example you will know the following things.
How to Access Checkbox values into Servlet
How to Convert Array Values into Single Object
How to Append String Values to String Builder
Convert StringBuilder Object to String Value
Example:
HTML Code:
<body>
<FORM ACTION="send">
Favourite Colors
<input type="checkbox" name="colors" value="RED"checked="checked">RED
<input type="checkbox" name="colors" value="GREEN" >GREEN
<input type="checkbox" name="colors" value="YELLOW" >YELLOW
<input type="checkbox" name="colors" value="BLUE" >BLUE <br>
<input type="submit" value="Submit" >
</FORM>
</body>
Java Servlet Code:
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/send")
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doProceed(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doProceed(request, response);
}
protected void doProceed(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 1.getting values from html and assign to array
String colors[] = request.getParameterValues("colors");
// 2. creating StringBuilder Object
StringBuilder color = new StringBuilder();
// 3. Appending Selected Values to StrinBuilder
for (String str : colors) {
color.append(str + " ");
}
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "root");
PreparedStatement pstmt = conn.prepareStatement("insert into colors values (?);");
//4. Converting StringBuilder Object to String
pstmt.setString(1, color.toString());
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
1 H.N0 15-20/677/8
2 Madahapur
3 Hitech City
4 Hyderabad
5 Telangana