写出根据学号,姓名使用vue实现按钮查询功能的前端代码,需要联动后端数据库,并且使用java语言写出后端代码
时间: 2024-02-09 07:12:17 浏览: 77
基于Vue框架的Java后端与多语言前端的小学期项目设计源码
前端代码:
```html
<template>
<div>
<label>
学号:
<input type="text" v-model="id" />
</label>
<label>
姓名:
<input type="text" v-model="name" />
</label>
<button @click="search">查询</button>
<div v-if="result">{{ result }}</div>
</div>
</template>
<script>
export default {
data() {
return {
id: '',
name: '',
result: '',
};
},
methods: {
search() {
// 根据学号和姓名查询后端接口
fetch(`/api/search?id=${this.id}&name=${this.name}`)
.then((res) => res.json())
.then((data) => {
this.result = data.result;
});
},
},
};
</script>
```
后端代码:
```java
import java.sql.*;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
public class Server {
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC";
private static final String JDBC_USERNAME = "root";
private static final String JDBC_PASSWORD = "root";
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/api/search", new SearchHandler());
server.setExecutor(null);
server.start();
}
static class SearchHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
String query = exchange.getRequestURI().getQuery();
String[] params = query.split("&");
String id = null;
String name = null;
for (String param : params) {
String[] pair = param.split("=");
if (pair[0].equals("id")) {
id = pair[1];
} else if (pair[0].equals("name")) {
name = pair[1];
}
}
String result = null;
try (Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD)) {
String sql = "SELECT * FROM students WHERE id=? AND name=?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, id);
stmt.setString(2, name);
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
result = "查询成功";
} else {
result = "查询失败";
}
}
}
} catch (SQLException e) {
e.printStackTrace();
result = "查询出错";
}
String response = "{\"result\": \"" + result + "\"}";
exchange.sendResponseHeaders(200, response.length());
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}
```
需要注意的是,这里使用了MySQL数据库,需要提前安装MySQL并创建名为`test`的数据库,以及名为`students`的表并插入一些数据。如果使用其他类型的数据库,需要根据实际情况修改JDBC连接URL和用户名密码等参数。
阅读全文