how to insert multiple selection values from html into database using servlets
1)form.jsp:
<html> <body> <form method = "post" action = "/Examples/GetParameterValues"> <p>Which of the programming languages you like the most</p> <select name="lang"> <option value="C/C++">C/C++</option> <option value="Java">C/C++</option> <option value=".NET">C/C++</option> <option value="Perl">C/C++</option> <option value="Pascal">C/C++</option> </select> </form> </body> </html>
2) GetParameterValues.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class GetParameterValues extends HttpServlet{ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); String[] lang = request.getParameterValues("lang"); for(int i=0; i<whisky.length; i++){ pw.println("<br>Language : " + lang[i]); } } }
3)web.xml file
<servlet> <servlet-name>GetParameterValues</servlet-name> <servlet-class>GetParameterValues</servlet-class> </servlet> <servlet-mapping> <servlet-name>GetParameterValues</servlet-name> <url-pattern>/GetParameterValues</url-pattern> </servlet-mapping>
Put attribute multiple in select tag. I forget to do that.Anyways change the form.jsp to the following code:
<html> <body> <form method = "post" action = "/Examples/GetParameterValues"> <p>Which of the programming languages you like the most</p> <select name="lang"> <option value="C/C++">C/C++</option> <option value="Java">C/C++</option> <option value=".NET">C/C++</option> <option value="Perl">C/C++</option> <option value="Pascal">C/C++</option> </select> </form> </body> </html>
Modify the servlet. It actually displays the selected values. So ti insert the selected values, try this:
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class GetParameterValues extends HttpServlet{ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String languages=" "; response.setContentType("text/html"); PrintWriter pw = response.getWriter(); String[] lang = request.getParameterValues("lang"); for(int i=0; i<lang.length; i++){ lanuages+=lang[i]+" "; } try{ Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root" ); Statement st=conn.createStatement(); st.executeUpdate("insert into data(languages) values('"+languages+"')"); pw.println("Inserted Successfully!"); } catch(Exception e){} } }
import java.sql.* to the above servlet code.
Ads