对于利用JavaBean+Servlet+jsp实现增删改查功能题目的实现
首先,为了更好地规范代码,可以分别将不同用处的Java文件放置到不同的文件夹里面
对于实体类,可以放在名为Bean的package里面
对于中间用来实现Java与jsp页面交互的类,可以放在名为Servlet的package里面
对于放置增删改查操作的方法的类,可以放在名为Dao的package里面
对于如果你不想要每次每一个操作方法就要连接一次数据库的话,可以将连接数据库的方法放在DBUtil.java类里面,放在名为DBUtils的package里面
具体的实现方法如下:
//mainBean.java
public class mainBean{
private String name;
private String id;
private String teacher;
private String whe;
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public void setId(String id){
this.id=id;
}
public String getId(){
return id;
}
public void setTeacher(String teacher){
this.teacher=teacher;
}
public String getTeacher(){
return teacher;
}
public void setWhe(String whe){
this.whe=whe;
}
public String getWhe(){
return whe;
}
public mainBean(){}
public mainBean(String name,String id,String teacher,String whe){
this.name=name;
this.id=id;
this.teacher=teacher;
this.whe=whe;
}
在封装数据库的连接操作时,可以选择使用JDBC连接,也可以使用db.properties进行连接,在这里示范的是后者
//db.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:/mysql://localhost:3306/数据库名称
username=用户名
pass=密码
需要注意到的是,有时db文件里面的url需要加上时区等内容,否则就会报错!
//DBUtil.java
package DBUtils;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class DBUtil {
private static String driver;
private static String url;
private static String username;
private static String pass;
static{
InputStream is=DBUtil.class.getClassLoader().getResourceAsStream("db.properties");
Properties p=new Properties();
try{
p.load(is);
driver=p.getProperty("driver");
url=p.getProperty("url");
username=p.getProperty("username");
pass=p.getProperty("pass");
Class.forName(driver);
System.out.println("驱动注册成功!");
} catch (IOException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
public static Connection getConn() throws SQLException {
Connection conn=null;
conn= DriverManager.getConnection(url,username,pass);
System.out.println("数据库连接成功!");
return conn;
}
public static void close(PreparedStatement ps,Connection conn) throws SQLException {
if(ps!=null){
ps.close();
}
if(conn!=null){
conn.close();
}
}
public static void close(Statement stmt,Connection conn) throws SQLException {
if(stmt!=null){
stmt.close();
}
if(conn!=null){
conn.close();
}
}
public static void close(PreparedStatement ps,Connection conn,ResultSet rs) throws SQLException {
if(rs!=null){
rs.close();
}
if(ps!=null){
ps.close();
}
if(conn!=null){
conn.close();
}
}
}
//interDao.java
package Dao;
import Bean.mainBean;
import java.sql.SQLException;
import java.util.List;
public interface interDao {
boolean addMain(mainBean bean) throws SQLException;
List<mainBean> searchMain(String name) throws SQLException;
boolean updateMain(mainBean main) throws SQLException;
boolean deleteMain(String name) throws SQLException;
}
//getDao.java
package Dao;
import Bean.mainBean;
import DBUtils.DBUtil;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class getDao implements interDao{
private static final String sql_insert="insert into we values(?,?,?,?)";
private static final String sql_delete="delete from we where name=?";
private static final String sql_update="update we set id=?,teacher=?,whe=? where name=?";
private static final String sql_search="select * from we where name=?";
@Override
public boolean addMain(mainBean main) throws SQLException {
Connection conn= null;
PreparedStatement ps=null;
try {
conn = DBUtil.getConn();
ps=conn.prepareStatement(sql_insert);
ps.setString(1,main.getName());
ps.setString(2,main.getId());
ps.setString(3,main.getTeacher());
ps.setString(4,main.getWhe());
int x=ps.executeUpdate();
return x>0?true:false;
} catch (SQLException e) {
throw new RuntimeException(e);
}finally{
DBUtil.close(ps,conn);
}
}
@Override
public List<mainBean> searchMain(String name) throws SQLException {
List<mainBean> list=new ArrayList<mainBean>();
Connection conn=DBUtil.getConn();
PreparedStatement ps=null;
ResultSet rs=null;
try{
ps=conn.prepareStatement(sql_search);
ps.setString(1,name);
rs=ps.executeQuery();
while(rs.next()){
mainBean main=new mainBean();
main.setName(rs.getString("name"));
main.setId(rs.getString(1));
main.setTeacher(rs.getString(2));
main.setWhe(rs.getString(3));
list.add(main);
}
} catch (SQLException e) {
throw new RuntimeException(e);
}finally{
DBUtil.close(ps,conn,rs);
}
return null;
}
@Override
public boolean updateMain(mainBean main) throws SQLException {
Connection conn=DBUtil.getConn();
PreparedStatement ps=null;
try{
ps=conn.prepareStatement(sql_update);
ps.setString(1,main.getId());
ps.setString(2,main.getTeacher());
ps.setString(3,main.getWhe());
ps.setString(4,main.getName());
int x=ps.executeUpdate();
return x>0?true:false;
} catch (SQLException e) {
throw new RuntimeException(e);
}finally{
DBUtil.close(ps,conn,null);
}
}
@Override
public boolean deleteMain(String name) throws SQLException {
Connection conn=DBUtil.getConn();
PreparedStatement ps=null;
try{
ps=conn.prepareStatement(sql_delete);
ps.setString(1,name);
int x=ps.executeUpdate();
return x>0?true:false;
} catch (SQLException e) {
throw new RuntimeException(e);
}finally{
DBUtil.close(ps,conn);
}
}
}
//mainServlet.java
package Servlet;
import Bean.mainBean;
import Dao.getDao;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/mainServlet")
public class mainServlet extends HttpServlet {
private static final long serialVersionUID = 1L;//使得兼容性更强一些
getDao gg=new getDao();
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String method=req.getParameter("method");
try {
if ("searchMain".equals(method)) {
searchMain(req, resp);
} else if ("addMain".equals(method)) {
addMain(req, resp);
} else if ("updateMain".equals(method)) {
updateMain(req, resp);
} else if ("deleteMain".equals(method)) {
deleteMain(req, resp);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public mainServlet(){ super(); }
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//super.doPost(req, resp);
doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().append("Served at:").append(req.getContextPath());
}
private void searchMain(HttpServletRequest req, HttpServletResponse resp) throws IOException, SQLException, ServletException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
String name=req.getParameter("name");
Connection conn= DBUtil.getConn();
PreparedStatement psmt=null;
ResultSet rs=null;
psmt=conn.prepareStatement("select * from we where name=?");
psmt.setString(1,name);
rs=psmt.executeQuery();
while(rs.next()){
req.setAttribute("name",rs.getString("name"));
req.setAttribute("id",rs.getString("id"));
req.setAttribute("teacher",rs.getString("teacher"));
req.setAttribute("whe",rs.getString("whe"));
req.getRequestDispatcher("check2.jsp").forward(req,resp);
}
DBUtil.close(psmt,conn,rs);
}
private void addMain(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
String name=req.getParameter("name");
String id=req.getParameter("id");
String teacher=req.getParameter("teacher");
String whe=req.getParameter("whe");
mainBean main=new mainBean();
main.setName(name);
main.setId(id);
main.setTeacher(teacher);
main.setWhe(whe);
if(gg.addMain(main)){
req.setAttribute("main",main);
req.setAttribute("name","添加成功!");
req.getRequestDispatcher("search.jsp").forward(req,resp);
}else{
req.setAttribute("name","添加失败!");
req.getRequestDispatcher("index.jsp").forward(req,resp);
}
}
protected void updateMain(HttpServletRequest req, HttpServletResponse resp) throws IOException, SQLException, ServletException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
String name=req.getParameter("name");
String id=req.getParameter("id");
String teacher=req.getParameter("teacher");
String whe=req.getParameter("whe");
mainBean main=new mainBean();
main.setName(name);
main.setId(id);
main.setTeacher(teacher);
main.setWhe(whe);
if(gg.updateMain(main)){
req.setAttribute("name","修改成功!");
req.getRequestDispatcher("search.jsp").forward(req,resp);
}else{
req.setAttribute("name","修改失败!");
req.getRequestDispatcher("update.jsp").forward(req,resp);
}
}
protected void deleteMain(HttpServletRequest req, HttpServletResponse resp) throws IOException, SQLException, ServletException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
String name=req.getParameter("name");
if(gg.deleteMain(name)){
req.setAttribute("name","删除成功!");
req.getRequestDispatcher("search.jsp").forward(req,resp);
}else{
req.setAttribute("name","删除失败!");
req.getRequestDispatcher("delete.jsp").forward(req,resp);
}
}
}
//Main.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>主界面</title>
</head>
<body>
<center>
<tr>
<button type="submit" value="添加" onclick="window.location.href='index.jsp'">添加信息</button>
</tr>
<p>
<tr>
<button type="submit" value="修改" onclick="window.location.href='update.jsp'">修改信息</button>
</tr>
<p>
<tr>
<button type="submit" value="删除" onclick="window.location.href='delete.jsp'">删除信息</button>
</tr>
<p>
<tr>
<button type="submit" value="浏览" onclick="window.location.href='search.jsp'">浏览信息</button>
</tr>
<p>
<tr>
<button type="submit" value="查询" onclick="window.location.href='check1.jsp'">查询信息</button>
</tr>
</center>
</body>
</html>
//check1.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>查询界面</title>
</head>
<body>
<center>
<form action="mainServlet?method=searchMain" method="post">
<h1>查询</h1>
<tr>
<input type="text" name="name" id="name" placeholder="请输入你想要查询的学生姓名">
</tr>
<p>
<tr>
<button type="submit" value="查询">查询</button>
</tr>
</form>
</center>
</body>
</html>
//check2.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>显示界面</title>
</head>
<body>
<center>
<form>
<tr>
<td>学生姓名</td>
<td>学生学号</td>
<td>教师姓名</td>
<td>授课地点</td>
</tr>
<p>
<tr>
<td>${name}</td>
<td>${id}</td>
<td>${teacher}</td>
<td>${whe}</td>
</tr>
</form>
</center>
</body>
</html>
//index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>添加界面</title>
</head>
<body>
<center>
<form action="mainServlet?method=addMain" method="post">
<table>
<tr>
<td>学生姓名:</td>
<td><input type="text" name="name" id="name" placeholder="请输入学生姓名" required></td>
</tr>
<p>
<tr>
<td>学生学号:</td>
<td><input type="text" name="id" id="id" placeholder="请输入学生学号:" required></td>
</tr>
<p>
<tr>
<td>教师姓名:</td>
<td><input type="text" name="teacher" id="teacher" placeholder="请输入教师姓名:" required></td>
</tr>
<p>
<tr>
<td>授课地点:</td>
<td><input type="text" name="whe" id="whe" placeholder="请输入授课地点:" required></td>
</tr>
<p>
</table>
<tr>
<button type="submit" value="提交">提交</button>
</tr>
</form>
</center>
</body>
</html>
//search.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>浏览界面</title>
</head>
<body>
<center>
<tr>
<th scope="col"> 学生姓名 </th>
<th scope="col"> 学生学号 </th>
<th scope="col"> 教师姓名 </th>
<th scope="col"> 授课地点 </th>
</tr>
<p>
<%
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/ad?useUnicode=true&characterEncoding=utf-8","root","20214063");
Statement ps=conn.createStatement();
ResultSet rs=ps.executeQuery("select * from we");
while(rs.next()){
out.println(" <tr> <th scope=row > " + rs.getString(1) + " </th><td> "+ rs.getString(2) + " </td><td> " + rs.getString(3) + " </td><td> " + rs.getString(4) + " </td></tr><p> ");
}
rs.close();
ps.close();
conn.close();
%>
</center>
</body>
</html>
//delete.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>删除界面</title>
</head>
<body>
<center>
<form action="mainServlet?method=deleteMain" method="post">
<table>
<h1>删除</h1>
<tr>
<td>学校姓名:</td>
<td><input type="text" name="name" id="name" placeholder="请输入你想要删除的学生姓名:"></td>
</tr>
</table>
<p>
<button type="submit" value="提交">删除</button>
</form>
</center>
</body>
</html>
咳咳,update.jsp代码与index.jsp代码基本一致,只需要改一改action里面的值就可以啦!就不写出来了
本次内容仅仅提供代码进行参考,对界面是否漂亮并没有做出要求!!!
对于利用JavaBean+Servlet+jsp实现增删改查功能题目的实现的更多相关文章
- C#利用WinForm调用WebServices实现增删改查
实习导师要求做一个项目,用Winform调用WebServices实现增删改查的功能.写下这篇博客,当做是这个项目的总结.如果您有什么建议,可以给我留言.欢迎指正. 1.首先,我接到这个项目的时候,根 ...
- vue实战(一):利用vue与ajax实现增删改查
vue实战(一):利用vue与ajax实现增删改查: <%@ page pageEncoding="UTF-8" language="java" %> ...
- JavaWeb后端jsp之增删改查
今日主题:JavaWeb后端jsp之增删改查 实体类: Student.java: package cn.itcast.model.entity; public class Student { pri ...
- Android(java)学习笔记193:利用谷歌API对数据库增删改查(推荐使用)
接下来我们通过项目案例来介绍:这个利用谷歌API对数据库增删改查 1.首先项目图: 2.这里的布局文件activity_main.xml: <LinearLayout xmlns:android ...
- Android(java)学习笔记136:利用谷歌API对数据库增删改查(推荐使用)
接下来我们通过项目案例来介绍:这个利用谷歌API对数据库增删改查 1. 首先项目图: 2. 这里的布局文件activity_main.xml: <LinearLayout xmlns:andro ...
- IDEA搭建SSM实现登录、注册,数据增删改查功能
本博文的源代码:百度云盘/java/java实例/SSM实例/SSM实现登录注册,增删改查/IDEA搭建SSM实现登录,注册,增删改查功能.zip 搭建空的Maven项目 使用Intellij id ...
- springmvc+spring3+hibernate4框架简单整合,简单实现增删改查功能
转自:https://blog.csdn.net/thinkingcao/article/details/52472252 C 所用到的jar包 数据库表 数据库表就不用教大家了,一张表,很简 ...
- JavaWeb 增删改查功能
1.今天来写一个简单的增删改查功能,这个项目还是接着在昨天写的 --JavaWeb实现简单登录注册-- 来写的. 登录成功进来后对学生信息的增删改查 2.项目文件为: 3.好了,直接贴上今天新写的代码 ...
- ES6学习笔记(三):教你用js面向对象思维来实现 tab栏增删改查功能
前两篇文章主要介绍了类和对象.类的继承,如果想了解更多理论请查阅<ES6学习笔记(一):轻松搞懂面向对象编程.类和对象>.<ES6学习笔记(二):教你玩转类的继承和类的对象>, ...
- Online Coding开发模式 (通过在线配置实现一个表模型的增删改查功能,无需写任何代码)
JEECG 智能开发平台. 开发模式由代码生成器转变为Online Coding模式 (通过在线配置实现一个表模型的增删改查功能,无需一行代码,支持用户自定义 ...
随机推荐
- Window:下载并安装FileZilla客户端
FileZilla官方网站:https://filezilla-project.org/ 环境 操作系统:Window 10 企业版LTSC;内存:8GB;操作类型:64位. 说明 本人想在腾讯云的系 ...
- bigdecimal 比较大小、bigdecimal 数学运算、bigdecimal 精度
创建 BigDecimal 建议使用 public BigDecimal(String val),使用 number 参数可能会有精度问题 设置精度 setScale(3, BigDecimal.RO ...
- 在控制台中输入msqyl一直报ERROR 2003 (HY000): Can't connect to MySQL server on 'localhost'错误
错误: 在绿色Mysql的bin文件下打开cmd,输入mysql,一直报ERROR 2003 (HY000): Can't connect to MySQL server on 'localhost' ...
- 【RTOS】《基于嵌入式实时操作系统的程序设计技术》——任务的划分与封装
任务的划分与封装 关键任务的划分处理 对于某些对于系统的正常运作至关重要,少执行一次会对系统产生较大影响的功能,我们倾向于将它从原有任务中剥离出来,称为关键任务,用一个独立任务或者ISR(如外部中断) ...
- HDFS Shell 操作
HDFS Shell 操作 HDFS Shell 命令行格式 格式一:hadoop fs –命令名 参数 格式二:hdfs dfs –命令名 参数 HDFS 常用命令及参数 ls:查看 hdfs 中的 ...
- not eligible for getting processed by all BeanPostProcessors
描述 这个BUG大的起源是我上线以后,在后台看日志的时候发现一行奇怪的INFO日志: 2022-06-09 23:34:24 [restartedMain] [org.springframework. ...
- python+scrcpy实现将安卓设备录屏并保存到pc本地
一)scrcpy下载及安装 参考链接:https://zhuanlan.zhihu.com/p/80264357 二)python+scrcpy实现将安卓设备录屏并保存到pc本地 示例代码: impo ...
- bquote
在Linux环境下,按"·"(1左边的按钮)会进入bquote模式 退出方法 按 Ctrl + C 其它(待补充)
- IntelliJ IDEA 最新激活破解教程,永久激活,亲测有效
使用ja-netfilter激活Jetbrains系列软件 注意:无限试用脚本已经失效.本教程适合2021.3.*之上的高版本,使用ja-netfilter插件进行激活操作,永久有效 激活步骤: 第一 ...
- mybatis的xml中#{}和${}区别
#{}表示一个占位符号,通过#{}可以实现preparedStatement向占位符中设置值,自动进行java类型和jdbc类型转换,#{}可以有效防止sql注入.初步编译后的sql语句是" ...