JavaWeb—期末实验——简单的准考证打印。

一:简单的写一个index.jsp表单提交页面

效果如图所示:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
  <title>准考证打印</title>
  <style>
    .container {
      display: flex;
      justify-content: center; /* 水平居中 */
      align-items: center; /* 垂直居中 */
      height: 100vh; /* 设置容器高度为视口高度 */
      margin: 0;
      padding: 20px;
      box-sizing: border-box; /* 确保padding不会增加容器的宽度 */
    }

    .form-wrapper {
      position: relative;
      width: 300px; /* 设置表单宽度 */
      max-width: 100%; /* 确保表单宽度不会超过容器宽度 */
      padding: 20px;
      border: 2px solid #ccc; /* 可选:添加边框以突出显示表单 */
      box-sizing: border-box; /* 确保padding不会增加表单的宽度 */
    }
    #number{
      margin-left: 30px;
    }
    #photo{
      position: absolute;
      left: 94px;
    }
    #d{
      position: absolute;
      left: 94px;
      top: 214px;
    }
  </style>
</head>
<body>
<div class="container">
  <div class="form-wrapper">
    <h2>准考证打印</h2>
    <form action="upload" method="post" enctype="multipart/form-data">
      <label for="name">考生姓名:</label>
      <input type="text" id="name" name="name" required><br><br>
      <label for="number">考号:</label>
      <input type="text" id="number" name="number" required><br><br>
      <label for="photo">考生照片:</label>
      <input type="file" id="photo" name="photo" accept="image/*" required><br><br>
      <input type="submit" id="d" value="上传">
    </form>
  </div>
</div>
</body>
</html>

二:写一个处理表单数据并把数据存入数据库的UploadServlet.java类

这里的数据库用户名和密码要与自己的数据库名和密码对应

package com.xl;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
    private static final String UPLOAD_DIR = "uploads";
    private static final String DB_URL = "jdbc:mysql://localhost:3306/yourdatabase?useSSL=false&serverTimezone=UTC";
    private static final String DB_USER = "root";
    private static final String DB_PASS = "123456";

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String name = request.getParameter("name");
        String number = request.getParameter("number");
        Part filePart = request.getPart("photo");

        String fileName = getFileName(filePart);
        String filePath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIR;
        File uploadDir = new File(filePath);
        if (!uploadDir.exists()) uploadDir.mkdir();

        filePart.write(filePath + File.separator + fileName);
        String photoPath = UPLOAD_DIR + File.separator + fileName;

        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS)) {
            String sql = "INSERT INTO students (name, number, photo) VALUES (?, ?, ?)";
            try (PreparedStatement stmt = conn.prepareStatement(sql)) {
                stmt.setString(1, name);
                stmt.setString(2, number);
                stmt.setString(3, photoPath);
                stmt.executeUpdate();
            }
        } catch (SQLException e) {
            throw new ServletException("Database error", e);
        }

        request.setAttribute("name", name);
        request.setAttribute("number", number);
        request.setAttribute("photoPath", photoPath);
        request.getRequestDispatcher("uploadSuccess.jsp").forward(request, response);
    }

    private String getFileName(Part part) {
        String contentDisposition = part.getHeader("content-disposition");
        for (String content : contentDisposition.split(";")) {
            if (content.trim().startsWith("filename")) {
                return content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }
}

三:写一个文件上传成功的uploadSussess.jsp页面

页面效果如下:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <title>上传成功</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }
        h2 {
            color: green;
        }
        form {
            margin-top: 20px;
        }
        label, input {
            font-size: 1.2em;
        }
    </style>
</head>
<body>
<h2>信息上传成功!</h2>
<h3>用户打印</h3>
<form action="generate" method="post">
    <label for="name">请输入要打印的考生名:</label>
    <input type="text" id="name" name="name" required>
    <br><br>
    <input type="submit" value="打印">
    <input type="reset" value="重置">
</form>
</body>
</html>

四:最后写一个获取数据库数据并把准考证做成pdf的效果

