一:简单的写一个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
);