TYBBA (CA)
Steps to run JAVA Servlet + jdbc Programs
1. In Eclipse :
Window -> Preferences -> Server ->Runtime Environment
Add
Select Apache Tomcat 10.1
Select the folder where Tomcat is stored
Apply
2. Create New Project
Web -> Dynamic Web Project
Select Generate [Link] development Descriptor
3. Create Home Page html file
src->webapp->new html file
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form name="MyForm" action="MyClass">
<input type="submit">
</form>
</body>
</html>
4. Java Resources -> Create New Package
5. In new Package create new Servlet
Servlet Name = MyClass
6. Add mysql / postgresql driver .jar file
Project -> Properties -> Java Build Path -> Libraries
Add External JAR
Select .jar file
Apply
1
Page
7. Type following Code
package Mypackage;
import [Link].*;
import [Link];
import [Link].*;
import [Link].*;
import [Link].*;
/**
* Servlet implementation class MyClass
*/
public class MyClass extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
private static final String URL =
"jdbc:mysql://localhost:3306/school";
private static final String USER = "root";
private static final String PASSWORD = "pmd123";
public MyClass() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request,
HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
// TODO Auto-generated method stub
[Link]().append("Served at:
").append([Link]());
[Link]("text/html");
PrintWriter out = [Link]();
try {
[Link]("[Link]");
Connection conn = [Link](URL,
USER, PASSWORD);
2
String query="insert into student values(?,?)";
Page
PreparedStatement stmt = [Link](query);
[Link](1, 1);
[Link](2, "Ram");
[Link]();
[Link]("Connected");
query="SELECT * FROM student";
Statement st=[Link]();
ResultSet rs = [Link](query);
[Link]("<h2>Database Records:</h2>");
while ([Link]()) {
[Link]("<p>Roll: " + [Link]("Roll") + ",
Name: " + [Link]("Name") + "</p>");
}
[Link]();
[Link]();
[Link]();
} catch (Exception e) {
[Link]("<h3>Error: " + [Link]() + "</h3>");
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request,
HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
// TODO Auto-generated method stub
doGet(request, response);
}
8. Save and Click on Project Name
Run -> Run As -> Run on Server
Webpage will open in Chrome -> Click on submit
3
Page