当前位置:网站首页>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
边栏推荐
- 【手写数字识别】基于Lenet网络实现手写数字识别附matlab代码
- ARM计算新应用,违规垂钓“一网打尽”
- Difference and connection between structure and Consortium
- 小说里的编程 【连载之十三】元宇宙里月亮弯弯
- Nacos new configuration management
- LeetCode 0115.不同的子序列
- Bean的作用域和生命周期
- Hcip - Comprehensive Experiment of OSPF
- [handwritten numeral recognition] handwritten numeral recognition based on lenet network with matlab code
- Programming in the novel [serial 12] the moon bends in the yuan universe
猜你喜欢
[untitled]
2022年上海市安全员C证国家题库及答案
Translucent double glass side thickness
动态内存管理
Hcip - Comprehensive Experiment of OSPF
SSM实现一对一查询实战详细教程(一)
HCIP --- OSPF的综合实验
LabVIEW用了多线程,程序是不是会跑的更快些
2022t elevator repair examination question bank and answers
解决ApplicationEventMulticaster not initialized - call ‘refresh‘ before multicasting events异常
随机推荐
Translucent double glass side thickness
2022t elevator repair examination question bank and answers
QR decomposition for matrix inversion -- C engineering implementation
Cocos shader basics 7
[face recognition] face recognition based on histogram histogram with matlab code
[leetcode] general operation summary
ES6 learning function (strict mode, higher-order function, closure)
How to write a string field in MySQL if its value is not empty?
[Hongke] lidar safety system: making the world safer
HCIP --- OSPF的综合实验
分布式事务-最大努力通知方案
MySQL存储函数和触发器
Expanding hard disk in VMWare
What is memory overflow
LabVIEW32位与64位的兼容性
Nacos 新建配置管理
VMware中扩展硬盘
SSM实现一对一查询实战详细教程(一)
Distributed transaction reliable message final consistency solution
第七天训练