📜  Servlet中的CRUD

📅  最后修改于: 2021-01-09 12:50:51             🧑  作者: Mango

Servlet中的CRUD

对于任何项目开发,CRUD(创建,读取,更新和删除)应用程序都是最重要的应用程序。在Servlet中,我们可以轻松创建CRUD应用程序。

Servlet CRUD示例

使用序列使用自动递增的ID在Oracle数据库中创建“ user905”表。其中有5个字段:ID,名称,密码,电子邮件和国家。

文件:index.html





Insert title here



Add New Employee

Name:
Password:
Email:
Country:

view employees

档案:Emp.java


public class Emp {
private int id;
private String name,password,email,country;
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getPassword() {
    return password;
}
public void setPassword(String password) {
    this.password = password;
}
public String getEmail() {
    return email;
}
public void setEmail(String email) {
    this.email = email;
}
public String getCountry() {
    return country;
}
public void setCountry(String country) {
    this.country = country;
}

}

档案:EmpDao.java

import java.util.*;
import java.sql.*;

public class EmpDao {

    public static Connection getConnection(){
        Connection con=null;
        try{
            Class.forName("oracle.jdbc.driver.OracleDriver");
            con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
        }catch(Exception e){System.out.println(e);}
        return con;
    }
    public static int save(Emp e){
        int status=0;
        try{
            Connection con=EmpDao.getConnection();
            PreparedStatement ps=con.prepareStatement(
                         "insert into user905(name,password,email,country) values (?,?,?,?)");
            ps.setString(1,e.getName());
            ps.setString(2,e.getPassword());
            ps.setString(3,e.getEmail());
            ps.setString(4,e.getCountry());
            
            status=ps.executeUpdate();
            
            con.close();
        }catch(Exception ex){ex.printStackTrace();}
        
        return status;
    }
    public static int update(Emp e){
        int status=0;
        try{
            Connection con=EmpDao.getConnection();
            PreparedStatement ps=con.prepareStatement(
                         "update user905 set name=?,password=?,email=?,country=? where id=?");
            ps.setString(1,e.getName());
            ps.setString(2,e.getPassword());
            ps.setString(3,e.getEmail());
            ps.setString(4,e.getCountry());
            ps.setInt(5,e.getId());
            
            status=ps.executeUpdate();
            
            con.close();
        }catch(Exception ex){ex.printStackTrace();}
        
        return status;
    }
    public static int delete(int id){
        int status=0;
        try{
            Connection con=EmpDao.getConnection();
            PreparedStatement ps=con.prepareStatement("delete from user905 where id=?");
            ps.setInt(1,id);
            status=ps.executeUpdate();
            
            con.close();
        }catch(Exception e){e.printStackTrace();}
        
        return status;
    }
    public static Emp getEmployeeById(int id){
        Emp e=new Emp();
        
        try{
            Connection con=EmpDao.getConnection();
            PreparedStatement ps=con.prepareStatement("select * from user905 where id=?");
            ps.setInt(1,id);
            ResultSet rs=ps.executeQuery();
            if(rs.next()){
                e.setId(rs.getInt(1));
                e.setName(rs.getString(2));
                e.setPassword(rs.getString(3));
                e.setEmail(rs.getString(4));
                e.setCountry(rs.getString(5));
            }
            con.close();
        }catch(Exception ex){ex.printStackTrace();}
        
        return e;
    }
    public static List getAllEmployees(){
        List list=new ArrayList();
        
        try{
            Connection con=EmpDao.getConnection();
            PreparedStatement ps=con.prepareStatement("select * from user905");
            ResultSet rs=ps.executeQuery();
            while(rs.next()){
                Emp e=new Emp();
                e.setId(rs.getInt(1));
                e.setName(rs.getString(2));
                e.setPassword(rs.getString(3));
                e.setEmail(rs.getString(4));
                e.setCountry(rs.getString(5));
                list.add(e);
            }
            con.close();
        }catch(Exception e){e.printStackTrace();}
        
        return list;
    }
}

文件:SaveServlet.java



import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/SaveServlet")
public class SaveServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
         throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out=response.getWriter();
        
        String name=request.getParameter("name");
        String password=request.getParameter("password");
        String email=request.getParameter("email");
        String country=request.getParameter("country");
        
        Emp e=new Emp();
        e.setName(name);
        e.setPassword(password);
        e.setEmail(email);
        e.setCountry(country);
        
        int status=EmpDao.save(e);
        if(status>0){
            out.print("

Record saved successfully!

"); request.getRequestDispatcher("index.html").include(request, response); }else{ out.println("Sorry! unable to save record"); } out.close(); } }

文件:EditServlet.java



import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/EditServlet")
public class EditServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
           throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out=response.getWriter();
        out.println("

Update Employee

"); String sid=request.getParameter("id"); int id=Integer.parseInt(sid); Emp e=EmpDao.getEmployeeById(id); out.print("
"); out.print(""); out.print(""); out.print(""); out.print(""); out.print(""); out.print(""); out.print(""); out.print("
Name:
Password:
Email:
Country:"); out.print(""); out.print("
"); out.print("
"); out.close(); } }

文件:EditServlet2.java



import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/EditServlet2")
public class EditServlet2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
          throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out=response.getWriter();
        
        String sid=request.getParameter("id");
        int id=Integer.parseInt(sid);
        String name=request.getParameter("name");
        String password=request.getParameter("password");
        String email=request.getParameter("email");
        String country=request.getParameter("country");
        
        Emp e=new Emp();
        e.setId(id);
        e.setName(name);
        e.setPassword(password);
        e.setEmail(email);
        e.setCountry(country);
        
        int status=EmpDao.update(e);
        if(status>0){
            response.sendRedirect("ViewServlet");
        }else{
            out.println("Sorry! unable to update record");
        }
        
        out.close();
    }

}

文件:DeleteServlet.java



import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/DeleteServlet")
public class DeleteServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
             throws ServletException, IOException {
        String sid=request.getParameter("id");
        int id=Integer.parseInt(sid);
        EmpDao.delete(id);
        response.sendRedirect("ViewServlet");
    }
}

档案:ViewServlet.java



import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/ViewServlet")
public class ViewServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
               throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out=response.getWriter();
        out.println("Add New Employee");
        out.println("

Employees List

"); List list=EmpDao.getAllEmployees(); out.print(""); for(Emp e:list){ out.print(""); } out.print("
IdNamePasswordEmailCountry EditDelete
"+e.getId()+""+e.getName()+""+e.getPassword()+" "+e.getEmail()+""+e.getCountry()+"edit delete
"); out.close(); } }

下载

输出量

第一页将如下所示,填写表格并提交。

您将收到一条消息“记录已成功保存!”。

单击查看员工链接以查看总员工列表。

单击更新链接,以更改数据。

更改信息后,提交按钮。您将看到信息已更改。

现在,单击删除链接以删除记录。