第二次作业
[实验目的]
1.掌握软件开发的基本流程
2.掌握常用的软件开发方式和工具。
[实验内容]
1.设计一个包含登录界面的计算器软件,该软件可以实现第一次作业中的全部功能,同时可以保存用户的历史计算记录(保存数据最好使用数据库)。
[实验工具]
1.用eclipse写登录界面和计算器。
2.用Mysql存储数据
3.用jdbc连接数据库。
4.用Visio绘制流程图。
【流程图设计】
1.登录界面
2.计算器流程图
【登录界面】
账号或密码输入错误时,点击重置键,则清除账号密码
【计算器页面】
【基本代码】
1. LoginServlet.java
package recordCalculator_Login;
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 javax.servlet.http.HttpSession;
/**
* 创建一个servlet(处理登录请求)
*/
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* 前端传参数到doPost
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 设置请求和响应的字符编码为 UTF-8
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
// 获取用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
// 进行登录逻辑的处理,比如验证用户名密码是否正确
System.out.println("username: " + username + ", password: " + password);
// 存储用户名到会话中
HttpSession session = request.getSession();
session.setAttribute("username", username);
// 假设验证通过,可以进行跳转或返回其他页面
response.sendRedirect(request.getContextPath() + "/calculator.jsp");
}
}
2.CalculateSaveServlet.java
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<!DOCTYPE html>
<html lang="ch-ZN">
<head>
<meta charset="UTF-8">
<title>计算器</title>
<style>
* {
margin: 0;
padding: 0;
}
.button {
width: 50px;
height: 50px;
font-size: 25px;
margin: 2px;
cursor: pointer;
background: #607d8b;
border: none;
color: white;
}
.button1 {
width: 221px;
height: 50px;
font-size: 25px;
margin: 2px;
cursor: pointer;
background: #607d8b;
border: none;
color: white;
}
.textView {
width: 200px;
margin: 5px;
font-size: 23px;
padding: 5px;
border: thick double #32a1ce;;
}
.main {
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
html {
background: linear-gradient(to right, #00f7ff, #d0cd77);
height: 100%;
}
</style>
<script>
var userOperations = []; // 用于存储用户的操作记录
let a="1343.43245";
let b=a.indexOf(".");
console.log(b);
let c=a.substring(0,b+3);
console.log(c);
function insert(num) {
document.form.textView.value = document.form.textView.value + num;
recordOperation("insert", num);
}
function equal() {
// TODO 计算结果,并且结果保留两位小数
let exp = document.form.textView.value;
if (exp) {
let eval1 = eval(document.form.textView.value);
// eval() 执行括号内的语句 , 记录结果
let number = eval1.toString().indexOf(".");
if (number!==-1){
// 如果是小数,保留两位小数
eval1=eval1.toString().substring(0,number+3);
// 截取
document.form.textView.value=eval1;
// 记录操作
recordOperation("equal", eval1);
// 发起后端请求
sendDataToBackend();
}else {
// 如果不是小数,直接赋值
document.form.textView.value=eval1;
// 记录操作
recordOperation("equal", eval1);
// 发起后端请求
sendDataToBackend();
}
}
}
function recordOperation(operation, data) {
// 记录操作到数组中
userOperations.push({ 操作: operation, 值: data });
}
function sendDataToBackend() {
// 创建 XMLHttpRequest 对象
var xhr = new XMLHttpRequest();
// 配置请求
xhr.open("POST", "/recordCalculator_Login/calculateSave", true);
xhr.setRequestHeader("Content-Type", "application/json");
// 处理响应
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
// 请求成功,可以在这里处理后端返回的数据
console.log("Data sent to backend successfully");
} else {
// 请求失败,可以在这里处理错误信息
console.error("Error sending data to backend");
}
}
};
// 发送数据,将操作记录作为 JSON 字符串发送
xhr.send("记录:" + JSON.stringify(userOperations));
// 清空操作记录数组
userOperations = [];
}
function Mclean() {
// TODO 清理输入框的文字
document.form.textView.value = null;
}
function back() {
// TODO 删除文本框的一个字符
let exp = document.form.textView.value;
document.form.textView.value = exp.substring(0, exp.length - 1);
// 截取字符串
}
function sqrt() {
let num = parseFloat(document.form.textView.value);
if (num < 0) {
document.form.textView.value='false';
return;
}
var guess = num / 2; // 初始猜测值为 num / 2
var epsilon = 0.00001; // 定义精度值
var previousGuess; // 用于存储上一次的猜测值
do {
previousGuess = guess; // 保存当前猜测值以便下一次迭代使用
guess = (guess + num / guess) / 2; // 牛顿迭代法更新猜测值
} while (Math.abs(guess - previousGuess) > epsilon); // 当两次猜测值之差小于精度值时停止迭代
document.form.textView.value=guess;
}
</script>
</head>
<body>
<div class="main">
<form name="form">
<input class="textView" name="textView">
</form>
<table>
<tr>
<td><input type="button" class="button" value="C"
onclick="Mclean()"></td>
<td><input type="button" class="button" value="<" onclick="back()"></td>
<td><input type="button" class="button" value="/"
onclick="insert('/')"></td>
<td><input type="button" class="button" value="x"
onclick="insert('*')"></td>
</tr>
<tr>
<td><input type="button" class="button" value="7"
onclick="insert(7)"></td>
<td><input type="button" class="button" value="8"
onclick="insert(8)"></td>
<td><input type="button" class="button" value="9"
onclick="insert(9)"></td>
<td><input type="button" class="button" value="-"
onclick="insert('-')"></td>
</tr>
<tr>
<td><input type="button" class="button" value="4"
onclick="insert(4)"></td>
<td><input type="button" class="button" value="5"
onclick="insert(5)"></td>
<td><input type="button" class="button" value="6"
onclick="insert(6)"></td>
<td><input type="button" class="button" value="+"
onclick="insert('+')"></td>
</tr>
<tr>
<td><input type="button" class="button" value="1"
onclick="insert(1)"></td>
<td><input type="button" class="button" value="2"
onclick="insert(2)"></td>
<td><input type="button" class="button" value="3"
onclick="insert(3)"></td>
<td rowspan="2"><input style="height: 107px" type="button"
class="button" value="=" onclick="equal()"></td>
</tr>
<tr>
<td colspan="2"><input style="width: 107px" type="button"
class="button" value="0" onclick="insert(0)"></td>
<td><input type="button" class="button" value="."
onclick="insert('.')"></td>
</tr>
</table>
<tr>
<td><input class="button1" value=" 开方计算"
onclick="sqrt()"></td>
</tr>
</div>
</body>
</html>
3.index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator Login</title>
<style>
body {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
}
form {
text-align: center;
}
label {
display: block;
margin-bottom: 10px;
}
input {
padding: 8px;
margin-bottom: 15px;
}
input[type="submit"] {
background-color: #4CAF50;
color: white;
cursor: pointer;
}
</style>
</head>
<body>
<div>
<h1>欢迎使用web计算器,请登录</h1>
<form action="/recordCalculator_Login/login" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<br>
<br>
<input type="reset" value="重置键" >
<input type="submit" value="Login">
</form>
</div>
</body>
</html>
4.calculator.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<!DOCTYPE html>
<html lang="ch-ZN">
<head>
<meta charset="UTF-8">
<title>计算器</title>
<style>
* {
margin: 0;
padding: 0;
}
.button {
width: 50px;
height: 50px;
font-size: 25px;
margin: 2px;
cursor: pointer;
background: #607d8b;
border: none;
color: white;
}
.button1 {
width: 221px;
height: 50px;
font-size: 25px;
margin: 2px;
cursor: pointer;
background: #607d8b;
border: none;
color: white;
}
.textView {
width: 200px;
margin: 5px;
font-size: 23px;
padding: 5px;
border: thick double #32a1ce;;
}
.main {
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
html {
background: linear-gradient(to right, #00f7ff, #d0cd77);
height: 100%;
}
</style>
<script>
var userOperations = []; // 用于存储用户的操作记录
let a="1343.43245";
let b=a.indexOf(".");
console.log(b);
let c=a.substring(0,b+3);
console.log(c);
function insert(num) {
document.form.textView.value = document.form.textView.value + num;
recordOperation("insert", num);
}
function equal() {
// TODO 计算结果,并且结果保留两位小数
let exp = document.form.textView.value;
if (exp) {
let eval1 = eval(document.form.textView.value);
// eval() 执行括号内的语句 , 记录结果
let number = eval1.toString().indexOf(".");
if (number!==-1){
// 如果是小数,保留两位小数
eval1=eval1.toString().substring(0,number+3);
// 截取
document.form.textView.value=eval1;
// 记录操作
recordOperation("equal", eval1);
// 发起后端请求
sendDataToBackend();
}else {
// 如果不是小数,直接赋值
document.form.textView.value=eval1;
// 记录操作
recordOperation("equal", eval1);
// 发起后端请求
sendDataToBackend();
}
}
}
function recordOperation(operation, data) {
// 记录操作到数组中
userOperations.push({ 操作: operation, 值: data });
}
function sendDataToBackend() {
// 创建 XMLHttpRequest 对象
var xhr = new XMLHttpRequest();
// 配置请求
xhr.open("POST", "/recordCalculator_Login/calculateSave", true);
xhr.setRequestHeader("Content-Type", "application/json");
// 处理响应
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
// 请求成功,可以在这里处理后端返回的数据
console.log("Data sent to backend successfully");
} else {
// 请求失败,可以在这里处理错误信息
console.error("Error sending data to backend");
}
}
};
// 发送数据,将操作记录作为 JSON 字符串发送
xhr.send("记录:" + JSON.stringify(userOperations));
// 清空操作记录数组
userOperations = [];
}
function Mclean() {
// TODO 清理输入框的文字
document.form.textView.value = null;
}
function back() {
// TODO 删除文本框的一个字符
let exp = document.form.textView.value;
document.form.textView.value = exp.substring(0, exp.length - 1);
// 截取字符串
}
function sqrt() {
let num = parseFloat(document.form.textView.value);
if (num < 0) {
document.form.textView.value='false';
return;
}
var guess = num / 2; // 初始猜测值为 num / 2
var epsilon = 0.00001; // 定义精度值
var previousGuess; // 用于存储上一次的猜测值
do {
previousGuess = guess; // 保存当前猜测值以便下一次迭代使用
guess = (guess + num / guess) / 2; // 牛顿迭代法更新猜测值
} while (Math.abs(guess - previousGuess) > epsilon); // 当两次猜测值之差小于精度值时停止迭代
document.form.textView.value=guess;
}
</script>
</head>
<body>
<div class="main">
<form name="form">
<input class="textView" name="textView">
</form>
<table>
<tr>
<td><input type="button" class="button" value="C"
onclick="Mclean()"></td>
<td><input type="button" class="button" value="<" onclick="back()"></td>
<td><input type="button" class="button" value="/"
onclick="insert('/')"></td>
<td><input type="button" class="button" value="x"
onclick="insert('*')"></td>
</tr>
<tr>
<td><input type="button" class="button" value="7"
onclick="insert(7)"></td>
<td><input type="button" class="button" value="8"
onclick="insert(8)"></td>
<td><input type="button" class="button" value="9"
onclick="insert(9)"></td>
<td><input type="button" class="button" value="-"
onclick="insert('-')"></td>
</tr>
<tr>
<td><input type="button" class="button" value="4"
onclick="insert(4)"></td>
<td><input type="button" class="button" value="5"
onclick="insert(5)"></td>
<td><input type="button" class="button" value="6"
onclick="insert(6)"></td>
<td><input type="button" class="button" value="+"
onclick="insert('+')"></td>
</tr>
<tr>
<td><input type="button" class="button" value="1"
onclick="insert(1)"></td>
<td><input type="button" class="button" value="2"
onclick="insert(2)"></td>
<td><input type="button" class="button" value="3"
onclick="insert(3)"></td>
<td rowspan="2"><input style="height: 107px" type="button"
class="button" value="=" onclick="equal()"></td>
</tr>
<tr>
<td colspan="2"><input style="width: 107px" type="button"
class="button" value="0" onclick="insert(0)"></td>
<td><input type="button" class="button" value="."
onclick="insert('.')"></td>
</tr>
</table>
<tr>
<td><input class="button1" value=" 开方计算"
onclick="sqrt()"></td>
</tr>
</div>
</body>
</html>
连接数据库
package recordCalculator_Login;
import java.sql.*;
public class sql{
public static void main(String args[])
{
try
{
Class.forName("com.mysql.jdbc.Driver"); //加载MYSQL JDBC驱动程序
//Class.forName("org.gjt.mm.mysql.Driver");
System.out.println("成功加载Mysql驱动程序!");
}
catch (Exception e)
{
System.out.print("加载Mysql驱动程序时出错!");
e.printStackTrace();
}
try
{
Connection connect = DriverManager.getConnection( "jdbc:mysql://localhost:3306/MySQL5.7","root","zj123456789");
//连接URL为 jdbc:mysql//服务器地址/数据库名 ,后面的2个参数分别是登陆用户名和密码
System.out.println("成功连接Mysql服务器!");
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery("select * from employee where salary>1900"); //student 为你表的名称
while (rs.next())
{
System.out.println(rs.getString("username"));
System.out.println(rs.getString("password"));
}
connect.close();
}
catch (Exception e)
{
System.out.print("获取数据错误!");
e.printStackTrace();
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南