Servlet – CRUD
CRUD 表示创建、读取、更新和删除。这些是在数据库和应用程序中执行的基本重要操作。我们可以使用 CRUD 操作来操作任何数据库的表。在本文中,让我们以 MYSQL 为例。 MySQL中的表创建
-- Let us keep the db name as geeksforgeeks
-- Table name geekusers
CREATE TABLE `geeksforgeeks`.`geekusers` (
`geekUserId` INT NOT NULL AUTO_INCREMENT,
`geekUserName` VARCHAR(25) NULL,
`numberOfPosts` INT NULL,
`technologiesPrefered` VARCHAR(45) NULL,
PRIMARY KEY (`geekUserId`));
让我们有一个 index.html 文件,流程开始的地方。一个 HTML 文件可以用 CSS 来美化和 javascript 来验证。
HTML
Addition of GeekUsers
Add New GeekUser
view GeekUsers
Java
// Model file equivalent
// to MySQL table GeekUsers
public class GeekUsers {
private int geekUserId;
private int numberOfPosts;
private String geekUserName, technologiesPrefered;
public int getId() { return geekUserId; }
public void setId(int id) { this.geekUserId = id; }
public String getName() { return geekUserName; }
public void setName(String name)
{
this.geekUserName = name;
}
public int getNumberOfPosts() { return numberOfPosts; }
public void setNumberOfPosts(int numberOfPosts)
{
this.numberOfPosts = numberOfPosts;
}
public String gettechnologiesPrefered()
{
return technologiesPrefered;
}
public void
setTechnologiesPrefered(String technologiesPrefered)
{
this.technologiesPrefered = technologiesPrefered;
}
}
Java
import java.util.*;
import java.sql.*;
public class GeekUsersDao {
// Here geeksforgeeks is the name of the database
private static String jdbcURL = "jdbc:mysql://localhost:3306/geeksforgeeks";
private static String jdbcUsername = "root";
// provide your appropriate password here
private static String jdbcPassword = "*****";
public static Connection getConnection(){
Connection con=null;
try {
// This is the way of connecting MySQL
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(jdbcURL, jdbcUsername, jdbcPassword);
} catch (SQLException e) {
System.out.println("Message.. " + e.getMessage());
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.out.println("Message.. " + e.getMessage());
e.printStackTrace();
}
return con;
}
// Rest of the methods like Save,
// Update, Delete etc., should come here
}
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 SaveGeekUserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Getting all the request parameters from
// index.html
String name = request.getParameter("name");
int numberOfPosts = Integer.parseInt(
request.getParameter("numberOfPosts"));
String technologiesPrefered
= request.getParameter("technologiesPrefered");
// GeekUsers object is created
GeekUsers geekUser = new GeekUsers();
// Collected parameters like name, numberOfPosts and
// technologiesPrefered are set for the object so
// that it can be retrieved in other places
geekUser.setName(name);
geekUser.setNumberOfPosts(numberOfPosts);
geekUser.setTechnologiesPrefered(
technologiesPrefered);
// Calling save method in GeekUsersDao by passing
// geekUser
int status = GeekUsersDao.save(geekUser);
// This is possible when the record is saved
// successfully
if (status > 0) {
out.print("
Record saved successfully!
");
request.getRequestDispatcher("index.html")
.include(request, response);
}
else {
// If there is an issue in saving the record, we
// need to show this message
out.println("Sorry! unable to save record");
}
out.close();
}
}
Java
public static int save(GeekUsers e)
{
int status = 0;
try {
Connection con = GeekUsersDao.getConnection();
// Using PreparedStatement, we can execute any SQL
// statement In order to save the record, we need to
// insert the details in 'geekusers' table "e" is an
// object of type "GeekUsers" which exactly resembles
// geekusers table From html page, the values has
// been passed to a servlet and from there, this
// method is called
PreparedStatement ps = con.prepareStatement(
"insert into geekusers(geekUserName,numberOfPosts,technologiesPrefered) values (?,?,?)");
ps.setString(1, e.getName());
ps.setInt(2, e.getNumberOfPosts());
ps.setString(3, e.gettechnologiesPrefered());
status = ps.executeUpdate();
con.close();
}
catch (Exception ex) {
System.out.println("Message.." + ex.getMessage());
ex.printStackTrace();
}
return status;
}
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 ViewGeekUserServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter printWriter=response.getWriter();
printWriter.println("Add New GeekUser");
printWriter.println("GeekUsers List
");
List list=GeekUsersDao.getAllGeekUses();
printWriter.print("Id Name Number Of Post Preferred Technology Edit Delete ");
for(GeekUsers e:list){
// each row is identified by means of its id
// hence on click of 'edit', it is sent as
// edit
// on click of 'delete', it is sent as
// delete
printWriter.print(""+e.getId()+" "+e.getName()+" "+e.getNumberOfPosts()+" "+e.gettechnologiesPrefered()+" edit delete ");
}
printWriter.print("
");
printWriter.close();
}
}
Java
public static List getAllGeekUses()
{
List list = new ArrayList();
try {
Connection con = GeekUsersDao.getConnection();
PreparedStatement ps = con.prepareStatement(
"select * from geekusers");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
GeekUsers e = new GeekUsers();
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setNumberOfPosts(rs.getInt(3));
e.setTechnologiesPrefered(rs.getString(4));
list.add(e);
}
con.close();
}
catch (Exception e) {
e.printStackTrace();
}
return list;
}
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 EditGeekUserServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("Update GeekUser
");
String sid=request.getParameter("id");
int id=Integer.parseInt(sid);
// We need to get the id from view servlet
// request and it has to be parsed with
// Integer.parseInt in order to get as number
// Then specific user is retrieved by means
// of GeekUsersDao.getGeekUsersById(id)
GeekUsers e=GeekUsersDao.getGeekUsersById(id);
out.print("");
out.close();
}
}
Java
public static GeekUsers getGeekUsersById(int id)
{
GeekUsers e = new GeekUsers();
try {
Connection con = GeekUsersDao.getConnection();
// We are getting the details for a specific user
// and hence the query has to be sent in the below
// way
PreparedStatement ps = con.prepareStatement(
"select * from geekusers where geekUserId=?");
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setNumberOfPosts(rs.getInt(3));
e.setTechnologiesPrefered(rs.getString(4));
}
con.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
return e;
}
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 EditGeekUserServlet2 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");
int numberOfPosts=Integer.parseInt(request.getParameter("numberOfPosts"));
String technologiesPrefered=request.getParameter("technologiesPrefered");
GeekUsers geekUser=new GeekUsers();
geekUser.setId(id);
geekUser.setName(name);
geekUser.setNumberOfPosts(numberOfPosts);
geekUser.setTechnologiesPrefered(technologiesPrefered);
// GeekUsersDao.update method is called
// along with the modified values for geekUser
int status=GeekUsersDao.update(geekUser);
if(status>0){
response.sendRedirect("ViewServlet");
}else{
out.println("Sorry! unable to update record");
}
out.close();
}
}
Java
public static int update(GeekUsers e)
{
int status = 0;
try {
Connection con = GeekUsersDao.getConnection();
// AS we are not sure about what fields need to be
// updated, we are setting for all the firlds by
// means of update query This will update the record
// for the corresponding geekUserId
PreparedStatement ps = con.prepareStatement(
"update geekusers set geekUserName=?,numberOfPosts=?,technologiesPrefered=? where geekUserId=?");
ps.setString(1, e.getName());
ps.setInt(2, e.getNumberOfPosts());
ps.setString(3, e.gettechnologiesPrefered());
ps.setInt(4, e.getId());
status = ps.executeUpdate();
con.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
return status;
}
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 DeleteGeekUserServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
String sid = request.getParameter("id");
int id = Integer.parseInt(sid);
// GeekUsersDao.delete methpd is called with the
// corresponding id and then it is redirected to
// viewservlet
GeekUsersDao.delete(id);
response.sendRedirect("ViewServlet");
}
}
Java
public static int delete(int id)
{
int status = 0;
try {
Connection con = GeekUsersDao.getConnection();
// delete query is given to delete the record for
// the given geekUserId
PreparedStatement ps = con.prepareStatement(
"delete from geekusers where geekUserId=?");
ps.setInt(1, id);
status = ps.executeUpdate();
con.close();
}
catch (Exception e) {
e.printStackTrace();
}
return status;
}
在运行 HTML 文件时,我们可以看到输出为
这里让我们给出如下输入
点击“ Save GeekUsers ”,我们可以看到下面的输出。这表明记录保存成功,并且还有通过“查看GeekUsers”的方式查看记录的规定
我们也可以看到一条记录被插入到 MySQL 中
让我们看看它的后端代码。首先,让我们看看“模型” Java文件。这里是 GeekUsers。Java它将包含一些类似于 MySQL 表中名为“geekusers”的列的属性。定义了其对应的 setter 和 getter 方法,这些方法在整个程序中都是必需的。
Java
// Model file equivalent
// to MySQL table GeekUsers
public class GeekUsers {
private int geekUserId;
private int numberOfPosts;
private String geekUserName, technologiesPrefered;
public int getId() { return geekUserId; }
public void setId(int id) { this.geekUserId = id; }
public String getName() { return geekUserName; }
public void setName(String name)
{
this.geekUserName = name;
}
public int getNumberOfPosts() { return numberOfPosts; }
public void setNumberOfPosts(int numberOfPosts)
{
this.numberOfPosts = numberOfPosts;
}
public String gettechnologiesPrefered()
{
return technologiesPrefered;
}
public void
setTechnologiesPrefered(String technologiesPrefered)
{
this.technologiesPrefered = technologiesPrefered;
}
}
需要一个 DAO 类(数据访问对象),它可以帮助获取 MySQL 的 JDBC 连接,并且这里定义了执行 CRUD 操作所需的所有方法。下面是获取连接所需的代码片段。当我们使用 JDBC 时,我们应该有一个 URL 类型
jdbcURL = "jdbc:mysql://localhost:3306/";
// Let us use "geeksforgeeks" for it
jdbcUsername = "root"; // username generally "root"
jdbcPassword = "xxxxx"; // password that is used to connect to mysql
用于获取连接的Java代码片段
Java
import java.util.*;
import java.sql.*;
public class GeekUsersDao {
// Here geeksforgeeks is the name of the database
private static String jdbcURL = "jdbc:mysql://localhost:3306/geeksforgeeks";
private static String jdbcUsername = "root";
// provide your appropriate password here
private static String jdbcPassword = "*****";
public static Connection getConnection(){
Connection con=null;
try {
// This is the way of connecting MySQL
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(jdbcURL, jdbcUsername, jdbcPassword);
} catch (SQLException e) {
System.out.println("Message.. " + e.getMessage());
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.out.println("Message.. " + e.getMessage());
e.printStackTrace();
}
return con;
}
// Rest of the methods like Save,
// Update, Delete etc., should come here
}
现在让我们看看 servlet 代码。从 index.html 中,输入值被发送到“/SaveServlet”。 'SaveServlet' 是查找的 servlet 名称,'POST' 是被调用的方法
SaveGeekUserServlet。Java
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 SaveGeekUserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Getting all the request parameters from
// index.html
String name = request.getParameter("name");
int numberOfPosts = Integer.parseInt(
request.getParameter("numberOfPosts"));
String technologiesPrefered
= request.getParameter("technologiesPrefered");
// GeekUsers object is created
GeekUsers geekUser = new GeekUsers();
// Collected parameters like name, numberOfPosts and
// technologiesPrefered are set for the object so
// that it can be retrieved in other places
geekUser.setName(name);
geekUser.setNumberOfPosts(numberOfPosts);
geekUser.setTechnologiesPrefered(
technologiesPrefered);
// Calling save method in GeekUsersDao by passing
// geekUser
int status = GeekUsersDao.save(geekUser);
// This is possible when the record is saved
// successfully
if (status > 0) {
out.print("
Record saved successfully!
");
request.getRequestDispatcher("index.html")
.include(request, response);
}
else {
// If there is an issue in saving the record, we
// need to show this message
out.println("Sorry! unable to save record");
}
out.close();
}
}
下面给出了将记录保存到表中的Java方法
Using PreparedStatement, we can execute any SQL statement. In order to save the record, we need to insert the details in ‘geekusers’ table
Java
public static int save(GeekUsers e)
{
int status = 0;
try {
Connection con = GeekUsersDao.getConnection();
// Using PreparedStatement, we can execute any SQL
// statement In order to save the record, we need to
// insert the details in 'geekusers' table "e" is an
// object of type "GeekUsers" which exactly resembles
// geekusers table From html page, the values has
// been passed to a servlet and from there, this
// method is called
PreparedStatement ps = con.prepareStatement(
"insert into geekusers(geekUserName,numberOfPosts,technologiesPrefered) values (?,?,?)");
ps.setString(1, e.getName());
ps.setInt(2, e.getNumberOfPosts());
ps.setString(3, e.gettechnologiesPrefered());
status = ps.executeUpdate();
con.close();
}
catch (Exception ex) {
System.out.println("Message.." + ex.getMessage());
ex.printStackTrace();
}
return status;
}
为了查看保存的记录,我们可以使用“查看 GeekUsers”链接
View Servlet的相关代码
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 ViewGeekUserServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter printWriter=response.getWriter();
printWriter.println("Add New GeekUser");
printWriter.println("GeekUsers List
");
List list=GeekUsersDao.getAllGeekUses();
printWriter.print("Id Name Number Of Post Preferred Technology Edit Delete ");
for(GeekUsers e:list){
// each row is identified by means of its id
// hence on click of 'edit', it is sent as
// edit
// on click of 'delete', it is sent as
// delete
printWriter.print(""+e.getId()+" "+e.getName()+" "+e.getNumberOfPosts()+" "+e.gettechnologiesPrefered()+" edit delete ");
}
printWriter.print("
");
printWriter.close();
}
}
为了获取所有极客用户,使用“GeekUsersDao”中的“getAllGeekUses”方法
PreparedStatement ps=con.prepareStatement(“select * from geekusers”);
ResultSet rs=ps.executeQuery();
// and then the resultset is
// iterated as shown in the below code
Java
public static List getAllGeekUses()
{
List list = new ArrayList();
try {
Connection con = GeekUsersDao.getConnection();
PreparedStatement ps = con.prepareStatement(
"select * from geekusers");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
GeekUsers e = new GeekUsers();
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setNumberOfPosts(rs.getInt(3));
e.setTechnologiesPrefered(rs.getString(4));
list.add(e);
}
con.close();
}
catch (Exception e) {
e.printStackTrace();
}
return list;
}
我们可以选择编辑数据以及删除数据。让我们看看他们
“edit”上对应的Servlet代码是“EditGeekUserServlet.Java”
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 EditGeekUserServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("Update GeekUser
");
String sid=request.getParameter("id");
int id=Integer.parseInt(sid);
// We need to get the id from view servlet
// request and it has to be parsed with
// Integer.parseInt in order to get as number
// Then specific user is retrieved by means
// of GeekUsersDao.getGeekUsersById(id)
GeekUsers e=GeekUsersDao.getGeekUsersById(id);
out.print("");
out.close();
}
}
让我们看看 GeekUsersDao.getGeekUsersById()
Java
public static GeekUsers getGeekUsersById(int id)
{
GeekUsers e = new GeekUsers();
try {
Connection con = GeekUsersDao.getConnection();
// We are getting the details for a specific user
// and hence the query has to be sent in the below
// way
PreparedStatement ps = con.prepareStatement(
"select * from geekusers where geekUserId=?");
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setNumberOfPosts(rs.getInt(3));
e.setTechnologiesPrefered(rs.getString(4));
}
con.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
return e;
}
现在,如果我们更新(更改)数据,相应的详细信息将更新并反映在屏幕以及 MySQL 中
让我们也查询 MySQL 部分
做上述操作的相关Servlet代码是“ EditGeekUserServlet2.Java“
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 EditGeekUserServlet2 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");
int numberOfPosts=Integer.parseInt(request.getParameter("numberOfPosts"));
String technologiesPrefered=request.getParameter("technologiesPrefered");
GeekUsers geekUser=new GeekUsers();
geekUser.setId(id);
geekUser.setName(name);
geekUser.setNumberOfPosts(numberOfPosts);
geekUser.setTechnologiesPrefered(technologiesPrefered);
// GeekUsersDao.update method is called
// along with the modified values for geekUser
int status=GeekUsersDao.update(geekUser);
if(status>0){
response.sendRedirect("ViewServlet");
}else{
out.println("Sorry! unable to update record");
}
out.close();
}
}
GeekUsersDao.update()
Java
public static int update(GeekUsers e)
{
int status = 0;
try {
Connection con = GeekUsersDao.getConnection();
// AS we are not sure about what fields need to be
// updated, we are setting for all the firlds by
// means of update query This will update the record
// for the corresponding geekUserId
PreparedStatement ps = con.prepareStatement(
"update geekusers set geekUserName=?,numberOfPosts=?,technologiesPrefered=? where geekUserId=?");
ps.setString(1, e.getName());
ps.setInt(2, e.getNumberOfPosts());
ps.setString(3, e.gettechnologiesPrefered());
ps.setInt(4, e.getId());
status = ps.executeUpdate();
con.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
return status;
}
现在让我们看看删除部分。假设我们有 2 条记录,点击删除第 2 条记录,第 2 行被删除
让我们看看它的相关代码。
“删除GeekUserServlet”。Java
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 DeleteGeekUserServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
String sid = request.getParameter("id");
int id = Integer.parseInt(sid);
// GeekUsersDao.delete methpd is called with the
// corresponding id and then it is redirected to
// viewservlet
GeekUsersDao.delete(id);
response.sendRedirect("ViewServlet");
}
}
GeekUsersDao.delete
Java
public static int delete(int id)
{
int status = 0;
try {
Connection con = GeekUsersDao.getConnection();
// delete query is given to delete the record for
// the given geekUserId
PreparedStatement ps = con.prepareStatement(
"delete from geekusers where geekUserId=?");
ps.setInt(1, id);
status = ps.executeUpdate();
con.close();
}
catch (Exception e) {
e.printStackTrace();
}
return status;
}
CRUD 流的可视化表示
结论
通过上述方式,我们可以使用 Servlet 技术对任何数据库进行“创建/读取/更新/删除”操作。一个模型类、DAO 类和相应的 servlet 类可以很好地执行简单的 CRUD 操作。