How to call servlet in JSP?
Hi Friend,
Try the following code:
1)form.jsp:
<html> <form action="../InsertServlet" method="post"> <table align=center border=0 cellspacing=0 cellpadding=10 width=100 height=0 bgcolor=#faebd7> <tr> <td>Name</td> <td><input type=text name="name" size=20></td> </tr> <tr> <td>Address</td> <td><input type=text name="address" size=30></td> </tr> <tr> <td>Tel no</td> <td><input type=text name="no" size=20></td> </tr> </table> <br> <br> <center> <input type=submit name=submit value=submit> </form> </html>
2)InsertServlet.java:
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class InsertServlet extends HttpServlet {
public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String name=req.getParameter("name");
String address=req.getParameter("address");
int no=Integer.parseInt(req.getParameter("no"));
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
Statement st=con.createStatement();
int i=st.executeUpdate("insert into data(name,address,telno) values('"+name+"','"+address+"',"+no+")");
out.println("Data is inserted successfully");
con.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
For more information, visit the following links:
Thanks