JSP 创建 CRUD 示例 MyBatis DAO 用于数据库JSTL 用于遍历记录

 在本 Java 教程中,我们将帮助您了解编写基本 Java Web 应用程序的过程,该应用程序管理具有基本功能的用户集合:列表、插入、更新、删除(或 CURD 操作 - 创建、更新、读取和删除)。该应用程序看起来像这样:

您将学习如何使用以下技术构建此应用程序:

  • Java 服务器页面 (JSP)
  • JSP 标准标签库 (JSTL)
  • Java 数据库连接 (JDBC)
  • MySQL数据库
  • Apache Tomcat 服务器

我们使用 NetBeans IDE 和 Maven 来开发项目。

1. 创建 MySQL 数据库

为简单起见,我们只有一张桌子。执行以下 MySQL 脚本以创建名为test的数据库和名为register的表:

CREATE DATABASE `test`;

CREATE TABLE IF NOT EXISTS `user` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `sex` varchar(100) NOT NULL,
  `country` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB   ;

INSERT INTO `user` (`id`, `name`, `password`, `email`, `sex`, `country`) VALUES
(17, 'arun', 'kumar', 'arun@gmail.com', 'Male', 'India'),
(19, 'sonoo', 'jaiswal', 'sonoo@javatpoint.com', 'male', 'India'),
(20, 'Ashok', 'ashok', 'ashok@javatpoint.com', 'male', 'India');

您可以使用 MySQL 命令行客户端或 MySQL Workbench 工具来创建数据库。

2. 创建新的 Java Web maven应用程序项目

要创建新的 Java Web 应用程序项目,只需打开 Netbeans IDE,然后打开 File -> New Project。然后在 Categories 列中选择 Java with Maven,在 Projects 列中选择 Web Application。然后点击下一步。

给你的项目起个名字,我的是“SimpleWebApp”。将另一个字段保留为默认值。然后点击下一步。

为服务器和设置中的所有字段保留默认值,然后单击完成。

这将创建新的 java web 应用程序,其中包含用于构建 java web 应用程序的核心元素。

创建 Maven POM 文件需要输入信息,例如组 ID、工件 ID 等。然后在pom.xml 文件中添加以下依赖项:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>mybatisjspcrud</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>mybatisjspcrud</name>

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.9</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <compilerArguments>
                        <endorseddirs>${endorsed.dir}</endorseddirs>
                    </compilerArguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${endorsed.dir}</outputDirectory>
                            <silent>true</silent>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>javax</groupId>
                                    <artifactId>javaee-endorsed-api</artifactId>
                                    <version>7.0</version>
                                    <type>jar</type>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

如您所见,这里的依赖项是针对 Servlet、JSP、JSTL 和 MySQL 连接器 Java(MySQL 的 JDBC 驱动程序)。

3. 编写模型类

接下来,使用以下代码创建一个名为User.java的 Java 类来对数据库中的User实体进行建模:

package com.javatpoint.bean;

public class User {
	private int id;
	private String name, password, email, sex, 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 getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public String getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}

}

如您所见,该类根据数据库中表book中的 6列有 6个字段:id、name、password, email, sex和  country。

4.编码DAO类

接下来,我们需要实现一个数据访问层 (DAO) 类,该类为数据库中的表user提供 CRUD(创建、读取、更新、删除)操作。这是UserDAO类的完整源代码:

package com.javatpoint.dao;

import java.util.List;

import com.javatpoint.bean.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

public class UserDao {

    public static int save(User user) {
        int status = 0;
        SqlSession session = null;

        try {
            SqlSessionFactory factory = ServiceLocator.getSessionFactory();
            session = factory.openSession();
            status = session.insert("insertUser", user);
            session.commit();

        } finally {

            if (session != null) {
                session.close();
            }
        }
        return status;
    }

    public static int update(User user) {
        int status = 0;
        SqlSession session = null;

        try {
            SqlSessionFactory factory = ServiceLocator.getSessionFactory();
            session = factory.openSession();
            session.update("updateUser", user);
            session.commit();

        } finally {

            if (session != null) {
                session.close();
            }
        }
        return status;
    }

    public static int delete(User user) {
        int status = 0;
        SqlSession session = null;

        try {
            SqlSessionFactory factory = ServiceLocator.getSessionFactory();
            session = factory.openSession();
            session.delete("deleteById", user.getId());
            session.commit();

        } finally {

            if (session != null) {
                session.close();
            }
        }

        return status;
    }

