首先我们新建一个HTML文件和一个Servlet文件
新建一个文件Package文件,命名为com.sql
将此文件拖入lib文件里(下载mysql-connector-java jar包_mysql-connector-java-5.7.33jar-CSDN博客)
在com.sql中创建以下文件
DBC文件内容:
解释
-
package com.sql;
-
import java.sql.Connection;
-
import java.sql.DriverManager;
-
public class DBConnection {
-
public static void main(String[] args) {
-
}
-
String driver = "com.mysql.jdbc.Driver";
-
String url = "jdbc:mysql://localhost:3306/bigdata01?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false";
-
String user = "root";
-
String password = "2020";
-
public Connection conn;
-
public DBConnection() {
-
try {
-
Class.forName(driver);
-
conn = (Connection) DriverManager.getConnection(url, user, password);
-
} catch (Exception e) {
-
e.printStackTrace();
-
}
-
}
-
public void close() {
-
try {
-
this.conn.close();
-
} catch (Exception e) {
-
e.printStackTrace();
-
}
-
}
-
}
MysqlUtil文件内容:
解释
-
package com.sql;
-
import java.sql.PreparedStatement;
-
import java.sql.ResultSet;
-
import java.sql.SQLException;
-
import java.sql.Statement;
-
import java.util.ArrayList;
-
public class MysqlUtil {
-
public static int add(String sql) {
-
int i=0;
-
DBConnection db = new DBConnection();
-
try {
-
PreparedStatement preStmt = (PreparedStatement) db.conn.prepareStatement(sql);
-
preStmt.executeUpdate();
-
preStmt.close();
-
db.close();
-
i = 1;
-
System.out.println("sql = " + sql);
-
} catch (Exception e) {
-
e.printStackTrace();
-
}
-
return i;
-
}
-
public static int update(String sql) {
-
int i =0;
-
DBConnection db = new DBConnection();
-
try {
-
PreparedStatement preStmt = (PreparedStatement) db.conn.prepareStatement(sql);
-
preStmt.executeUpdate();
-
preStmt.close();
-
db.close();
-
i = 1;
-
System.out.println("sql = " + sql);
-
} catch (SQLException e) {
-
e.printStackTrace();
-
}
-
return i;
-
}
-
public static int del(String delstr) {
-
int i=0;
-
DBConnection db = new DBConnection();
-
try {
-
PreparedStatement preStmt = (PreparedStatement) db.conn.prepareStatement(delstr);
-
preStmt.executeUpdate();
-
preStmt.close();
-
db.close();
-
i = 1;
-
System.out.println("sql = " + delstr);
-
} catch (SQLException e){
-
e.printStackTrace();
-
}
-
return i;
-
}
-
public static int getCount(String sql) {
-
int sum = 0;
-
DBConnection db = new DBConnection();
-
try {
-
Statement stmt = (Statement) db.conn.createStatement();
-
ResultSet rs = (ResultSet) stmt.executeQuery(sql);
-
while (rs.next()) {
-
sum += rs.getInt(1);
-
}
-
rs.close();
-
db.close();
-
} catch (Exception e) {
-
}
-
return sum;
-
}
-
public static String getJsonBySqlDataGrid( String sqlcount,String sql,String[] colums){
-
int count = getCount(sqlcount);
-
System.err.println("sql=" + sql);
-
ArrayList<String[]> result = new ArrayList<String[]>();
-
DBConnection db = new DBConnection();
-
try {
-
Statement stmt = (Statement) db.conn.createStatement();
-
ResultSet rs = (ResultSet) stmt.executeQuery(sql);
-
while(rs.next()){
-
String[] dataRow = new String[colums.length];
-
for( int i = 0; i < dataRow.length; i++ ) {
-
dataRow[i] = rs.getString( colums[i] );
-
}
-
result.add(dataRow);
-
}
-
rs.close();
-
db.close();//
-
} catch (SQLException e) {
-
e.printStackTrace();
-
}
-
return listToJsonDataGrid(result,colums,count);
-
}
-
public static String getJsonBySql( String sql,String[] colums){
-
System.err.println("sql=" + sql);
-
ArrayList<String[]> result = new ArrayList<String[]>();
-
DBConnection db = new DBConnection();
-
try {
-
Statement stmt = (Statement) db.conn.createStatement();
-
ResultSet rs = (ResultSet) stmt.executeQuery(sql);
-
while(rs.next()){
-
String[] dataRow = new String[colums.length];
-
for( int i = 0; i < dataRow.length; i++ ) {
-
dataRow[i] = rs.getString( colums[i] );
-
}
-
result.add(dataRow);
-
}
-
rs.close();
-
db.close();//
-
} catch (SQLException e) {
-
e.printStackTrace();
-
}
-
return listToJson(result,colums);
-
}
-
public static ArrayList<String[]> showUtil( String sql, String[] colums){
-
ArrayList<String[]> result = new ArrayList<String[]>();
-
DBConnection db = new DBConnection();
-
try {
-
Statement stmt = (Statement) db.conn.createStatement();
-
ResultSet rs = (ResultSet) stmt.executeQuery(sql);
-
while(rs.next()){
-
String[] dataRow = new String[colums.length];
-
for( int i = 0; i < dataRow.length; i++ ) {
-
dataRow[i] = rs.getString( colums[i] );
-
}
-
result.add(dataRow);
-
}
-
rs.close();
-
db.close();//
-
} catch (SQLException e) {
-
e.printStackTrace();
-
}
-
return result;
-
}
-
public static String listToJsonDataGrid( ArrayList<String[]> list,String[] colums,int count) {
-
String jsonStr = "{\"code\":0,\"msg\":\"success\",\"count\":"+count+",\"data\":[";
-
for(int i = 0; i < list.size(); i++) {
-
String arr = "{";
-
for( int j = 0; j < list.get(0).length; j++) {
-
if( list.get(i)[j] == null || "NULL".equals(list.get(i)[j])) {
-
arr += "\"" + colums[j] + "\":\"\"";
-
}else {
-
arr += "\"" + colums[j] + "\""+":" ;
-
arr += "\"" + list.get(i)[j].replace("\"","\\\"") + "\"";
-
}
-
if( j < list.get(0).length - 1 ) {
-
arr += ",";
-
}
-
}
-
arr += "}";
-
if( i < list.size() - 1 ) {
-
arr += ",";
-
}
-
jsonStr += arr;
-
}
-
jsonStr += "]}";
-
return jsonStr;
-
}
-
public static String listToJson( ArrayList<String[]> list,String[] colums) {
-
String jsonStr = "{\"code\":0,\"msg\":\"success\",\"data\":[";
-
for(int i = 0; i < list.size(); i++) {
-
String arr = "{";
-
for( int j = 0; j < list.get(0).length; j++) {
-
if( list.get(i)[j] == null || "NULL".equals(list.get(i)[j])) {
-
arr += "\"" + colums[j] + "\":\"\"";
-
}else {
-
arr += "\"" + colums[j] + "\""+":" ;
-
arr += "\"" + list.get(i)[j].replace("\"","\\\"") + "\"";
-
}
-
if( j < list.get(0).length - 1 ) {
-
arr += ",";
-
}
-
}
-
arr += "}";
-
if( i < list.size() - 1 ) {
-
arr += ",";
-
}
-
jsonStr += arr;
-
}
-
jsonStr += "]}";
-
return jsonStr;
-
}
-
}
然后再HTML文件里写入
解释
-
<!DOCTYPE html>
-
<html>
-
<head>
-
<meta charset="UTF-8">
-
<title>Insert title here</title>
-
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"> </script>
-
</head>
-
<!-- onload刷新页面就会触发该方法 -->
-
<body onload="get()">
-
<div id = "hhh"></div>
-
</body>
-
<script>
-
function get(){
-
$.ajax({
-
type:"get",
-
url:"/BigData02/UserServlet",
-
success:function(data){
-
console.log(data);
-
showData(data.data)
-
}
-
})
-
}
-
function showData(data){
-
var html = '<table border="1">';
-
for(var i = 0; i < data.length; i++){
-
html += '<tr>';
-
html += '<td>' + data[i].id + '</td>';
-
html += '<td>' + data[i].username + '</td>';
-
html += '<td>' + data[i].password + '</td>';
-
html += '<td>';
-
html += '<input type="button" value="编辑" />';
-
html += '<input type="button" value="删除" />';
-
html += '</td>';
-
html += '</tr>';
-
}
-
html += '</table>';
-
$("#hhh").empty().append(html);
-
}
-
</script>
-
</html>
包含了一个使用jQuery进行AJAX请求并展示用户数据的功能。页面加载完成后会调用 get()
方法,该方法通过AJAX请求从服务器获取数据,并在成功后调用 showData()
方法展示数据。
在展示数据的部分,会将获取到的数据以表格的形式展示在页面上,每一行代表一个用户的信息,包括用户ID、用户名和密码,并且每行最后有一个"编辑"和"删除"按钮。
请注意,为了使这段代码正常工作,需要确保 /BigData02/UserServlet
能够正确处理 GET 请求并返回符合预期格式的用户数据
sql数据库文件内容:
更改sevtel文件;
解释
-
package com.bigdata;
-
import java.io.IOException;
-
import javax.servlet.ServletException;
-
import javax.servlet.annotation.WebServlet;
-
import javax.servlet.http.HttpServlet;
-
import javax.servlet.http.HttpServletRequest;
-
import javax.servlet.http.HttpServletResponse;
-
import com.sql.MysqlUtil;
-
/**
-
* Servlet implementation class UserServlet
-
*/
-
@WebServlet("/UserServlet")
-
public class UserServlet extends HttpServlet {
-
private static final long serialVersionUID = 1L;
-
/**
-
* @see HttpServlet#HttpServlet()
-
*/
-
public UserServlet() {
-
super();
-
// TODO Auto-generated constructor stub
-
}
-
/**
-
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
-
*/
-
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
-
String sql = "select * from user";
-
String[] colums = {"id","username","password"};
-
String data = MysqlUtil.getJsonBySql(sql, colums);
-
System.out.println(data);
-
response.setCharacterEncoding("utf-8");
-
response.setContentType("application/json; charset=utf-8");
-
response.getWriter().append(data);
-
}
-
/**
-
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
-
*/
-
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
-
// TODO Auto-generated method stub
-
doGet(request, response);
-
}
-
}
这段代码是一个简单的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来获取用户信息并展示在页面上。
结果为:文章来源:https://www.toymoban.com/news/detail-848660.html
文章来源地址https://www.toymoban.com/news/detail-848660.html
到了这里,关于eclipse之MySQL数据库与Web前段存储交互的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!