Servlet – CRUD 操作示例
CRUD 表示创建、读取、更新和删除。这些是在数据库和应用程序中执行的基本重要操作。我们将使用 Servlet、MYSQL 和 JDBC 构建一个简单的用户注册应用程序进行演示。在这个例子中,我们将能够创建用户、读取用户、更新用户和删除用户。
技术工具:
- MySQL(工作台)数据库
- IDE(智能)
- Apache Tomcat(我使用的是 Tomcat 9 版本)。
首先,我们从下载 Apache Tomcat 中下载 Apache Tomcat,解压到您的工作目录中。
然后我们创建一个新项目,将其命名为 app user。通常,有两种方法,第一种是从数据库创建项目,另一种是先创建应用程序,然后设置数据库。在本文中,我们将从数据库开始我们的项目。所以,让我们建立我们的数据库,在这个例子中使用 MYSQL,查看下图以了解如何建立数据库。
之后,我们设置了我们的项目,对于这个例子,我使用 Intellij IDE,
- 通过选择文件创建一个新项目(它将显示各种选项)
- 选择新建,然后项目
- 单击Java Enterprise 并选择 Web 应用程序作为您的项目模板
设置应用服务器
- 选择应用程序并选择新的
- 选择 Tomcat 基目录(保存在工作目录中的那个)
这是项目结构的样子:
编码方面。首先,我们创建一个名为 User 的模型类,它是一个简单的 POJO 类;
用户。Java
Java
public class User {
private int id;
private String username;
private String password;
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getUsername() { return username; }
public void setUsername(String username)
{
this.username = username;
}
public String getPassword() { return password; }
public void setPassword(String password)
{
this.password = password;
}
}
Java
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class UserDaoHandler {
public static Connection connectDB()
{
// connection object
Connection connection = null;
try {
// returns the class object
Class.forName("com.mysql.jdbc.Driver");
// it creates a connection to the database using
// the url
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/appuserdb",
"adminuser", "user123");
}
catch (Exception message) {
System.out.println(message);
}
return connection;
}
public static int addUser(User user) throws SQLException
{
int result = 0;
Connection connect = UserDaoHandler.connectDB();
// SQL statement is precompiled and stored in a
// PreparedStatement object.
PreparedStatement preparedStatement
= connect.prepareStatement(
"insert into user(username,password) values (?,?)");
// set the parameter to the given Java String value
preparedStatement.setString(1, user.getUsername());
preparedStatement.setString(2, user.getPassword());
// execute SQl statement insert values to the
// database
result = preparedStatement.executeUpdate();
// close the database connection
connect.close();
return result;
}
public static int updateUser(User user)
throws SQLException
{
int result = 0;
// create connection at the call of this method
Connection connect = UserDaoHandler.connectDB();
// SQL statement is precompiled and stored in a
// PreparedStatement object
PreparedStatement preparedStatement
= connect.prepareStatement(
"update user set username=?,password=? where id=?");
// set the parameter to the given Java String value
preparedStatement.setString(1, user.getUsername());
preparedStatement.setString(2, user.getPassword());
// execute SQl statement, insert values to the
// database
result = preparedStatement.executeUpdate();
// close the database connection
connect.close();
return result;
}
public static int deleteUser(int id) throws SQLException
{
int result = 0;
// create connection at the call of this method
Connection connect = UserDaoHandler.connectDB();
// SQL statement is precompiled and stored in a
// PreparedStatement object
PreparedStatement preparedStatement
= connect.prepareStatement(
"delete from USER where id =?");
// set the integer value to the user id,
preparedStatement.setInt(1, id);
// execute SQl statement, insert values to the
// database
result = preparedStatement.executeUpdate();
// close the database connection
connect.close();
return result;
}
public static User getUserById(int id)
throws SQLException
{
// create a user object
User user = new User();
// create connection at the call of the method
Connection connect = UserDaoHandler.connectDB();
// SQL statement is precompiled and stored in a
// PreparedStatement object
PreparedStatement preparedStatement
= connect.prepareStatement(
"select * from USER where id=?");
// set the integer value to the user id,
preparedStatement.setInt(1, id);
// A table of data representing a database result
// set,generated after the query
ResultSet resultSet
= preparedStatement.executeQuery();
// checking for saved fields,if more than one
if (resultSet.next()) {
// value of the column is assigned to the set
// method
user.setId(resultSet.getInt(1));
user.setUsername(resultSet.getString(2));
user.setPassword(resultSet.getString(3));
}
// close the database connection
connect.close();
return user;
}
public static List getAllUsers(int start,
int total)
throws SQLException
{
// creating an empty arraylist of type User.
List list = new ArrayList();
// create connection at the call of the method
Connection connect = UserDaoHandler.connectDB();
// SQL statement and telling it to select from the
// first index
PreparedStatement preparedStatement
= connect.prepareStatement(
"select * from user limit " + (start - 1)
+ "," + total);
ResultSet resultSet
= preparedStatement.executeQuery();
// this keep iterating the list of user
// setting the values to the corresponding integer
while (resultSet.next()) {
User user = new User();
user.setId(resultSet.getInt(1));
user.setUsername(resultSet.getString(2));
user.setPassword(resultSet.getString(3));
// store the values into the list
list.add(user);
}
// close the database connection
connect.close();
return list;
}
}
Java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
@WebServlet(name = "addUser", value = "/addUser")
public class AddUser extends HttpServlet {
protected void
processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
}
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
}
// override the supertype method post
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
processRequest(request, response);
// print object for string formatting
PrintWriter out = response.getWriter();
// Httpservletrequest get parameters from user
String username = request.getParameter("username");
String password = request.getParameter("password");
// Instances of User class
User user = new User();
// set the parameters gotten to the 'Username' field
// of User class
user.setUsername(username);
user.setPassword(password);
int status = 0;
try {
// static method add the values stored in the
// user object to the database
status = UserDaoHandler.addUser(user);
}
catch (SQLException e) {
e.printStackTrace();
}
// check if the values correspond to the one
// specified
if (status > 0) {
out.print("
Record saved successfully!
");
request.getRequestDispatcher("index.html")
.include(request, response);
}
else {
out.println("Sorry! unable to save record");
}
// close database connection
out.close();
}
}
Java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
@WebServlet(name = "updateUser", value = "/updateUser")
public class UpdateUser extends HttpServlet {
// override the supertype method post
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
// collect user id parameter
String userId = request.getParameter("id");
// the string value is parse as integer to id
int id = Integer.parseInt(userId);
try {
// this statement get user by id
User user = UserDaoHandler.getUserById(id);
// this print the jsp and render web page
out.println("Edit User Account
");
out.print(
"");
// close database connection
out.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
}
}
Java
import static java.lang.System.out;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
@WebServlet(name = "patchUser", value = "/patchUser")
public class PatchUser extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
String userId = request.getParameter("id");
int id = Integer.parseInt(userId);
String username = request.getParameter("name");
String password = request.getParameter("password");
User user = new User();
user.setId(id);
user.setUsername(username);
user.setPassword(password);
try {
int result = UserDaoHandler.updateUser(user);
if (result > 0) {
response.sendRedirect("viewUser? page =1");
}
else {
out.print("unable to connect");
}
}
catch (SQLException e) {
e.printStackTrace();
}
out.close();
}
}
Java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
@WebServlet(name = "viewUser", value = "/viewUser")
public class ViewUser extends HttpServlet {
protected void
processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
}
// override the supertype method get
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
processRequest(request, response);
PrintWriter out = response.getWriter();
// assigning integer values to web pages
String pageId = request.getParameter("page");
int total = 3;
int pagesId = Integer.parseInt(pageId);
if (pagesId == 1) {
}
else {
pagesId = pagesId - 1;
pagesId = pagesId * total + 1;
}
// initializing list of users
List list = null;
out.println(
"Add user");
out.print(" User Table:
");
out.print(
"");
out.print("Id username ");
try {
// getting all users and assigning to the page
// numbers
list = UserDaoHandler.getAllUsers(pagesId,
total);
}
catch (SQLException e) {
e.printStackTrace();
}
// ensuring list is not null
if (list != null) {
// iterating through the list of Users
// And getting username and id of users.
for (User user : list) {
out.print("" + user.getId()
+ " " + user.getUsername()
+ " ");
}
// printing out in a jsp web format.
out.print("
");
out.print("1 ");
out.print("2 ");
out.print("3 ");
}
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
}
}
Java
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
@WebServlet(name = "deleteUser", value = "/deleteUser")
public class DeleteUser extends HttpServlet {
protected void
processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
}
// overriding the supertype method get
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
processRequest(request, response);
// get user by id
String userId = request.getParameter("id");
// the int value of the parameter
// is parse to the id
int id = Integer.parseInt(userId);
try {
// the delete method is
// invoked on user with the
// specified id
UserDaoHandler.deleteUser(id);
}
catch (SQLException e) {
e.printStackTrace();
}
// it sent the current
// user view as response
response.sendRedirect("viewUser?page=1");
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
}
}
然后我们创建一个类来帮助对我们的数据库执行 CRUD 操作,
用户道处理程序。Java
Java
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class UserDaoHandler {
public static Connection connectDB()
{
// connection object
Connection connection = null;
try {
// returns the class object
Class.forName("com.mysql.jdbc.Driver");
// it creates a connection to the database using
// the url
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/appuserdb",
"adminuser", "user123");
}
catch (Exception message) {
System.out.println(message);
}
return connection;
}
public static int addUser(User user) throws SQLException
{
int result = 0;
Connection connect = UserDaoHandler.connectDB();
// SQL statement is precompiled and stored in a
// PreparedStatement object.
PreparedStatement preparedStatement
= connect.prepareStatement(
"insert into user(username,password) values (?,?)");
// set the parameter to the given Java String value
preparedStatement.setString(1, user.getUsername());
preparedStatement.setString(2, user.getPassword());
// execute SQl statement insert values to the
// database
result = preparedStatement.executeUpdate();
// close the database connection
connect.close();
return result;
}
public static int updateUser(User user)
throws SQLException
{
int result = 0;
// create connection at the call of this method
Connection connect = UserDaoHandler.connectDB();
// SQL statement is precompiled and stored in a
// PreparedStatement object
PreparedStatement preparedStatement
= connect.prepareStatement(
"update user set username=?,password=? where id=?");
// set the parameter to the given Java String value
preparedStatement.setString(1, user.getUsername());
preparedStatement.setString(2, user.getPassword());
// execute SQl statement, insert values to the
// database
result = preparedStatement.executeUpdate();
// close the database connection
connect.close();
return result;
}
public static int deleteUser(int id) throws SQLException
{
int result = 0;
// create connection at the call of this method
Connection connect = UserDaoHandler.connectDB();
// SQL statement is precompiled and stored in a
// PreparedStatement object
PreparedStatement preparedStatement
= connect.prepareStatement(
"delete from USER where id =?");
// set the integer value to the user id,
preparedStatement.setInt(1, id);
// execute SQl statement, insert values to the
// database
result = preparedStatement.executeUpdate();
// close the database connection
connect.close();
return result;
}
public static User getUserById(int id)
throws SQLException
{
// create a user object
User user = new User();
// create connection at the call of the method
Connection connect = UserDaoHandler.connectDB();
// SQL statement is precompiled and stored in a
// PreparedStatement object
PreparedStatement preparedStatement
= connect.prepareStatement(
"select * from USER where id=?");
// set the integer value to the user id,
preparedStatement.setInt(1, id);
// A table of data representing a database result
// set,generated after the query
ResultSet resultSet
= preparedStatement.executeQuery();
// checking for saved fields,if more than one
if (resultSet.next()) {
// value of the column is assigned to the set
// method
user.setId(resultSet.getInt(1));
user.setUsername(resultSet.getString(2));
user.setPassword(resultSet.getString(3));
}
// close the database connection
connect.close();
return user;
}
public static List getAllUsers(int start,
int total)
throws SQLException
{
// creating an empty arraylist of type User.
List list = new ArrayList();
// create connection at the call of the method
Connection connect = UserDaoHandler.connectDB();
// SQL statement and telling it to select from the
// first index
PreparedStatement preparedStatement
= connect.prepareStatement(
"select * from user limit " + (start - 1)
+ "," + total);
ResultSet resultSet
= preparedStatement.executeQuery();
// this keep iterating the list of user
// setting the values to the corresponding integer
while (resultSet.next()) {
User user = new User();
user.setId(resultSet.getInt(1));
user.setUsername(resultSet.getString(2));
user.setPassword(resultSet.getString(3));
// store the values into the list
list.add(user);
}
// close the database connection
connect.close();
return list;
}
}
之后,我们创建我们的 Servlet 类,每个 servlet 类用于从数据库中创建用户、更新用户、读取用户和删除用户。这是课程;
添加用户 Servlet:
该方法是一个post方法,它收集用户信息并将其添加到数据库中,在这个例子中,我们使用“username”、“password”和“userId”作为要保存到数据库中的字段。
Java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
@WebServlet(name = "addUser", value = "/addUser")
public class AddUser extends HttpServlet {
protected void
processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
}
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
}
// override the supertype method post
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
processRequest(request, response);
// print object for string formatting
PrintWriter out = response.getWriter();
// Httpservletrequest get parameters from user
String username = request.getParameter("username");
String password = request.getParameter("password");
// Instances of User class
User user = new User();
// set the parameters gotten to the 'Username' field
// of User class
user.setUsername(username);
user.setPassword(password);
int status = 0;
try {
// static method add the values stored in the
// user object to the database
status = UserDaoHandler.addUser(user);
}
catch (SQLException e) {
e.printStackTrace();
}
// check if the values correspond to the one
// specified
if (status > 0) {
out.print("
Record saved successfully!
");
request.getRequestDispatcher("index.html")
.include(request, response);
}
else {
out.println("Sorry! unable to save record");
}
// close database connection
out.close();
}
}
添加用户。 Java用于将用户添加到数据库。
更新用户 Servlet:
此方法获取用户 ID 并将其与数据库中的用户 ID 匹配,然后对其进行更新。
更新用户。Java
Java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
@WebServlet(name = "updateUser", value = "/updateUser")
public class UpdateUser extends HttpServlet {
// override the supertype method post
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
// collect user id parameter
String userId = request.getParameter("id");
// the string value is parse as integer to id
int id = Integer.parseInt(userId);
try {
// this statement get user by id
User user = UserDaoHandler.getUserById(id);
// this print the jsp and render web page
out.println("Edit User Account
");
out.print(
"");
// close database connection
out.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
}
}
补丁方法:
该方法简单地将数据库信息与从网页获取的输入参数进行交换,并将其保存到数据库中。
补丁用户。Java
Java
import static java.lang.System.out;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
@WebServlet(name = "patchUser", value = "/patchUser")
public class PatchUser extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
String userId = request.getParameter("id");
int id = Integer.parseInt(userId);
String username = request.getParameter("name");
String password = request.getParameter("password");
User user = new User();
user.setId(id);
user.setUsername(username);
user.setPassword(password);
try {
int result = UserDaoHandler.updateUser(user);
if (result > 0) {
response.sendRedirect("viewUser? page =1");
}
else {
out.print("unable to connect");
}
}
catch (SQLException e) {
e.printStackTrace();
}
out.close();
}
}
查看用户 Servlet:
此方法从数据库中获取所有用户并以简单的表格格式显示。
查看用户。Java
Java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
@WebServlet(name = "viewUser", value = "/viewUser")
public class ViewUser extends HttpServlet {
protected void
processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
}
// override the supertype method get
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
processRequest(request, response);
PrintWriter out = response.getWriter();
// assigning integer values to web pages
String pageId = request.getParameter("page");
int total = 3;
int pagesId = Integer.parseInt(pageId);
if (pagesId == 1) {
}
else {
pagesId = pagesId - 1;
pagesId = pagesId * total + 1;
}
// initializing list of users
List list = null;
out.println(
"Add user");
out.print(" User Table:
");
out.print(
"");
out.print("Id username ");
try {
// getting all users and assigning to the page
// numbers
list = UserDaoHandler.getAllUsers(pagesId,
total);
}
catch (SQLException e) {
e.printStackTrace();
}
// ensuring list is not null
if (list != null) {
// iterating through the list of Users
// And getting username and id of users.
for (User user : list) {
out.print("" + user.getId()
+ " " + user.getUsername()
+ " ");
}
// printing out in a jsp web format.
out.print("
");
out.print("1 ");
out.print("2 ");
out.print("3 ");
}
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
}
}
删除小服务程序:
下面的方法从数据库中删除用户并发送用户视图响应,显示数据库中的当前用户。
删除用户。Java
Java
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
@WebServlet(name = "deleteUser", value = "/deleteUser")
public class DeleteUser extends HttpServlet {
protected void
processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
}
// overriding the supertype method get
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
processRequest(request, response);
// get user by id
String userId = request.getParameter("id");
// the int value of the parameter
// is parse to the id
int id = Integer.parseInt(userId);
try {
// the delete method is
// invoked on user with the
// specified id
UserDaoHandler.deleteUser(id);
}
catch (SQLException e) {
e.printStackTrace();
}
// it sent the current
// user view as response
response.sendRedirect("viewUser?page=1");
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
}
}
输出:
每当用户调用时, Java servlet 都会呈现Java服务器页面。