当前位置:网站首页>Jsp+Ajax+Servlet+Mysql实现增删改查(一)
Jsp+Ajax+Servlet+Mysql实现增删改查(一)
2022-07-17 08:57:00 【逍遥游@】
引言:我们通常在java web开发中,通常使用表单提交,这种提交方式比较简单,但是如果我们想添加或者删除后提示一条添加成功,或者删除成功该如何实现呢,这个时候就需要ajax进行校验了。ajax提交form表单的好处就是可以得到一个返回值,那么服务端servlet如何回应一个字符串给ajax呢,这是个难点。本章节一我们演示增加记录,稍后的会逐步添加上。
1、实体类:
package edu.jmi.model;
import java.io.Serializable;
import java.sql.Date;
public class Admin implements Serializable{
@Override
public String toString() {
return "Admin [id=" + id + ", username=" + username + ", password=" + password + ", creatTime=" + createTime
+ ", status=" + status + "]";
}
public Integer getId() {
return id;
}
public void setId(Integer 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;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
private Integer id;
private String username;
private String password;
private Date createTime;
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
private Integer status;
}
2、数据库连接
package edu.jmi.util;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBUtils {
final static String DRIVER="com.mysql.jdbc.Driver";
final static String URL="jdbc:mysql://localhost:3306/meal?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull";
final static String USER="root";
final static String PASSWORD="123456";
public static Connection getConnection(){
try{
Class.forName(DRIVER);
Connection connection=DriverManager.getConnection(URL,USER,PASSWORD);
System.out.println("连接成功数据库");
return connection;
}catch(Exception e){
e.printStackTrace();
return null;
}
}
public static void closeConnection(Connection con){
try{
con.close();
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args){
DBUtils db=new DBUtils();
DBUtils.getConnection();
//System.out.print(c);
}
}
3、Dao层
public boolean insert(Admin admin){
Connection c=null;
try{
c=DBUtils.getConnection();
String sql="insert into admin(username,password,createTime,status) values (?,?,?,?)";
PreparedStatement pst=c.prepareStatement(sql);
pst.setString(1,admin.getUsername());
pst.setString(2, admin.getPassword());
pst.setString(3,String.valueOf(admin.getCreateTime()));
pst.setInt(4, admin.getStatus());
pst.execute();
return true;
}catch(Exception e){
e.printStackTrace();
return false;
}finally{
DBUtils.closeConnection(c);
}
}
4、表单
<form id="addForm" method="post" onSubmit="return add(this)">
<input class="form-control" name="username" type="text" placeholder="Enter full UserName">
<input class="form-control " name="password" type="text" placeholder="Enter full PassWord">
<input type="date" class="form-control " name="createTime" />
<button class="btn btn-primary" id="addButton">OK</button>
</form>
5、js部分,记得引入jiquery的jar包
<script type="text/javascript">
function add(form){
if(form.username.value==""){
alert("管理员用户名不能为空");
form.username.focus();
return false;
}
if(form.password.value==""){
alert("管理员密码不能为空");
form.password.focus();
return false;
}
}
$(document).ready(function(){
$("#addButton").click(function(){
$.ajax({
type: "post",
url: "<%=path %>/AdminServlet?method=insertAdmin",
data: $("#addForm").serialize(),
dataType:'json',
success: function(data){
console.log(data.type);
console.log(data.status);
if(data.type =="ok"){
alert("插入成功");
window.location.href="<%=path%>/LoginServlet?method=FindAllAct";
} else{
alert("插入失败");
}
}
});
});
});
</script>
3、服务端servlet
private void insert(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
AdminDao adminDao=new AdminDao();
Map<String, String> ret=new HashMap<String, String>();
String uname=request.getParameter("username");
String pwd=request.getParameter("password");
Date createTime=Date.valueOf(request.getParameter("createTime"));
Admin admin=new Admin();
admin.setUsername(uname);
admin.setPassword(pwd);
admin.setStatus(1);
admin.setCreateTime(createTime);
boolean b=adminDao.insert(admin);
System.out.println(b);
if(b==true){
ret.put("type", "ok");
response.getWriter().write(JSONObject.toJSONString(ret));
return;
}else{
response.sendRedirect("/WEB-INF/views/admin/addAdmin.jsp");
}
}
6、效果图
ajax发出请求执行增加记录的数据,服务端通过response.getWriter.wirte(JSONobject.toJSONString(ret);返回一个OK,成功之后在执行刷新页面的servlet,
边栏推荐
- 【回归预测】基于粒子滤波实现锂离子电池寿命预测附matlab代码
- Paddleserving service deployment tensorrt reports an error, shape of TRT subgraph is [-1, -1768],
- ES6 learning function (strict mode, higher-order function, closure)
- Unity 使用一张贴图来控制材质主贴图的透明度
- LabVIEW32位与64位的兼容性
- scratch逆序输出 电子学会图形化编程scratch等级考试四级真题和答案解析2022年6月
- Dynamic memory management
- Error received from peer ipv4/connection reset by peer paddleserving
- 【无标题】
- [face recognition] face recognition based on histogram histogram with matlab code
猜你喜欢

Bean的作用域和生命周期

【AXI】解读AXI协议的额外信号(QOS信号,REGION信号,与USER信号)

LabVIEW32位与64位的兼容性

Scratch reverse order output electronic society graphical programming scratch grade examination level 4 true questions and answers analysis June 2022

如何在 Authing 上快速实现 Zadig 单点登录?

【虹科】激光雷达安全系统:让世界更安全

Finishing of key concepts on deep neural networks exercises in the fourth week of in-depth learning

Softmax regression + loss function + image classification dataset

mongodb $符号的神奇用法+mongo数据类型

Idea debug according to conditional breakpoints
随机推荐
LeetCode 0116. Populate the next right node pointer for each node
Yyds dry inventory cross origin cross domain request
VMware中扩展硬盘
How to position the circle of friends? Three core steps to build a circle of friends selling popular products
终结重复开发,两三下搞定登录系统个性化
Matlab imports floating-point numbers with more than 9 digits after the decimal point
Expanding hard disk in VMWare
Distributed transaction best effort notification scheme
MySQL中查询一个字符串字段的值不为空到底该怎么写?
动态内存管理
vscode下载历史版本
【CTF】pwn2_sctf_2016
Cbcgpedit control used by BCG
2022年上海市安全员C证国家题库及答案
SDL图像显示
软件测试需要学习多久?
[face recognition] face recognition based on histogram histogram with matlab code
SQL优化
ARM计算新应用,违规垂钓“一网打尽”
LabVIEW32位与64位的兼容性