    public static List<User> getAllRecords() {
        SqlSession session = null;
        List<User> retrieveList = null;

        try {
            SqlSessionFactory factory = ServiceLocator.getSessionFactory();
            session = factory.openSession();
            retrieveList = session.selectList("selectAllUsers");

        } finally {

            if (session != null) {
                session.close();
            }
        }

        return retrieveList;
    }

    public static User getRecordById(int id) {
        SqlSession session = null;
        User user = null;

        try {
            SqlSessionFactory factory = ServiceLocator.getSessionFactory();
            session = factory.openSession();
            user = session.selectOne("selectUser", id);

        } finally {

            if (session != null) {
                session.close();
            }
        }

        return user;
    }
}

ServiceLocator.java

package com.javatpoint.dao;

import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class ServiceLocator {

    public static SqlSessionFactory getSessionFactory() {

        InputStream inputStream = null;
        SqlSessionFactory sqlSessionFactory = null;

        try {
            String resource = "mybatis-config.xml";
            inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        } catch (IOException ex) {
            Logger.getLogger(ServiceLocator.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(ServiceLocator.class.getName()).log(Level.WARNING, null, ex);
            }
        }

        return sqlSessionFactory;
    }
}

如您所见,MyBatis连接信息是通过服务类静态方法提供的。以下方法适用于 CRUD 操作:

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <typeAliases>
        <typeAlias alias="User" type="com.javatpoint.bean.User"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/test"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="UserMapper.xml"/>
    </mappers>
</configuration>

UserMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.javatpoint">

    <select id="selectAllUsers" resultType="User">
        select * from register
    </select>

    <select id="selectUser" parameterType="int" resultType="User">
        select * from register where id = #{id}
    </select>

    <insert id="insertUser" parameterType="User" statementType="PREPARED" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
        INSERT INTO register(name,password,email,sex,country) VALUES
        (#{name}, #{password}, #{email}, #{sex}, #{country})
    </insert>

    <update id = "updateUser" parameterType = "User">
        UPDATE register SET name = #{name},
        password = #{password},
        email = #{email},
        sex = #{sex},
        country = #{country}
        WHERE id = #{id};
    </update>

    <delete id = "deleteById" parameterType = "int">
        DELETE from register WHERE id = #{id};
    </delete>
</mapper>

5.编写JSP页面

接下来,创建 JSP 页面来显示数据库中的所有书籍。以下是项目中WebContent目录下jsp页面的代码:

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

	<a href="adduserform.jsp">Add User</a>
	<a href="viewusers.jsp">View Users</a>

</body>
</html>

adduserform.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add User Form</title>
</head>
<body>

	<jsp:include page="userform.html"></jsp:include>

</body>
</html>

userform.html

<a href="viewusers.jsp">View All Records</a>
<br />

<h1>Add New User</h1>
<form action="adduser.jsp" method="post">
	<table>
		<tr>
			<td>Name:</td>
			<td><input type="text" name="name" /></td>
		</tr>
		<tr>
			<td>Password:</td>
			<td><input type="password" name="password" /></td>
		</tr>
		<tr>
			<td>Email:</td>
			<td><input type="email" name="email" /></td>
		</tr>
		<tr>
			<td>Sex:</td>
			<td><input type="radio" name="sex" value="male" />Male <input
				type="radio" name="sex" value="female" />Female</td>
		</tr>
		<tr>
			<td>Country:</td>
			<td><select name="country" style="width: 155px">
					<option>India</option>
					<option>Pakistan</option>
					<option>Afghanistan</option>
					<option>Berma</option>
					<option>Other</option>
			</select></td>
		</tr>
		<tr>
			<td colspan="2"><input type="submit" value="Add User" /></td>
		</tr>
	</table>
</form>

adduser.jsp

<%@page import="com.javatpoint.dao.UserDao"%>
<jsp:useBean id="u" class="com.javatpoint.bean.User"></jsp:useBean>
<jsp:setProperty property="*" name="u" />

<%
	int i = UserDao.save(u);
if (i > 0) {
	response.sendRedirect("adduser-success.jsp");
} else {
	response.sendRedirect("adduser-error.jsp");
}
%>

adduser-success.jsp

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add User Success</title>
</head>
<body>

	<p>Record successfully saved!</p>
	<jsp:include page="userform.html"></jsp:include>

</body>
</html>

adduser-error.jsp

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add User Success</title>
</head>
<body>

	<p>Sorry, an error occured!</p>
	<jsp:include page="userform.html"></jsp:include>

</body>
</html>

viewusers.jsp

<!DOCTYPE html>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>View Users</title>
</head>
<body>

	<%@page
		import="com.javatpoint.dao.UserDao,com.javatpoint.bean.*,java.util.*"%>
	<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

	<h1>Users List</h1>

	<%
		List<User> list = UserDao.getAllRecords();
	request.setAttribute("list", list);
	%>

	<table border="1" width="90%">
		<tr>
			<th>Id</th>
			<th>Name</th>
			<th>Password</th>
			<th>Email</th>
			<th>Sex</th>
			<th>Country</th>
			<th>Edit</th>
			<th>Delete</th>
		</tr>
		<c:forEach items="${list}" var="u">
			<tr>
				<td>${u.getId()}</td>
				<td>${u.getName()}</td>
				<td>${u.getPassword()}</td>
				<td>${u.getEmail()}</td>
				<td>${u.getSex()}</td>
				<td>${u.getCountry()}</td>
				<td><a href="editform.jsp?id=${u.getId()}">Edit</a></td>
				<td><a href="deleteuser.jsp?id=${u.getId()}">Delete</a></td>
			</tr>
		</c:forEach>
	</table>
	<br />
	<a href="adduserform.jsp">Add New User</a>

</body>
</html>

editform.jsp

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Edit Form</title>
</head>
<body>
	<%@page import="com.javatpoint.dao.UserDao,com.javatpoint.bean.User"%>

	<%
		String id = request.getParameter("id");
	User u = UserDao.getRecordById(Integer.parseInt(id));
	%>

	<h1>Edit Form</h1>
	<form action="edituser.jsp" method="post">
		<input type="hidden" name="id" value="<%=u.getId()%>" />
		<table>
			<tr>
				<td>Name:</td>
				<td><input type="text" name="name" value="<%=u.getName()%>" /></td>
			</tr>
			<tr>
				<td>Password:</td>
				<td><input type="password" name="password"
					value="<%=u.getPassword()%>" /></td>
			</tr>
			<tr>
				<td>Email:</td>
				<td><input type="email" name="email" value="<%=u.getEmail()%>" /></td>
			</tr>
			<tr>
				<td>Sex:</td>
				<td><input type="radio" name="sex" value="male" />Male <input
					type="radio" name="sex" value="female" />Female</td>
			</tr>
			<tr>
				<td>Country:</td>
				<td><select name="country">
						<option>India</option>
						<option>Pakistan</option>
						<option>Afghanistan</option>
						<option>Berma</option>
						<option>Other</option>
				</select></td>
			</tr>
			<tr>
				<td colspan="2"><input type="submit" value="Edit User" /></td>
			</tr>
		</table>
	</form>

</body>
</html>

edituser.jsp

<%@page import="com.javatpoint.dao.UserDao"%>
<jsp:useBean id="u" class="com.javatpoint.bean.User"></jsp:useBean>
<jsp:setProperty property="*" name="u" />

<%
	int i = UserDao.update(u);
response.sendRedirect("viewusers.jsp");
%>

deleteuser.jsp

<%@page import="com.javatpoint.dao.UserDao"%>
<jsp:useBean id="u" class="com.javatpoint.bean.User"></jsp:useBean>
<jsp:setProperty property="*" name="u" />

<%
	UserDao.delete(u);
response.sendRedirect("viewusers.jsp");
%>

6. 部署和测试应用程序

至此我们已经完成了项目的代码。是时候部署和测试应用程序以了解它是如何工作的了。如果您不知道如何在 Eclipse 中添加 Apache Tomcat 服务器,请遵循本教程。

在 Web 浏览器中键入以下 URL 以访问 UserReg应用程序:

http://localhost:8080/UserReg

输出

      

下载项目

GitHub - allwaysoft/MyBatis-JSP-CRUD-MySQLContribute to allwaysoft/MyBatis-JSP-CRUD-MySQL development by creating an account on GitHub.https://github.com/allwaysoft/MyBatis-JSP-CRUD-MySQL

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值