Cheap VPS & Xen Server


Residential Proxy Network - Hourly & Monthly Packages

CRUD Example


A CRUD (Create, Read, Update and Delete) application is the most important application for any project development. In Servlet, we can easily create CRUD application.

Servlet CRUD example

Create “user905” table in Oracle Database with auto incrementing id using sequence. There are 5 fields in it: id, name, password, email and country.

crudtable.jpg

File: index.html

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset=“ISO-8859-1”>
  5. <title>Insert title here</title>
  6. </head>
  7. <body>
  8. <h1>Add New Employee</h1>
  9. <form action=“SaveServlet” method=“post”>
  10. <table>
  11. <tr><td>Name:</td><td><input type=“text” name=“name”/></td></tr>
  12. <tr><td>Password:</td><td><input type=“password” name=“password”/></td></tr>
  13. <tr><td>Email:</td><td><input type=“email” name=“email”/></td></tr>
  14. <tr><td>Country:</td><td>
  15. <select name=“country” style=“width:150px”>
  16. <option>India</option>
  17. <option>USA</option>
  18. <option>UK</option>
  19. <option>Other</option>
  20. </select>
  21. </td></tr>
  22. <tr><td colspan=“2”><input type=“submit” value=“Save Employee”/></td></tr>
  23. </table>
  24. </form>
  25. <br/>
  26. <a href=“ViewServlet”>view employees</a>
  27. </body>
  28. </html>

File: Emp.java

  1. public class Emp {
  2. private int id;
  3. private String name,password,email,country;
  4. public int getId() {
  5.     return id;
  6. }
  7. public void setId(int id) {
  8.     this.id = id;
  9. }
  10. public String getName() {
  11.     return name;
  12. }
  13. public void setName(String name) {
  14.     this.name = name;
  15. }
  16. public String getPassword() {
  17.     return password;
  18. }
  19. public void setPassword(String password) {
  20.     this.password = password;
  21. }
  22. public String getEmail() {
  23.     return email;
  24. }
  25. public void setEmail(String email) {
  26.     this.email = email;
  27. }
  28. public String getCountry() {
  29.     return country;
  30. }
  31. public void setCountry(String country) {
  32.     this.country = country;
  33. }
  34. }

File: EmpDao.java

  1. import java.util.*;
  2. import java.sql.*;
  3. public class EmpDao {
  4.     public static Connection getConnection(){
  5.         Connection con=null;
  6.         try{
  7.             Class.forName(“oracle.jdbc.driver.OracleDriver”);
  8.             con=DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:xe”,“system”,“oracle”);
  9.         }catch(Exception e){System.out.println(e);}
  10.         return con;
  11.     }
  12.     public static int save(Emp e){
  13.         int status=0;
  14.         try{
  15.             Connection con=EmpDao.getConnection();
  16.             PreparedStatement ps=con.prepareStatement(
  17.                          “insert into user905(name,password,email,country) values (?,?,?,?)”);
  18.             ps.setString(1,e.getName());
  19.             ps.setString(2,e.getPassword());
  20.             ps.setString(3,e.getEmail());
  21.             ps.setString(4,e.getCountry());
  22.             status=ps.executeUpdate();
  23.             con.close();
  24.         }catch(Exception ex){ex.printStackTrace();}
  25.         return status;
  26.     }
  27.     public static int update(Emp e){
  28.         int status=0;
  29.         try{
  30.             Connection con=EmpDao.getConnection();
  31.             PreparedStatement ps=con.prepareStatement(
  32.                          “update user905 set name=?,password=?,email=?,country=? where id=?”);
  33.             ps.setString(1,e.getName());
  34.             ps.setString(2,e.getPassword());
  35.             ps.setString(3,e.getEmail());
  36.             ps.setString(4,e.getCountry());
  37.             ps.setInt(5,e.getId());
  38.             status=ps.executeUpdate();
  39.             con.close();
  40.         }catch(Exception ex){ex.printStackTrace();}
  41.         return status;
  42.     }
  43.     public static int delete(int id){
  44.         int status=0;
  45.         try{
  46.             Connection con=EmpDao.getConnection();
  47.             PreparedStatement ps=con.prepareStatement(“delete from user905 where id=?”);
  48.             ps.setInt(1,id);
  49.             status=ps.executeUpdate();
  50.             con.close();
  51.         }catch(Exception e){e.printStackTrace();}
  52.         return status;
  53.     }
  54.     public static Emp getEmployeeById(int id){
  55.         Emp e=new Emp();
  56.         try{
  57.             Connection con=EmpDao.getConnection();
  58.             PreparedStatement ps=con.prepareStatement(“select * from user905 where id=?”);
  59.             ps.setInt(1,id);
  60.             ResultSet rs=ps.executeQuery();
  61.             if(rs.next()){
  62.                 e.setId(rs.getInt(1));
  63.                 e.setName(rs.getString(2));
  64.                 e.setPassword(rs.getString(3));
  65.                 e.setEmail(rs.getString(4));
  66.                 e.setCountry(rs.getString(5));
  67.             }
  68.             con.close();
  69.         }catch(Exception ex){ex.printStackTrace();}
  70.         return e;
  71.     }
  72.     public static List<Emp> getAllEmployees(){
  73.         List<Emp> list=new ArrayList<Emp>();
  74.         try{
  75.             Connection con=EmpDao.getConnection();
  76.             PreparedStatement ps=con.prepareStatement(“select * from user905”);
  77.             ResultSet rs=ps.executeQuery();
  78.             while(rs.next()){
  79.                 Emp e=new Emp();
  80.                 e.setId(rs.getInt(1));
  81.                 e.setName(rs.getString(2));
  82.                 e.setPassword(rs.getString(3));
  83.                 e.setEmail(rs.getString(4));
  84.                 e.setCountry(rs.getString(5));
  85.                 list.add(e);
  86.             }
  87.             con.close();
  88.         }catch(Exception e){e.printStackTrace();}
  89.         return list;
  90.     }
  91. }

