当前位置:   article > 正文

eclipse之MySQL数据库与Web前端存储交互_eclipse创建的web项目.mysql

eclipse创建的web项目.mysql

首先我们新建一个HTML文件和一个Servlet文件

新建一个文件Package文件,命名为com.sql 

将此文件拖入lib文件里(下载mysql-connector-java jar包_mysql-connector-java-5.7.33jar-CSDN博客

在com.sql中创建以下文件

DBC文件内容:

  1. package com.sql;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. public class DBConnection {
  5. public static void main(String[] args) {
  6. }
  7. String driver = "com.mysql.jdbc.Driver";
  8. String url = "jdbc:mysql://localhost:3306/bigdata01?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false";
  9. String user = "root";
  10. String password = "2020";
  11. public Connection conn;
  12. public DBConnection() {
  13. try {
  14. Class.forName(driver);
  15. conn = (Connection) DriverManager.getConnection(url, user, password);
  16. } catch (Exception e) {
  17. e.printStackTrace();
  18. }
  19. }
  20. public void close() {
  21. try {
  22. this.conn.close();
  23. } catch (Exception e) {
  24. e.printStackTrace();
  25. }
  26. }
  27. }

MysqlUtil文件内容:

  1. package com.sql;
  2. import java.sql.PreparedStatement;
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6. import java.util.ArrayList;
  7. public class MysqlUtil {
  8. public static int add(String sql) {
  9. int i=0;
  10. DBConnection db = new DBConnection();
  11. try {
  12. PreparedStatement preStmt = (PreparedStatement) db.conn.prepareStatement(sql);
  13. preStmt.executeUpdate();
  14. preStmt.close();
  15. db.close();
  16. i = 1;
  17. System.out.println("sql = " + sql);
  18. } catch (Exception e) {
  19. e.printStackTrace();
  20. }
  21. return i;
  22. }
  23. public static int update(String sql) {
  24. int i =0;
  25. DBConnection db = new DBConnection();
  26. try {
  27. PreparedStatement preStmt = (PreparedStatement) db.conn.prepareStatement(sql);
  28. preStmt.executeUpdate();
  29. preStmt.close();
  30. db.close();
  31. i = 1;
  32. System.out.println("sql = " + sql);
  33. } catch (SQLException e) {
  34. e.printStackTrace();
  35. }
  36. return i;
  37. }
  38. public static int del(String delstr) {
  39. int i=0;
  40. DBConnection db = new DBConnection();
  41. try {
  42. PreparedStatement preStmt = (PreparedStatement) db.conn.prepareStatement(delstr);
  43. preStmt.executeUpdate();
  44. preStmt.close();
  45. db.close();
  46. i = 1;
  47. System.out.println("sql = " + delstr);
  48. } catch (SQLException e){
  49. e.printStackTrace();
  50. }
  51. return i;
  52. }
  53. public static int getCount(String sql) {
  54. int sum = 0;
  55. DBConnection db = new DBConnection();
  56. try {
  57. Statement stmt = (Statement) db.conn.createStatement();
  58. ResultSet rs = (ResultSet) stmt.executeQuery(sql);
  59. while (rs.next()) {
  60. sum += rs.getInt(1);
  61. }
  62. rs.close();
  63. db.close();
  64. } catch (Exception e) {
  65. }
  66. return sum;
  67. }
  68. public static String getJsonBySqlDataGrid( String sqlcount,String sql,String[] colums){
  69. int count = getCount(sqlcount);
  70. System.err.println("sql=" + sql);
  71. ArrayList<String[]> result = new ArrayList<String[]>();
  72. DBConnection db = new DBConnection();
  73. try {
  74. Statement stmt = (Statement) db.conn.createStatement();
  75. ResultSet rs = (ResultSet) stmt.executeQuery(sql);
  76. while(rs.next()){
  77. String[] dataRow = new String[colums.length];
  78. for( int i = 0; i < dataRow.length; i++ ) {
  79. dataRow[i] = rs.getString( colums[i] );
  80. }
  81. result.add(dataRow);
  82. }
  83. rs.close();
  84. db.close();//
  85. } catch (SQLException e) {
  86. e.printStackTrace();
  87. }
  88. return listToJsonDataGrid(result,colums,count);
  89. }
  90. public static String getJsonBySql( String sql,String[] colums){
  91. System.err.println("sql=" + sql);
  92. ArrayList<String[]> result = new ArrayList<String[]>();
  93. DBConnection db = new DBConnection();
  94. try {
  95. Statement stmt = (Statement) db.conn.createStatement();
  96. ResultSet rs = (ResultSet) stmt.executeQuery(sql);
  97. while(rs.next()){
  98. String[] dataRow = new String[colums.length];
  99. for( int i = 0; i < dataRow.length; i++ ) {
  100. dataRow[i] = rs.getString( colums[i] );
  101. }
  102. result.add(dataRow);
  103. }
  104. rs.close();
  105. db.close();//
  106. } catch (SQLException e) {
  107. e.printStackTrace();
  108. }
  109. return listToJson(result,colums);
  110. }
  111. public static ArrayList<String[]> showUtil( String sql, String[] colums){
  112. ArrayList<String[]> result = new ArrayList<String[]>();
  113. DBConnection db = new DBConnection();
  114. try {
  115. Statement stmt = (Statement) db.conn.createStatement();
  116. ResultSet rs = (ResultSet) stmt.executeQuery(sql);
  117. while(rs.next()){
  118. String[] dataRow = new String[colums.length];
  119. for( int i = 0; i < dataRow.length; i++ ) {
  120. dataRow[i] = rs.getString( colums[i] );
  121. }
  122. result.add(dataRow);
  123. }
  124. rs.close();
  125. db.close();//
  126. } catch (SQLException e) {
  127. e.printStackTrace();
  128. }
  129. return result;
  130. }
  131. public static String listToJsonDataGrid( ArrayList<String[]> list,String[] colums,int count) {
  132. String jsonStr = "{\"code\":0,\"msg\":\"success\",\"count\":"+count+",\"data\":[";
  133. for(int i = 0; i < list.size(); i++) {
  134. String arr = "{";
  135. for( int j = 0; j < list.get(0).length; j++) {
  136. if( list.get(i)[j] == null || "NULL".equals(list.get(i)[j])) {
  137. arr += "\"" + colums[j] + "\":\"\"";
  138. }else {
  139. arr += "\"" + colums[j] + "\""+":" ;
  140. arr += "\"" + list.get(i)[j].replace("\"","\\\"") + "\"";
  141. }
  142. if( j < list.get(0).length - 1 ) {
  143. arr += ",";
  144. }
  145. }
  146. arr += "}";
  147. if( i < list.size() - 1 ) {
  148. arr += ",";
  149. }
  150. jsonStr += arr;
  151. }
  152. jsonStr += "]}";
  153. return jsonStr;
  154. }
  155. public static String listToJson( ArrayList<String[]> list,String[] colums) {
  156. String jsonStr = "{\"code\":0,\"msg\":\"success\",\"data\":[";
  157. for(int i = 0; i < list.size(); i++) {
  158. String arr = "{";
  159. for( int j = 0; j < list.get(0).length; j++) {
  160. if( list.get(i)[j] == null || "NULL".equals(list.get(i)[j])) {
  161. arr += "\"" + colums[j] + "\":\"\"";
  162. }else {
  163. arr += "\"" + colums[j] + "\""+":" ;
  164. arr += "\"" + list.get(i)[j].replace("\"","\\\"") + "\"";
  165. }
  166. if( j < list.get(0).length - 1 ) {
  167. arr += ",";
  168. }
  169. }
  170. arr += "}";
  171. if( i < list.size() - 1 ) {
  172. arr += ",";
  173. }
  174. jsonStr += arr;
  175. }
  176. jsonStr += "]}";
  177. return jsonStr;
  178. }
  179. }

然后再HTML文件里写入

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Insert title here</title>
  6. <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"> </script>
  7. </head>
  8. <!-- onload刷新页面就会触发该方法 -->
  9. <body onload="get()">
  10. <div id = "hhh"></div>
  11. </body>
  12. <script>
  13. function get(){
  14. $.ajax({
  15. type:"get",
  16. url:"/BigData02/UserServlet",
  17. success:function(data){
  18. console.log(data);
  19. showData(data.data)
  20. }
  21. })
  22. }
  23. function showData(data){
  24. var html = '<table border="1">';
  25. for(var i = 0; i < data.length; i++){
  26. html += '<tr>';
  27. html += '<td>' + data[i].id + '</td>';
  28. html += '<td>' + data[i].username + '</td>';
  29. html += '<td>' + data[i].password + '</td>';
  30. html += '<td>';
  31. html += '<input type="button" value="编辑" />';
  32. html += '<input type="button" value="删除" />';
  33. html += '</td>';
  34. html += '</tr>';
  35. }
  36. html += '</table>';
  37. $("#hhh").empty().append(html);
  38. }
  39. </script>
  40. </html>

包含了一个使用jQuery进行AJAX请求并展示用户数据的功能。页面加载完成后会调用 get() 方法,该方法通过AJAX请求从服务器获取数据,并在成功后调用 showData() 方法展示数据。

在展示数据的部分,会将获取到的数据以表格的形式展示在页面上,每一行代表一个用户的信息,包括用户ID、用户名和密码,并且每行最后有一个"编辑"和"删除"按钮。

请注意,为了使这段代码正常工作,需要确保 /BigData02/UserServlet 能够正确处理 GET 请求并返回符合预期格式的用户数据

sql数据库文件内容:

更改sevtel文件;

  1. package com.bigdata;
  2. import java.io.IOException;
  3. import javax.servlet.ServletException;
  4. import javax.servlet.annotation.WebServlet;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import com.sql.MysqlUtil;
  9. /**
  10. * Servlet implementation class UserServlet
  11. */
  12. @WebServlet("/UserServlet")
  13. public class UserServlet extends HttpServlet {
  14. private static final long serialVersionUID = 1L;
  15. /**
  16. * @see HttpServlet#HttpServlet()
  17. */
  18. public UserServlet() {
  19. super();
  20. // TODO Auto-generated constructor stub
  21. }
  22. /**
  23. * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  24. */
  25. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  26. String sql = "select * from user";
  27. String[] colums = {"id","username","password"};
  28. String data = MysqlUtil.getJsonBySql(sql, colums);
  29. System.out.println(data);
  30. response.setCharacterEncoding("utf-8");
  31. response.setContentType("application/json; charset=utf-8");
  32. response.getWriter().append(data);
  33. }
  34. /**
  35. * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  36. */
  37. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  38. // TODO Auto-generated method stub
  39. doGet(request, response);
  40. }
  41. }

这段代码是一个简单的Java Servlet类,名为UserServlet,用于处理GET请求和POST请求。在该Servlet中,定义了doGet()和doPost()方法来处理GET请求和POST请求。

在doGet()方法中,首先构建了一个查询语句"select * from user",然后调用MysqlUtil类的getJsonBySql()方法来执行查询并获取返回的JSON格式数据。接着设置响应的字符编码和内容类型为JSON格式,并将查询结果通过response.getWriter().append(data)写入响应,返回给客户端。

在doPost()方法中,直接调用了doGet()方法,实现了POST请求的处理逻辑与GET请求相同。

该Servlet的作用是在接收到GET请求时,从数据库中查询用户信息,并将查询结果以JSON格式返回给客户端。前端页面中的AJAX请求会调用这个Servlet来获取用户信息并展示在页面上。

结果为:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/933454
推荐阅读
相关标签
  

闽ICP备14008679号