首页 > 代码库 > extjs+servlet填充gird实现增删改查
extjs+servlet填充gird实现增删改查
由于项目工程中还有许多其他的练习,不好讲项目上传!
下面只说和本文章相关的代码
usergrid.jsp
js也写在其中了所以会有点乱
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href=http://www.mamicode.com/"">>
DBConnection.javapackage com.nuoxin.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DBConnection { private static Connection connection; private static Statement statement; private static ResultSet resultSet; public static Connection getConnection() { try { try { Class.forName("com.mysql.jdbc.Driver"); System.out.println("加载驱动"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } connection = DriverManager .getConnection( "jdbc:mysql://localhost:3306/user", "root", "root"); } catch (SQLException e) { // TODO Auto-generated catch block System.out.println("数据库连接失败"); e.printStackTrace(); } return connection; } public static Statement getStatement() { try { statement = getConnection().createStatement(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return statement; } public static ResultSet getResultSet(String sql) { try { resultSet = getStatement().executeQuery(sql); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return resultSet; } public static void close(){ if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (statement != null) { try { statement.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void main(String[] args) throws SQLException { ResultSet rs = getResultSet("select * from users"); while (rs.next()) { try { System.out.println(rs.getString("name")); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }UserSerivce.java
package com.iss.service; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.nuoxin.pojo.Users; import com.nuoxin.util.DBConnection; public class UserService { // 修改用户 public static void updateUser(Users user) { String sql = "update users set name='" + user.getName() + "',sex='" + user.getSex() + "',age='" + user.getAge() + "' where id=" + user.getId() + ""; try { Statement statement = DBConnection.getStatement(); statement.executeUpdate(sql); DBConnection.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } // 删除用户 public static void deleteUser(Users users) { String sql = "delete from users where id=" + users.getId() + ""; try { DBConnection.getStatement().executeUpdate(sql); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } DBConnection.close(); } // 添加用户 public static void addUser(Users user) { String sql = "insert into users values(null,'" + user.getName() + "','" + user.getSex() + "','" + user.getAge() + "')"; try { DBConnection.getStatement().executeUpdate(sql); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } DBConnection.close(); } public static Users getUser(int id) { String sql = "select * from users where id=" + id; Users user = null; ResultSet resultSet = DBConnection.getResultSet(sql); try { while (resultSet.next()) { user = new Users(); user.setId(resultSet.getInt("id")); user.setName(resultSet.getString("name")); user.setAge(resultSet.getString("sex")); user.setSex(resultSet.getString("age")); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return user; } }
几个servletgetUsersServlet
package com.nuoxin.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.LimitExceededException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.nuoxin.util.DBConnection;
public class GetUsersServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
request.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
StringBuilder stringBuilder;
String start = request.getParameter("start");
System.out.println("start:" + start);
String limit = request.getParameter("limit");
System.out.println("limit:" + limit);
String query = request.getParameter("query");
System.out.println(query);
// 判断条件
String countSql = "select count(*) from users ";
String selectSql = "select * from users limit " + start + "," + limit
+ "";
if (query != null && !"".equals(query)) {
query = new String(query.getBytes("iso-8859-1"), "utf-8");
System.out.println("query:" + query);
countSql += " where name=‘" + query + "‘;";
System.out.println(countSql);
selectSql = "select * from users where name=‘" + query + "‘ limit "
+ start + "," + limit + "";
System.out.println(selectSql);
}
int total = 0;
ResultSet resultSet = DBConnection.getResultSet(countSql);
// 添加异常快捷键 alt+shift+z
try {
while (resultSet.next()) {
total = resultSet.getInt(1);
System.out.println("total:" + total);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ResultSet rs = DBConnection.getResultSet(selectSql);
stringBuilder = new StringBuilder();
// 拼接json字符串 jdbc中下标从1开始
stringBuilder.append("{totalCount:" + total + ",bugs:[");
try {
while (rs.next()) {
stringBuilder.append("{");
stringBuilder.append("id:" + "\‘" + rs.getInt(1) + "\‘,");
stringBuilder.append("name:" + "\‘" + rs.getString(2) + "\‘,");
stringBuilder.append("sex:" + "\‘" + rs.getString(3) + "\‘,");
stringBuilder.append("age:" + "\‘" + rs.getString(4) + "\‘");
stringBuilder.append("},");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String json = null;
if (total != 0) {
json = stringBuilder.substring(0, stringBuilder.length() - 1);
}
// json = stringBuilder.substring(0, stringBuilder.length());
// json += "]}";
json = stringBuilder.append("]}").toString();
System.out.println("json:" + json);
out.print(json);
out.flush();
out.close();
}
}
getUserServlet 这个是修改用户时在userForm中加载用户
package com.nuoxin.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import com.iss.service.UserService;
import com.nuoxin.pojo.Users;
import com.nuoxin.util.DBConnection;
public class GetUserServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
int userId = Integer.parseInt(request.getParameter("userId"));
System.out.println("userId:" + userId);
Users user = UserService.getUser(userId);
// JSONArray jsonArray = JSONArray.fromObject(user);
System.out.println("{success:true,data:" + user + "}");
out.print("{success:true,data:" + user + "}");
// out.print("{success:true,data:{age:‘22‘,id:46,name:‘22‘,sex:‘22‘}}");
out.flush();
out.close();
}
}addUserSevlet
package com.nuoxin.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.iss.service.UserService;
import com.nuoxin.pojo.Users;
public class AddUserServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
String sex = request.getParameter("sex");
String age = request.getParameter("age");
Users user=new Users();
user.setName(name);
user.setSex(sex);
user.setAge(age);
System.out.println("name:"+user.getName());
UserService.addUser(user);
out.print("{success:true}");
out.flush();
out.close();
}
}deleteUserServlet 这里要注意引入解析json的包
package com.nuoxin.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.iss.service.UserService;
import com.nuoxin.pojo.Users;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class DeleteUserServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String deleteUsers = request.getParameter("deleteUsers");
System.out.println("deleteUsers:"+deleteUsers);
JSONArray jsonArray = JSONArray.fromObject(deleteUsers);
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
UserService.deleteUser((Users) JSONObject.toBean(jsonObject,
Users.class));
}
out.print("{success:true}");
out.flush();
out.close();
}
}
updateUserServlet
package com.nuoxin.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.iss.service.UserService;
import com.nuoxin.pojo.Users;
import com.nuoxin.util.DBConnection;
public class UpdateUserServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
int id = Integer.parseInt(request.getParameter("id"));
Users user = UserService.getUser(id);
user.setName(request.getParameter("name"));
user.setAge(request.getParameter("age"));
user.setSex(request.getParameter("sex"));
UserService.updateUser(user);
out.print("{success:true}");
out.flush();
out.close();
}
}
点击打开链接这是整个项目链接地址
extjs+servlet填充gird实现增删改查