第二次作业

发布时间 2023-12-03 00:11:11作者: 帅气不拿拿

一、实验目的

       1.掌握软件开发的基本流程

       2.掌握常用的软件开发方式和工具。

二、实验内容

        设计一个包含登录界面的计算器软件,该软件可以实现第一次作业中的全部功能,同时使用数据库可以保存用户的历史计算记录和时间。

三、流程图

 

(一)实现思路

总体上采用MVC架构。登录页面login.jsp,输入用户名和密码后,跳转到登录处理程序LoginServlet进行业务逻辑处理,调用服务层,服务层调用数据访问层(DAO),连接数据库,查询数据库,以此判断是否登录成功。登录成功,跳转到登录成功页面success.jsp,否则跳转到登录失败页面failure.jsp。

(二)代码实现

1.创建登录页面

登录页面 - login.jsp
原代码

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>用户登录</title>
</head>
<body>
<h3 style="text-align: center">用户登录</h3>
<form action="doLogin.jsp" method="post">
    <table border="1" cellpadding="10" style="margin: 0px auto">
        <tr>
            <td align="center">账号</td>
            <td><input type="text" name="username"/></td>
        </tr>
        <tr>
            <td align="center">密码</td>
            <td><input type="password" name="password"/></td>
        </tr>
        <tr align="center">
            <td colspan="2">
                <input type="submit" value="登录"/>
                <input type="reset" value="重置"/>
            </td>
        </tr>
    </table>
</form>
</body>
</html>

2.创建登录处理页面

登录处理页面 - doLogin.jsp
原代码

<%
    // 获取登录表单数据
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    // 判断登录是否成功
    if (username.equals("易烊千玺") && password.equals("123456")) {
        // 跳转到登录成功页面,传递用户名
        response.sendRedirect("success.jsp?username=" + username);
    } else {
        // 跳转到登录失败页面,传递用户名
        response.sendRedirect("failure.jsp?username=" + username);
    }
%>

3.创建登录成功页面

登录成功页面 - success.jsp
原代码

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录成功</title>
</head>
<body>
<h3 style="text-align: center">恭喜,<%=request.getParameter("username")%>,登录成功!</h3>
</body>
</html>

4.创建登录失败页面

登录失败页面 - failure.jsp
原代码

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录失败</title>
</head>
<body>
<h3 style="text-align: center">遗憾,<%=request.getParameter("username")%>,登录失败!</h3>
</body>
</html>

5. 编辑项目首页

项目首页 - index.jsp
原代码

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>首页</title>
  </head>
  <body>
    <h1 style="color: red; text-align: center">纯JSP方式实现用户登录成功能</h1>
    <h3 style="text-align: center">跳转到登录页面</h3>
  </body>
</html>

 

6.测试结果展现

用户登录页面

输入正确的用户名和密码(臭嘟嘟,123456)

登录成功界

 

如果用户名或密码错误,登录失败

 

(二)计算器代码

package cn.lidan.start;

import cn.lidan.util.Const;
import jdk.nashorn.internal.objects.NativeString;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Carculator extends JFrame implements ActionListener {
    //北面控件
    private JPanel jp_north = new JPanel();
    private JTextField input_text = new JTextField();
    private JButton c_Btu = new JButton("C");

    //中间的控件
    private JPanel jp_center = new JPanel();
    private NativeString btn_text;

    public Carculator() throws HeadlessException {
       this.init();
       this.addNorthComponent();
       this.addCenterButton();
    }


    //初始化的方法
    public void init(){
        this.setTitle(Const.TITLE);
        this.setSize(Const.FRAME_W,Const.FRAME_H);
        this.setLayout(new BorderLayout());

        this.setLocation(Const.FRAME_X,Const.FRAME_Y);//窗口固定到中心点位置
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    //添加北面的控件
    public void addNorthComponent(){
        this.input_text.setPreferredSize(new Dimension(230,30));
        jp_north.add(input_text);

        this.c_Btu.setForeground(Color.red);
        jp_north.add(c_Btu);

        c_Btu.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                input_text.setText("");
            }
        });
        this.add(jp_north,BorderLayout.NORTH);
    }

    //添加中间按钮
    public void addCenterButton(){
        String btn_text = "123+456-789*.0=/C√()";//按键内容
        String regex = "[\\+\\-*/.=C√()]";
        this.jp_center.setLayout(new GridLayout(5,4));//中间键的个数
        for(int i=0;i<20;i++){
            String temp = btn_text.substring(i,i+1);
            JButton btn = new JButton();
            btn.setText(temp);
            if(temp.matches(regex)){
              btn.setFont(new Font("粗体",Font.BOLD, 20));
                btn.setForeground(Color.red);
            }
            btn.addActionListener(this);
            jp_center.add(btn);
        }
        this.add(jp_center,BorderLayout.CENTER);
    }

    public static  void main(String[] args) {
        Carculator carculator = new Carculator();
        carculator.setVisible(true);
    }

    private  String firstInput = null;
    private String operator = null;
    @Override
    public void actionPerformed(ActionEvent e) {
        String clickStr = e.getActionCommand();
        if(".0123456789".indexOf(clickStr) != -1) {
            this.input_text.setText(input_text.getText() + clickStr);
            this.input_text.setHorizontalAlignment(JTextField.RIGHT);
           // JOptionPane.showMessageDialog(this, clickStr);
        }else if(clickStr.matches("[\\+\\-*/]{1}")){
            operator = clickStr;
            firstInput =this.input_text.getText();
            this.input_text.setText("");
        }else if(clickStr.equals("=")){
            Double a = Double.valueOf(firstInput);
            Double b = Double.valueOf(this.input_text.getText());
            Double result = null;
            switch (operator){
                case "+":
                    result = a+b;
                    break;
                case "-":
                    result = a-b;
                    break;
                case "*":
                    result = a*b;
                    break;
                case "/":
                    if(b!=0){
                        result =a/b;
                    }
                    break;
              case "C":
                    input_text.setText(" ");
                    break;
            }
            this.input_text.setText(result.toString());
        }

    }
}

 登录进去计算机界面

 (四)数据库连接

