How to use Url-rewriting using Java in NetBeansIDE
URL Rewriting format - ( url?paramName=paramValue )
1. In your web project make web page (say index.jsp) having a link as:
<a href="FetchDataServlet">Fetch Data from DB...</a>
2. Make a Servlet (say 'FetchDataServlet') and write code to fetch all the record on web page.
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/testdb", "root", "root");
PreparedStatement ps = con.prepareStatement("select * from test2");
ResultSet rs = ps.executeQuery();
out.print("<table border='1'>");
out.print("<tr><th>Serial No.</th><th>name</th><th>Delete</th></tr>");
while(rs.next()){
out.println("<tr>");
out.print("<td>"+rs.getInt(1)+"</td>");
out.print("<td>"+rs.getString(2)+"</td>");
out.print("<td><a href='DeleteServlet?row="+rs.getInt(1)+"'>Delele this row</a></td>");
out.println("</tr>");
}
out.println("</table>");
}catch(Exception e){
e.printStackTrace();
}
3. Make another Servlet (say 'DeleteServlet') and write code to delete record as:
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/testdb", "root", "root");
PreparedStatement ps = con.prepareStatement("delete from test2 where S_No="+request.getParameter("row"));
int rs = ps.executeUpdate();
if(rs>0){
out.println("row is deleted successfully");
RequestDispatcher rd = request.getRequestDispatcher("FetchDataServlet");
rd.forward(request, response);
}else{
out.print("an error occurred");
}
}catch(Exception e){
e.printStackTrace();
}
4. Build path for required jars
5. Run the Project
6. Finish.
Thank You :)
Comments
Post a Comment