Java Program to Develop a Web Application Working with Servlet and JDBC

Aim:

Develop a Web application Working with Servlet and JDBC.

Procedure:

  • Step 1: Open a New Java Web Application on Netbeans Editor.
  • Step 2: Open Netbeans Ide, Choose File -> new Project.
  • Step 3: New Open a New Project and Choose a Web Application and Open a New Servlet File.
  • Step 4: Create a Database in Mysql and Establish a Prepare Jdbc With Java Application.
  • Step 5: the Give Proper Database Connections Through Web Services.
  • Step 6: Write a Prepare Query in Servlet Page.
  • Step 7: Design a Html Page With Label Textbox and Button for Searching.
  • Step 8: Run the Project and Display the Search Result in Browser.
  • Step 9: Save the Project (Ctrl+s).
  • Step 10: Run the Project (F5).

Program:

Index.html

<html>
<body>
<form action="search">
Enter your Rollno:<input type="text" name="regno"/><br/>
<input type="submit" value="search"/>
</form>
</body>
</html> 

Search.java

import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class search extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String rollno=request.getParameter("regno");
int roll=Integer.valueOf(rollno);
try{
Class.forName("com.mysql.jdbc.Driver");
 Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/msc","root","ram
");
PreparedStatement ps=con.prepareStatement("select * from stud where regno=?");
ps.setInt(1,roll);
out.print("<table width=50% border=1>"); 
out.print("<caption>Result:</caption>");
ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
int total=rsmd.getColumnCount();
out.print("<tr>");
for(int i=1;i<=total;i++)
{
out.print("<th>"+rsmd.getColumnName(i)+"</th>");
}
out.print("</tr>");
while(rs.next())
{
out.print("<tr><td>"+rs.getInt(1)+"</td><td>"+rs.getString(2)+"
</td><td>"+rs.getString(3)+"</td><td>"+rs.getString(4)+"</td></tr>");
}
out.print("</table>");
}catch (Exception e2) {e2.printStackTrace();}
finally{out.close();}
}
}

Output:

Leave a Comment