1.创建数据库

2.创建用户表

3.创建用户实体类

package net.xyx.bean;

import java.util.Date;

/**
 * 功能:用户实体类
 * 作者:xyx
 * 日期:2023年12月1日
 */
public class User {
    private int id;
    private String username;
    private String password;
    private String telephone;
    private Date registerTime;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getTelephone() {
        return telephone;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    public Date getRegisterTime() {
        return registerTime;
    }

    public void setRegisterTime(Date registerTime) {
        this.registerTime = registerTime;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", telephone='" + telephone + '\'' +
                ", registerTime=" + registerTime +
                '}';
    }
}

4.创建数据库连接管理工具类

package net.xyx.dbutils;

import javax.swing.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 功能:数据库连接管理类
 * 作者:xyx
 * 日期:2023年12月1日
 */
public class ConnectionManager {
    private static final String DRIVER = "com.mysql.jdbc.Driver"; // 数据库驱动程序
    private static final String URL = "jdbc:mysql://localhost:3306/student/test?useSSL=false"; // 数据库统一资源标识符
    private static final String USER = "root"; // 数据库用户
    private static final String PASSWORD = "1"; // 数据库密码

    //私有化构造方法,拒绝实例化
    private ConnectionManager() {
    }

    /**
     * 获取数据库连接静态方法
     *
     * @return 数据库连接对象
     */
    public static Connection getConnection() {
        // 定义数据库连接
        Connection conn = null;

        try {
            // 安装数据库驱动程序
            Class.forName(DRIVER);
            // 获取数据库连接
            conn = DriverManager.getConnection(URL, USER, PASSWORD);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        // 返回数据库连接
        return conn;
    }

    /**
     * 关闭数据连接静态方法
     *
     * @param conn
     */
    public static void closeConnection(Connection conn) {
        // 判断数据库连接是否非空
        if (conn != null) {
            try {
                // 判断连接是否未关闭
                if (!conn.isClosed()) {
                    // 关闭数据库连接
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 主方法:测试两个静态方法
     *
     * @param args
     */
    public static void main(String[] args) {
        // 获取数据库连接
        Connection conn = getConnection();
        // 判断数据库连接是否成功
        if (conn != null) {
            JOptionPane.showMessageDialog(null, "恭喜,数据库连接成功!");
        } else {
            JOptionPane.showMessageDialog(null, "遗憾,数据库连接失败!");
        }
        // 关闭数据库连接
        closeConnection(conn);
    }
}

5.创建用户数据访问类

package net.xyx.dao;

import net.huawei.bean.User;
import net.huawei.dbutils.ConnectionManager;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 功能:用户数据访问类
 * 作者:xyx
 * 日期:2023年12月1日
 */
public class UserDao {
    /**
     * 用户登录方法
     * @param username
     * @param password
     * @return 用户对象(非空:登录成功,否则登录失败)
     */
    public User login(String username, String password) {
        // 声明用户对象
        User user = null;

        // 获取数据库连接
        Connection conn = ConnectionManager.getConnection();
        try {
            // 定义SQL字符串
            String strSQL = "SELECT * FROM t_user WHERE username = ? AND password = ?";
            // 创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            // 设置占位符
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            // 执行查询,返回结果集
            ResultSet rs = pstmt.executeQuery();
            // 判断结果集是否为空
            if (rs.next()) {
                // 创建用户对象
                user = new User();
                // 利用当前记录字段值来设置用户对象属性
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setTelephone(rs.getString("telephone"));
                user.setRegisterTime(rs.getTimestamp("register_time"));
            }
        } catch (SQLException e) {
            System.err.println(e.getMessage());
        } finally {
            // 关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }

        // 返回用户对象
        return user;
    }
}

6.测试用户数据访问类

package net.xyx.test;

import net.xyx.bean.User;
import net.xyx.dao.UserDao;
import org.junit.Test;

/**
 * 功能:测试用户数据访问类
 * 作者:xyx
 * 日期:2023年05月19日
 */
public class TestUserDao {
    @Test
    public void testLogin() {
        String username = "臭嘟嘟";
        String password = "12345";

        // 创建用户数据访问对象
        UserDao userDao = new UserDao();
        // 调用登录方法,返回用户对象
        User user = userDao.login(username, password);
        // 判断用户登录是否成功
        if (user != null) { // 成功
            System.out.println("恭喜,用户[" + username + "]登录成功~");
        } else { // 失败
            System.out.println("遗憾,用户[" + username + "]登录失败~");
        }
    }
}