File: SaveServlet.java

  1. import java.io.IOException;
  2. import java.io.PrintWriter;
  3. import javax.servlet.ServletException;
  4. import javax.servlet.annotation.WebServlet;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. @WebServlet(“/SaveServlet”)
  9. public class SaveServlet extends HttpServlet {
  10.     protected void doPost(HttpServletRequest request, HttpServletResponse response)
  11.          throws ServletException, IOException {
  12.         response.setContentType(“text/html”);
  13.         PrintWriter out=response.getWriter();
  14.         String name=request.getParameter(“name”);
  15.         String password=request.getParameter(“password”);
  16.         String email=request.getParameter(“email”);
  17.         String country=request.getParameter(“country”);
  18.         Emp e=new Emp();
  19.         e.setName(name);
  20.         e.setPassword(password);
  21.         e.setEmail(email);
  22.         e.setCountry(country);
  23.         int status=EmpDao.save(e);
  24.         if(status>0){
  25.             out.print(“<p>Record saved successfully!</p>”);
  26.             request.getRequestDispatcher(“index.html”).include(request, response);
  27.         }else{
  28.             out.println(“Sorry! unable to save record”);
  29.         }
  30.         out.close();
  31.     }
  32. }

File: EditServlet.java

  1. import java.io.IOException;
  2. import java.io.PrintWriter;
  3. import javax.servlet.ServletException;
  4. import javax.servlet.annotation.WebServlet;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. @WebServlet(“/EditServlet”)
  9. public class EditServlet extends HttpServlet {
  10.     protected void doGet(HttpServletRequest request, HttpServletResponse response)
  11.            throws ServletException, IOException {
  12.         response.setContentType(“text/html”);
  13.         PrintWriter out=response.getWriter();
  14.         out.println(“<h1>Update Employee</h1>”);
  15.         String sid=request.getParameter(“id”);
  16.         int id=Integer.parseInt(sid);
  17.         Emp e=EmpDao.getEmployeeById(id);
  18.         out.print(“<form action=’EditServlet2′ method=’post’>”);
  19.         out.print(“<table>”);
  20.         out.print(“<tr><td></td><td><input type=’hidden’ name=’id’ value='”+e.getId()+“‘/></td></tr>”);
  21.         out.print(“<tr><td>Name:</td><td><input type=’text’ name=’name’ value='”+e.getName()+“‘/></td></tr>”);
  22.         out.print(“<tr><td>Password:</td><td><input type=’password’ name=’password’ value='”+e.getPassword()+”‘/>
  23.                 </td></tr>”);
  24.         out.print(“<tr><td>Email:</td><td><input type=’email’ name=’email’ value='”+e.getEmail()+“‘/></td></tr>”);
  25.         out.print(“<tr><td>Country:</td><td>”);
  26.         out.print(“<select name=’country’ style=’width:150px’>”);
  27.         out.print(“<option>India</option>”);
  28.         out.print(“<option>USA</option>”);
  29.         out.print(“<option>UK</option>”);
  30.         out.print(“<option>Other</option>”);
  31.         out.print(“</select>”);
  32.         out.print(“</td></tr>”);
  33.         out.print(“<tr><td colspan=’2′><input type=’submit’ value=’Edit & Save ‘/></td></tr>”);
  34.         out.print(“</table>”);
  35.         out.print(“</form>”);
  36.         out.close();
  37.     }
  38. }

File: EditServlet2.java

  1. import java.io.IOException;
  2. import java.io.PrintWriter;
  3. import javax.servlet.ServletException;
  4. import javax.servlet.annotation.WebServlet;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. @WebServlet(“/EditServlet2”)
  9. public class EditServlet2 extends HttpServlet {
  10.     protected void doPost(HttpServletRequest request, HttpServletResponse response)
  11.           throws ServletException, IOException {
  12.         response.setContentType(“text/html”);
  13.         PrintWriter out=response.getWriter();
  14.         String sid=request.getParameter(“id”);
  15.         int id=Integer.parseInt(sid);
  16.         String name=request.getParameter(“name”);
  17.         String password=request.getParameter(“password”);
  18.         String email=request.getParameter(“email”);
  19.         String country=request.getParameter(“country”);
  20.         Emp e=new Emp();
  21.         e.setId(id);
  22.         e.setName(name);
  23.         e.setPassword(password);
  24.         e.setEmail(email);
  25.         e.setCountry(country);
  26.         int status=EmpDao.update(e);
  27.         if(status>0){
  28.             response.sendRedirect(“ViewServlet”);
  29.         }else{
  30.             out.println(“Sorry! unable to update record”);
  31.         }
  32.         out.close();
  33.     }
  34. }

File: DeleteServlet.java

  1. import java.io.IOException;
  2. import javax.servlet.ServletException;
  3. import javax.servlet.annotation.WebServlet;
  4. import javax.servlet.http.HttpServlet;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7. @WebServlet(“/DeleteServlet”)
  8. public class DeleteServlet extends HttpServlet {
  9.     protected void doGet(HttpServletRequest request, HttpServletResponse response)
  10.              throws ServletException, IOException {
  11.         String sid=request.getParameter(“id”);
  12.         int id=Integer.parseInt(sid);
  13.         EmpDao.delete(id);
  14.         response.sendRedirect(“ViewServlet”);
  15.     }
  16. }

File: ViewServlet.java

  1. import java.io.IOException;
  2. import java.io.PrintWriter;
  3. import java.util.List;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.annotation.WebServlet;
  6. import javax.servlet.http.HttpServlet;
  7. import javax.servlet.http.HttpServletRequest;
  8. import javax.servlet.http.HttpServletResponse;
  9. @WebServlet(“/ViewServlet”)
  10. public class ViewServlet extends HttpServlet {
  11.     protected void doGet(HttpServletRequest request, HttpServletResponse response)
  12.                throws ServletException, IOException {
  13.         response.setContentType(“text/html”);
  14.         PrintWriter out=response.getWriter();
  15.         out.println(“<a href=’index.html’>Add New Employee</a>”);
  16.         out.println(“<h1>Employees List</h1>”);
  17.         List<Emp> list=EmpDao.getAllEmployees();
  18.         out.print(“<table border=’1′ width=’100%'”);
  19.         out.print(“<tr><th>Id</th><th>Name</th><th>Password</th><th>Email</th><th>Country</th>
  20.                  <th>Edit</th><th>Delete</th></tr>”);
  21.         for(Emp e:list){
  22.          out.print(“<tr><td>”+e.getId()+“</td><td>”+e.getName()+“</td><td>”+e.getPassword()+”</td>
  23.                  <td>“+e.getEmail()+”</td><td>“+e.getCountry()+”</td><td><a href=‘EditServlet?id=”+e.getId()+”‘>edit</a></td>
  24.                  <td><a href=‘DeleteServlet?id=”+e.getId()+”‘>delete</a></td></tr>”);
  25.         }
  26.         out.print(“</table>”);
  27.         out.close();
  28.     }
  29. }

Download

download this example (developed using Eclipse)

Output

First page will look like this, fill the form and submit it.

crud1

You will get a message “Record successfully saved!”.

crud2.jpg

Click on the View Employees link to see the total employees list.

crud3.jpg

Click on the update link, to change the data.

crud4.jpg

After changing information, submit button. You will see that information is changed.

crud5.jpg

Now, click on the delete link to delete the record.

crud6.jpg

Comments

comments