package com.xl;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
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.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.Image;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.Table;
import java.io.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
@WebServlet("/generate")
public class GeneratePDFServlet extends HttpServlet {
    private static final String DB_URL = "jdbc:mysql://localhost:3306/yourdatabase?useSSL=false&serverTimezone=UTC";
    private static final String DB_USER = "root";
    private static final String DB_PASS = "123456";

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String name = request.getParameter("name");

        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS)) {
            String sql = "SELECT name, number, photo FROM students WHERE name = ?";
            try (PreparedStatement stmt = conn.prepareStatement(sql)) {
                stmt.setString(1, name);
                try (ResultSet rs = stmt.executeQuery()) {
                    if (rs.next()) {
                        String studentName = rs.getString("name");
                        String number = rs.getString("number");
                        String photoPath = getServletContext().getRealPath("") + File.separator + rs.getString("photo");

                        Document document = new Document();
                        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                        PdfWriter.getInstance(document, buffer);
                        document.open();

                        // 设置中文字体
                        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

                        // 标题居中
                        Paragraph title = new Paragraph("准考证", new com.lowagie.text.Font(bfChinese, 24));
                        title.setAlignment(Element.ALIGN_CENTER);
                        document.add(title);

                        // 创建表格
                        Table table = new Table(1);
                        table.setAlignment(Table.ALIGN_CENTER); // 设置表格居中
                        table.setBorderWidth(0); // 将边框宽度设为0
                        table.setPadding(3); // 表格边距离为3
                        table.setSpacing(3);

                        // 添加图片并居中
                        Image img = Image.getInstance(photoPath);
                        img.setAlignment(Image.MIDDLE);
                        table.addCell(new com.lowagie.text.Cell(img));

                        // 添加姓名并居中
                        com.lowagie.text.Cell studentNameCell = new com.lowagie.text.Cell(new Paragraph("姓名: " + studentName, new com.lowagie.text.Font(bfChinese, 16)));
                        studentNameCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                        table.addCell(studentNameCell);

                        // 添加考号并居中
                        com.lowagie.text.Cell numberCell = new com.lowagie.text.Cell(new Paragraph("考号: " + number, new com.lowagie.text.Font(bfChinese, 16)));
                        numberCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                        table.addCell(numberCell);

                        document.add(table);
                        document.close();

                        // 输出PDF到客户端
//                        response.reset();
//                        response.setContentType("application/pdf");
//                        response.setHeader("Content-Disposition", "attachment; filename=准考证.pdf");

                        byte[] bytes = buffer.toByteArray();
                        response.setContentLength(bytes.length);
                        OutputStream output = response.getOutputStream();
                        output.write(bytes);
                        output.flush();
                    } else {
                        response.getWriter().println("未找到考生信息。");
                    }
                }
            }
        } catch (SQLException e) {
            throw new ServletException("Database error", e);
        } catch (Exception e) {
            throw new ServletException("PDF生成错误", e);
        }
    }
}

最终效果如下:

五:补充数据库的创建

create database yourdatabase;
use yourdatabase;
CREATE TABLE students (
                          id INT AUTO_INCREMENT PRIMARY KEY,
                          name VARCHAR(255) NOT NULL,
                          number VARCHAR(255) NOT NULL,
                          photo VARCHAR(255) NOT NULL
);

  • 12
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以用 Python 的第三方库 requests 来实现这个功能。具体步骤如下: 1. 安装 requests 库,执行以下命令: ``` pip install requests ``` 2. 在代码中导入 requests 库,并使用其中的 get() 函数调用网站的 API 接口。 ```python import requests def query(admission_no): url = f"https://example.com/api/query?admission_no={admission_no}" response = requests.get(url) return response.json() ``` 3. 调用 query() 函数并传入准考证号,就能得到查询结果。 ```python result = query("123456") print(result) ``` 注意:这仅仅是一个示例代码,实际使用中需要根据具体网站的 API 接口进行调整。 ### 回答2: Python可以根据准考证证号实现查询功能。实现这个功能的方法有很多,下面是一种简单的实现方式: 首先,我们需要有一个包含准考证证号和相关信息的数据库。可以使用Python中的字典或列表来实现简单的数据库。例如,我们可以创建一个包含多个字典的列表,每个字典表示一个学生的信息,其中包括准考证证号、姓名、性别等。 然后,用户输入准考证证号进行查询。通过Python的input()函数获取用户输入的准考证证号。 接下来,我们在数据库中遍历查找与输入的准考证证号匹配的信息。可以使用for循环来遍历数据库列表,并使用if语句判断准考证证号是否匹配。 如果找到了匹配的准考证证号,我们可以输出该学生的相关信息,例如姓名、性别、报考科目等。 如果没有找到匹配的准考证证号,我们可以输出相关的提示信息,例如“未找到该准考证证号的信息”。 最后,我们可以将查询功能封装在一个函数中,以便在需要的时候调用。 这只是一个简单的实现方式,具体的实现方式还可以根据实际情况进行调整和改进。例如,可以将数据库存储在文件或数据库中,以便更方便地读取和操作。另外,还可以添加其他功能,例如根据姓名或其他信息进行查询等。 ### 回答3: Python 可以通过以下代码实现根据准考证证号进行查询功能: ```python # 创建一个空的学生信息字典 student_info = {} # 添加学生信息到字典中(示例) student_info["200001"] = {"name": "张三", "age": 18, "gender": "男", "score": 90} student_info["200002"] = {"name": "李四", "age": 17, "gender": "女", "score": 85} student_info["200003"] = {"name": "王五", "age": 16, "gender": "男", "score": 95} # 定义查询函数 def query_student_info(student_id): if student_id in student_info: return student_info[student_id] else: return None # 输入要查询的准考证证号 input_id = input("请输入要查询的准考证证号:") # 调用查询函数并打印结果 result = query_student_info(input_id) if result: print(f"姓名:{result['name']}") print(f"年龄:{result['age']}") print(f"性别:{result['gender']}") print(f"分数:{result['score']}") else: print("该准考证证号不存在") ``` 以上代码创建了一个学生信息字典 `student_info`,其中以准考证证号作为键,每个学生的信息作为值。然后定义了一个查询函数 `query_student_info`,根据输入的准考证证号返回相应的学生信息。最后,用户输入要查询的准考证证号,调用查询函数并打印结果。如果输入的准考证证号存在于学生信息字典中,就会打印该学生的姓名、年龄、性别和分数;如果不存在,则会打印提示信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值