Hi sir, I would like to know how to send the form data from html page to database by calling servlet code from html page .
Hello Friend,
Try the following code:
1)callServlet.html:
<html> <center><h3>Registration Form</h3></center> <form method="post" action="http://localhost:8080/examples/Registration"> <center> <table> <tr><td>ID:</td><td><input type="text" name="userId" size="20"></td></tr> <tr><td>First Name:</td><td><input type="text" name="firstname" size="20"></td></tr> <tr><td>Last Name:</td><td><input type="text" name="lastname" size="20"></td></tr> <tr><td>Email: </td><td><input type="text" name="email" size="20"></td></tr> <tr><td>City: </td><td><input type="text" name="city" size="20"></td></tr> <tr><td>State: </td><td><input type="text" name="state" size="20"></td></tr> <tr><td>Country: </td><td> <input type="text" name="country" size="20"></td></tr> <tr><td><input type="submit" value="Submit" name="B1"></td><td><input type="reset" value="Reset" name="B2"></td></tr> </table> </center> </form> </html>
2)Registration.java:
import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class Registration extends HttpServlet{ public void init(ServletConfig config) throws ServletException{ super.init(config); } public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{ String connectionURL = "jdbc:mysql://localhost:3306/test"; Connection connection=null; ResultSet rs; res.setContentType("text/html"); PrintWriter out = res.getWriter(); String uId = req.getParameter("userId"); String fname = req.getParameter("firstname"); String lname = req.getParameter("lastname"); String email = req.getParameter("email"); String state = req.getParameter("state"); String city = req.getParameter("city"); String country = req.getParameter("country"); try{ Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection(connectionURL, "root", "root"); String sql = "insert into employee(empid,firstname,lastname,email,state,city,country) values (?,?,?,?,?,?,?)"; PreparedStatement pst = connection.prepareStatement(sql); pst.setString(1, uId); pst.setString(2, fname); pst.setString(3, lname); pst.setString(4, email); pst.setString(5, state); pst.setString(6, city); pst.setString(7, country); int numRowsChanged = pst.executeUpdate(); out.println("Hello:"); out.println("'"+fname+"'"); pst.close(); } catch(Exception e){ out.println(e); } } }
3)Do the servlet mapping in web.xml:
<servlet> <servlet-name>Registration</servlet-name> <servlet-class>Registration</servlet-class> </servlet> <servlet-mapping> <servlet-name>Registration</servlet-name> <url-pattern>/Registration</url-pattern> </servlet-mapping>
Thanks
thanks for your answer
what is i want to separate many names by semicolon how should i do it in html?
Ads