当前位置:网站首页>Jsp+ajax+servlet+mysql to realize addition, deletion, modification and query (I)
Jsp+ajax+servlet+mysql to realize addition, deletion, modification and query (I)
2022-07-19 08:58:00 【Free [email protected]】
introduction : We usually java web In development , Form submission is usually used , This submission method is relatively simple , But if we want to add or delete, we will be prompted that the addition is successful , Or how to achieve a successful deletion , This is the time ajax Check it out .ajax Submit form The advantage of the form is that you can get a return value , So the server side servlet How to respond to a string to ajax Well , This is a difficult point . In this chapter, we demonstrate adding records , Later, it will be added gradually .
1、 Entity class :
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、 Database connection
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(" Successfully connected to database ");
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 layer
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、 Forms
<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 part , Remember to introduce jiquery Of jar package
<script type="text/javascript">
function add(form){
if(form.username.value==""){
alert(" Administrator user name cannot be empty ");
form.username.focus();
return false;
}
if(form.password.value==""){
alert(" Administrator password cannot be empty ");
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(" Insert the success ");
window.location.href="<%=path%>/LoginServlet?method=FindAllAct";
} else{
alert(" Insert the failure ");
}
}
});
});
});
</script>
3、 Server side 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、 design sketch
ajax Send a request to execute adding recorded data , Server through response.getWriter.wirte(JSONobject.toJSONString(ret); Return to one OK, After success, refresh the page servlet,
版权声明
本文为[Free [email protected]]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/200/202207170857335556.html
边栏推荐
猜你喜欢

Distributed transaction reliable message final consistency solution

Softmax regression + loss function + image classification dataset

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

深度学习第四周Key Concepts on Deep Neural Networks习题整理
![[Hongke] Introduction to genicam protocol](/img/a5/91a1d24a47ea2e3265530778d6fc1f.png)
[Hongke] Introduction to genicam protocol

Project code training tutorial

分布式事务-可靠消息最终一致性解决方案

分布式事务-最大努力通知方案

2022T电梯修理考试题库及答案

Dynamic memory management
随机推荐
Programming in the novel [serial 12] the moon bends in the yuan universe
Express
QR decomposition for matrix inversion -- C engineering implementation
HCIP --- OSPF的综合实验
小说里的编程 【连载之十一】元宇宙里月亮弯弯
VMware中扩展硬盘
QT serial communication
项目代码训练教程
Shell notes
scratch逆序输出 电子学会图形化编程scratch等级考试四级真题和答案解析2022年6月
Difference and connection between structure and Consortium
SDL图像显示
(鬼火引擎)中多设备的支持
Baidu Apollo
ARM计算新应用,违规垂钓“一网打尽”
OGG中token的使用
Introduction to deep learning exercises sorting in the first week of deep learning
MySQL存储函数和触发器
MySQL索引(一)
2022 Guangdong Provincial Safety Officer a certificate, the third batch (main person in charge) exercise questions and mock examination