Connect Servlet to the Database
Connect Servlet to the Database with Example
Files Required
·
index.html
·
ServletDatabaseConnect.java
·
web.xml
·
ojdbc14.jar
index.html
1
2
3
4
5
6
|
<form action="show"
method="post">
<font face="verdana"
size="2">
Enter Table Name
:<input type="text" name="table">
<input
type="submit" value="Display">
</font>
</form>
|
ServletDatabaseConnect.java
package java4s;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletDatabaseConnect extends HttpServlet
{
protected void doPost(HttpServletRequest
req,HttpServletResponse res)throws ServletException,IOException
{
PrintWriter pw=res.getWriter();
res.setContentType("text/html");
String
tb=req.getParameter("table");
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","admin");
Statement
st=con.createStatement();
System.out.println("connection established successfully...!!");
ResultSet rs=st.executeQuery("Select
* from "+tb);
pw.println("<table border=1>");
while(rs.next())
{
pw.println("<tr><td>"+rs.getInt(1)+"</td><td>"+rs.getString(2)+"</td>"+
"<td>"+rs.getString(3)+"</td></tr>");
}
pw.println("</table>");
pw.close();
}
catch (Exception e){
e.printStackTrace();
}
}
}
web.xml
<web-app>
<servlet>
<servlet-name>ServletDBConnect</servlet-name>
<servlet-class>java4s.ServletDatabaseConnect</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletDBConnect</servlet-name>
<url-pattern>/show</url-pattern>
</servlet-mapping>
</web-app>
Comments
Post a Comment