就是简单的对数据进行增删改查。代码如下:
1.bean层:用来封装属性及其get set方法 toString方法,有参构造方法,无参构造方法等。
public class Bean {
private int id;
private String name;
private String password;
private String sex; 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 getSex() {
return sex;
} public void setSex(String sex) {
this.sex = sex;
} @Override
public String toString() {
return "Bean [id=" + id + ", name=" + name + ", password=" + password + ", sex=" + sex + "]";
} public Bean(int id, String name, String password, String sex) {
super();
this.id = id;
this.name = name;
this.password = password;
this.sex = sex;
} public Bean() {
// TODO Auto-generated constructor stub
} }
2.DBUtil:对数据库连接关闭操作的封装:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; public class DBUtil {
private static String url = "jdbc:mysql://localhost:3306/db10?useUnicode=true&characterEncoding=utf8";
private static String user = "root";
private static String password = "root";
private static String jdbcName="com.mysql.jdbc.Driver";
private Connection con=null;
public static Connection getConnection() {
Connection con=null;
try {
Class.forName(jdbcName);
con=DriverManager.getConnection(url, user, password);
//System.out.println("数据库连接成功");
} catch (Exception e) {
// TODO Auto-generated catch block
//System.out.println("数据库连接失败");
e.printStackTrace();
}
return con; }
public static void close(Connection con) {
if(con!=null)
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
public static void close(Statement state, Connection conn) {
if(state!=null) {
try {
state.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} public static void close(ResultSet rs, Statement state, Connection conn) {
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(state!=null) {
try {
state.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} }
可以将其定义为一个工具类,每次使用的时候直接复制,然后更改url里数据库的名字,这样可以提高效率。
dao层:对数据库的各种增删改查方法的封装:
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List; import org.junit.jupiter.api.Test; public class Dao {//dao层
private DBUtil dbutil=new DBUtil(); public Dao() {
// TODO Auto-generated constructor stub
}
@Test
public boolean insert(Bean bean) {//插入数据的方法
boolean f=false;
String sql="insert into info(id,name,password,sex) values('"+bean.getId()+"','"+bean.getName()+"','"+bean.getPassword()+"','"+bean.getSex()+"')";
Connection conn=DBUtil.getConnection();//数据库连接,加载驱动
Statement state=null;
try
{
state=conn.createStatement();//实例化Statement对象,方便对sql语句进行操作
System.out.println(conn);
state.executeUpdate(sql);
f=true;
//执行数据库更新操作用于执行INSERT、UPDATE或DELETE语句以及SQLDDL(数据定义语言)语句,
//例如CREATETABLE和DROPTABLE,(创建表和删除表)
}catch(Exception e)//当try语句中s出现异常时,会执行catch中的语句
{
e.printStackTrace();//捕获异常的语句
}
finally //finally作为异常处理的一部分,它只能用在try/catch语句中,并且附带一个语句块,表示这段语句最终一定会被执行(不管有没有抛出异常),经常被用在需要释放资源的情况下。
{
DBUtil.close(conn);
}
return f;
} public boolean delete(int id ) {//删除方法
String sql="delete from info where id='"+id+"'";
boolean f=false;
Connection conn =DBUtil.getConnection();
Statement st=null;
try {
st=conn.createStatement();
st.executeUpdate(sql);
f=true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
DBUtil.close(st, conn);
}
return f;
}
public boolean update(Bean bean) {//更新方法
String sql="update info set name='"+bean.getName()+"',password='"+bean.getPassword()+"',sex='"+bean.getSex()+"'where id='"+bean.getId()+"'";
Connection conn=DBUtil.getConnection();
boolean f=false;
Statement st=null;
try {
st=conn.createStatement();
st.executeUpdate(sql);
f=true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return f;
} public List<Bean> list(){//查询所有方法
String sql="select * from info order by id ASC";
Connection conn=DBUtil.getConnection();
Statement st=null;
List<Bean> list=new ArrayList<>();
ResultSet rs=null;
Bean bean=null;
try {
st=conn.createStatement();
st.executeQuery(sql);
rs=st.executeQuery(sql);
while(rs.next()) { int id=rs.getInt("id");
String name = rs.getString("name");
String password = rs.getString("password");
String sex = rs.getString("sex");
bean=new Bean(id,name,password,sex);
list.add(bean);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
DBUtil.close(rs, st, conn);
}
return list;
} }
对数据库进行操作的方法都封装在里面。
servlet:简单说servlet就是跳转的类,当什么情况下干什么跳转到哪里。
import java.io.IOException;
import java.io.UnsupportedEncodingException;
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; /**
* Servlet implementation class servlet
*/
@WebServlet("/servlet")
public class servlet extends HttpServlet {
Dao dao=new Dao();
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public servlet() {
super();
// TODO Auto-generated constructor stub
} private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
String password = request.getParameter("password");
String sex = request.getParameter("sex");
Bean bean=new Bean(id,name,password,sex);
dao.update(bean);
request.setAttribute("message", "修改成功");
request.getRequestDispatcher("servlet?method=list").forward(request, response);
} private void list(HttpServletRequest request, HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
List<Bean> list = dao.list();
request.setAttribute("list", list);
request.getRequestDispatcher("list.jsp").forward(request,response);
} private void delete(HttpServletRequest request, HttpServletResponse response) throws Exception, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("UTF-8");
int id=Integer.parseInt(request.getParameter("id"));
dao.delete(id); //进行数据库的删除操作
request.setAttribute("message", "删除成功");
request.getRequestDispatcher("servlet?method=list").forward(request, response);
} private void insert(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
String password = request.getParameter("password");
String sex = request.getParameter("sex");
Bean bean=new Bean(id,name,password,sex);
if(dao.insert(bean)) {
request.setAttribute("message", "添加成功");
request.getRequestDispatcher("index.jsp").forward(request, response);
}
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
String method=request.getParameter("method");
if("insert".equals(method)) {
insert(request,response); }
else if("delete".equals(method)) {
try {
delete(request,response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
else if("update".equals(method)) {
update(request,response);
}
else if("list".equals(method)) {
try {
list(request,response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} } /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }
注意:在创建的时候一定要选择创建servlet而不是类如图:
输入完名字以后点击next选择自己要写的方法:
jsp页面:
index.jsp:主页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>首页</title> </head>
<body><%
Object message =request.getAttribute("message");
if(message!=null&&!"".equals(message)){
%>
<script type="text/javascript">
alert("<%=request.getAttribute("message")%>");
</script>
<%}%> <div align="center">
<h1>简单的增删改查</h1>
<div>
<a href="insert.jsp">添加</a>
</div>
<div>
<a href="servlet?method=list">删除</a>
</div>
<div>
<a href="servlet?method=list">修改</a>
</div>
<div>
<a href="servlet?method=list">查询</a>
</div> </div>
</body>
</html>
主页面就是一个菜单,至于为什么删除修改查询的链接都是servlet?method=list,那是因为他们都去调用servlet里面的list方法:
private void list(HttpServletRequest request, HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
List<Bean> list = dao.list();
request.setAttribute("list", list);
request.getRequestDispatcher("list.jsp").forward(request,response);
}
先把数据库里所有的信息显示出来,然后在通过request.getRequestDispatcher("list.jsp").forward(request,response);进行跳转,跳转到list.jsp界面,并将之前的所有数据(request,response)一并转发过去
insert.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>添加</title>
</head>
<body>
<%
Object message = request.getAttribute("message");
if (message != null && !"".equals(message)) {
%>
<script type="text/javascript">
alert("<%=request.getAttribute("message")%>"); //弹出对话框
</script>
<%
}
%>
<div align="center">
<h1>添加信息</h1>
<a href="index.jsp">返回主页</a>
<form action="servlet?method=insert" method="post">
<div>
id<input type="text" id="id" name="id" />
</div>
<div>
name<input type="text" id="name" name="name" />
</div>
<div>
password<input type="text" id="password" name="password" />
</div>
<div>
sex<input type="radio" id="sex" name="sex" value="男"/>男 <input type="radio"
id="sex" name="sex" value="女" />女
</div>
<div>
<button type="submit">添 加</button>
</div>
</form>
</div>
</body>
</html>
正常的添加页面。
list.jsp界面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
Object message = request.getAttribute("message");
Object grade_list = request.getAttribute("grade_list");
if(message!=null && !"".equals(message)){ %>
<script type="text/javascript">
alert("<%=request.getAttribute("message")%>");
</script>
<%} %>
<div align="center">
<h1 >信息列表</h1>
<a href="index.jsp">返回主页</a>
<table >
<tr>
<td>id</td>
<td>姓名</td>
<td>密码</td>
<td>性别</td>
<td align="center" colspan="2">操作</td>
</tr>
<c:forEach items="${list}" var="item">
<tr>
<td>${item.id}</td>
<td>${item.name}</td>
<td>${item.password}</td>
<td>${item.sex}</td>
<td><a href="update.jsp?id=${item.id}&name=${item.name}&password=${item.password}&sex=${item.sex}">修改</a></td>
<td><a href="servlet?method=delete&id=${item.id}">删除</a></td>
</tr>
</c:forEach>
</table>
</div> </body>
</html>
其中用到了标签库(<c:forEach>),需要导入jstl的包,并且加入其核心依赖,为固定值,如果不了解请点击:https://www.cnblogs.com/tkg1314/p/12008284.html查看jstl标签库。用<c:forEach>来遍历信息,然后每行信息都有删除和修改操作。修改的话跳转到update.jsp并且将id,name,password,sex的值传过去。删除是跳转到servlet的delete方法:
private void delete(HttpServletRequest request, HttpServletResponse response) throws Exception, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("UTF-8");
int id=Integer.parseInt(request.getParameter("id"));
dao.delete(id); //进行数据库的删除操作
request.setAttribute("message", "删除成功");
request.getRequestDispatcher("servlet?method=list").forward(request, response);
}
因为delete只需要id所以只需要将id传过去。
至于每个jsp里面的:
<%
Object message = request.getAttribute("message");
Object grade_list = request.getAttribute("grade_list");
if(message!=null && !"".equals(message)){ %>
<script type="text/javascript">
alert("<%=request.getAttribute("message")%>");
</script>
<%} %>
是用来获取servlet里面你通过setAttribute方法添加的信息(红色加粗):并且提示出来
private void insert(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
String password = request.getParameter("password");
String sex = request.getParameter("sex");
Bean bean=new Bean(id,name,password,sex);
if(dao.insert(bean)) {
request.setAttribute("message", "添加成功");
request.getRequestDispatcher("index.jsp").forward(request, response);
}
}
这样便完成了一个简单的java web 数据库的简单增删改查,没有做页面,那个password不是密码,只是一个名字,因此<input>标签没用password类型。
运行结果:
主页面:
添加操作:
添加之前的表数据:
添加之后
修改操作:
删除操作:
体会:做了一个简单的增删改查明白了每个类的作用以及联系。bean是用将属性的get,set等方法进行封装。dao层,是对数据库表操作的封装,里面有sql语句的执行等。而DBUtil是对数据库连接和关闭等操作的封装。servlet是跳转,通过调用dao层的方法实现跳转操作。然后jsp页面,有一个主页面 写超链接链接到其他页面。当然你对数据的删改都是在查询的基础上操作的,如果没有显示出信息就不能去删除和修改。当然我把id设为了主键自增,但我没有写验证主键的条件。另外还有什么不对的地方希望大家和老师多多指点!