Java文章案例

wen java案例 3

本文目录导读:

Java文章案例

  1. 后端代码
  2. 前端代码(Java Swing GUI)
  3. 数据库建表SQL
  4. 运行说明
  5. 功能特点

我将为您提供一个完整的Java文章管理系统的案例,包含前后端代码。

这是一个简单的文章管理系统,支持文章的增删改查、分类管理、搜索等功能。

后端代码

实体类 Article.java

package com.example.article.entity;
import java.time.LocalDateTime;
public class Article {
    private Long id;
    private String title;
    private String author;
    private String category;
    private String content;
    private LocalDateTime createTime;
    private LocalDateTime updateTime;
    private int viewCount;
    public Article() {}
    public Article(Long id, String title, String author, String category, 
                  String content, LocalDateTime createTime, LocalDateTime updateTime) {
        this.id = id;
        this.title = title;
        this.author = author;
        this.category = category;
        this.content = content;
        this.createTime = createTime;
        this.updateTime = updateTime;
        this.viewCount = 0;
    }
    // Getter和Setter方法
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    public String getTitle() { return title; }
    public void setTitle(String title) { this.title = title; }
    public String getAuthor() { return author; }
    public void setAuthor(String author) { this.author = author; }
    public String getCategory() { return category; }
    public void setCategory(String category) { this.category = category; }
    public String getContent() { return content; }
    public void setContent(String content) { this.content = content; }
    public LocalDateTime getCreateTime() { return createTime; }
    public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; }
    public LocalDateTime getUpdateTime() { return updateTime; }
    public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; }
    public int getViewCount() { return viewCount; }
    public void setViewCount(int viewCount) { this.viewCount = viewCount; }
    @Override
    public String toString() {
        return "Article{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", author='" + author + '\'' +
                ", category='" + category + '\'' +
                ", createTime=" + createTime +
                ", viewCount=" + viewCount +
                '}';
    }
}

数据库工具类 DBUtil.java

package com.example.article.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBUtil {
    private static final String URL = "jdbc:mysql://localhost:3306/article_db?useSSL=false&serverTimezone=UTC";
    private static final String USER = "root";
    private static final String PASSWORD = "123456";
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL, USER, PASSWORD);
    }
    public static void close(AutoCloseable... resources) {
        for (AutoCloseable resource : resources) {
            if (resource != null) {
                try {
                    resource.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

数据访问对象 ArticleDAO.java

package com.example.article.dao;
import com.example.article.entity.Article;
import com.example.article.util.DBUtil;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class ArticleDAO {
    // 添加文章
    public boolean addArticle(Article article) {
        String sql = "INSERT INTO articles (title, author, category, content, create_time, update_time) VALUES (?, ?, ?, ?, ?, ?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, article.getTitle());
            ps.setString(2, article.getAuthor());
            ps.setString(3, article.getCategory());
            ps.setString(4, article.getContent());
            ps.setTimestamp(5, Timestamp.valueOf(article.getCreateTime()));
            ps.setTimestamp(6, Timestamp.valueOf(article.getUpdateTime()));
            return ps.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }
    // 删除文章
    public boolean deleteArticle(Long id) {
        String sql = "DELETE FROM articles WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setLong(1, id);
            return ps.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }
    // 更新文章
    public boolean updateArticle(Article article) {
        String sql = "UPDATE articles SET title = ?, author = ?, category = ?, content = ?, update_time = ? WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, article.getTitle());
            ps.setString(2, article.getAuthor());
            ps.setString(3, article.getCategory());
            ps.setString(4, article.getContent());
            ps.setTimestamp(5, Timestamp.valueOf(article.getUpdateTime()));
            ps.setLong(6, article.getId());
            return ps.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }
    // 根据ID查找文章
    public Article getArticleById(Long id) {
        String sql = "SELECT * FROM articles WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setLong(1, id);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                return mapRowToArticle(rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    // 获取所有文章
    public List<Article> getAllArticles() {
        List<Article> articles = new ArrayList<>();
        String sql = "SELECT * FROM articles ORDER BY create_time DESC";
        try (Connection conn = DBUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                articles.add(mapRowToArticle(rs));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return articles;
    }
    // 搜索文章
    public List<Article> searchArticles(String keyword) {
        List<Article> articles = new ArrayList<>();
        String sql = "SELECT * FROM articles WHERE title LIKE ? OR author LIKE ? OR category LIKE ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            String searchPattern = "%" + keyword + "%";
            ps.setString(1, searchPattern);
            ps.setString(2, searchPattern);
            ps.setString(3, searchPattern);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                articles.add(mapRowToArticle(rs));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return articles;
    }
    // 增加浏览量
    public void incrementViewCount(Long id) {
        String sql = "UPDATE articles SET view_count = view_count + 1 WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setLong(1, id);
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    // ResultSet映射到Article对象
    private Article mapRowToArticle(ResultSet rs) throws SQLException {
        Article article = new Article();
        article.setId(rs.getLong("id"));
        article.setTitle(rs.getString("title"));
        article.setAuthor(rs.getString("author"));
        article.setCategory(rs.getString("category"));
        article.setContent(rs.getString("content"));
        article.setCreateTime(rs.getTimestamp("create_time").toLocalDateTime());
        article.setUpdateTime(rs.getTimestamp("update_time").toLocalDateTime());
        article.setViewCount(rs.getInt("view_count"));
        return article;
    }
}

服务层 ArticleService.java

package com.example.article.service;
import com.example.article.dao.ArticleDAO;
import com.example.article.entity.Article;
import java.time.LocalDateTime;
import java.util.List;
public class ArticleService {
    private ArticleDAO articleDAO = new ArticleDAO();
    // 创建文章
    public boolean createArticle(String title, String author, String category, String content) {
        if (title == null || title.trim().isEmpty()) {
            return false;
        }
        Article article = new Article();
        article.setTitle(title.trim());
        article.setAuthor(author);
        article.setCategory(category);
        article.setContent(content);
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        return articleDAO.addArticle(article);
    }
    // 更新文章
    public boolean updateArticle(Long id, String title, String author, String category, String content) {
        Article article = articleDAO.getArticleById(id);
        if (article == null) {
            return false;
        }
        article.setTitle(title);
        article.setAuthor(author);
        article.setCategory(category);
        article.setContent(content);
        article.setUpdateTime(LocalDateTime.now());
        return articleDAO.updateArticle(article);
    }
    // 删除文章
    public boolean deleteArticle(Long id) {
        return articleDAO.deleteArticle(id);
    }
    // 获取文章
    public Article getArticle(Long id) {
        articleDAO.incrementViewCount(id);
        return articleDAO.getArticleById(id);
    }
    // 获取所有文章
    public List<Article> getAllArticles() {
        return articleDAO.getAllArticles();
    }
    // 搜索文章
    public List<Article> searchArticles(String keyword) {
        return articleDAO.searchArticles(keyword);
    }
    // 获取热门文章(按浏览量排序)
    public List<Article> getHotArticles(int limit) {
        List<Article> allArticles = articleDAO.getAllArticles();
        allArticles.sort((a1, a2) -> a2.getViewCount() - a1.getViewCount());
        return allArticles.stream().limit(limit).toList();
    }
}

前端代码(Java Swing GUI)

ArticleApp.java

package com.example.article.gui;
import com.example.article.entity.Article;
import com.example.article.service.ArticleService;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.List;
public class ArticleApp extends JFrame {
    private ArticleService articleService = new ArticleService();
    private JTable articleTable;
    private DefaultTableModel tableModel;
    private JTextField searchField;
    private JTextArea contentArea;
    public ArticleApp() {
        initUI();
        loadArticles();
    }
    private void initUI() {
        setTitle("文章管理系统");
        setSize(900, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        // 顶部工具栏
        JPanel toolbarPanel = new JPanel(new BorderLayout());
        // 搜索面板
        JPanel searchPanel = new JPanel();
        searchPanel.add(new JLabel("搜索: "));
        searchField = new JTextField(20);
        searchPanel.add(searchField);
        JButton searchButton = new JButton("搜索");
        searchPanel.add(searchButton);
        JButton showAllButton = new JButton("显示全部");
        searchPanel.add(showAllButton);
        toolbarPanel.add(searchPanel, BorderLayout.WEST);
        // 操作按钮面板
        JPanel buttonPanel = new JPanel();
        JButton addButton = new JButton("添加文章");
        JButton editButton = new JButton("编辑文章");
        JButton deleteButton = new JButton("删除文章");
        JButton viewButton = new JButton("查看文章");
        JButton refreshButton = new JButton("刷新");
        buttonPanel.add(addButton);
        buttonPanel.add(editButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(viewButton);
        buttonPanel.add(refreshButton);
        toolbarPanel.add(buttonPanel, BorderLayout.EAST);
        add(toolbarPanel, BorderLayout.NORTH);
        // 主内容区
        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
        // 表格面板
        String[] columns = {"ID", "标题", "作者", "分类", "创建时间", "浏览量"};
        tableModel = new DefaultTableModel(columns, 0);
        articleTable = new JTable(tableModel);
        articleTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane tableScrollPane = new JScrollPane(articleTable);
        splitPane.setLeftComponent(tableScrollPane);
        // 内容预览面板
        JPanel contentPanel = new JPanel(new BorderLayout());
        contentPanel.add(new JLabel(" 文章内容预览: "), BorderLayout.NORTH);
        contentArea = new JTextArea();
        contentArea.setEditable(false);
        JScrollPane contentScrollPane = new JScrollPane(contentArea);
        contentPanel.add(contentScrollPane, BorderLayout.CENTER);
        splitPane.setRightComponent(contentPanel);
        splitPane.setDividerLocation(550);
        add(splitPane, BorderLayout.CENTER);
        // 底部状态栏
        JPanel statusPanel = new JPanel();
        JLabel statusLabel = new JLabel("共 0 篇文章");
        statusPanel.add(statusLabel);
        add(statusPanel, BorderLayout.SOUTH);
        // 事件监听
        searchButton.addActionListener(e -> searchArticles());
        showAllButton.addActionListener(e -> loadArticles());
        addButton.addActionListener(e -> showAddDialog());
        editButton.addActionListener(e -> showEditDialog());
        deleteButton.addActionListener(e -> deleteArticle());
        viewButton.addActionListener(e -> viewArticle());
        refreshButton.addActionListener(e -> loadArticles());
        // 表格点击事件
        articleTable.getSelectionModel().addListSelectionListener(e -> {
            int selectedRow = articleTable.getSelectedRow();
            if (selectedRow >= 0) {
                Long id = (Long) tableModel.getValueAt(selectedRow, 0);
                Article article = articleService.getArticle(id);
                if (article != null) {
                    contentArea.setText(article.getContent());
                }
            }
        });
        // 存储statusLabel引用以备更新
        getContentPane().putClientProperty("statusLabel", statusLabel);
    }
    private void showAddDialog() {
        JDialog dialog = new JDialog(this, "添加文章", true);
        dialog.setSize(500, 400);
        dialog.setLocationRelativeTo(this);
        JPanel panel = new JPanel(new GridLayout(5, 2, 5, 5));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        JTextField titleField = new JTextField();
        JTextField authorField = new JTextField();
        JTextField categoryField = new JTextField();
        JTextArea contentTextArea = new JTextArea(5, 20);
        panel.add(new JLabel("标题: "));
        panel.add(titleField);
        panel.add(new JLabel("作者: "));
        panel.add(authorField);
        panel.add(new JLabel("分类: "));
        panel.add(categoryField);
        panel.add(new JLabel("内容: "));
        JScrollPane contentScroll = new JScrollPane(contentTextArea);
        panel.add(contentScroll);
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");
        panel.add(saveButton);
        panel.add(cancelButton);
        saveButton.addActionListener(e -> {
            if (titleField.getText().trim().isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "标题不能为空!");
                return;
            }
            boolean success = articleService.createArticle(
                titleField.getText(),
                authorField.getText(),
                categoryField.getText(),
                contentTextArea.getText()
            );
            if (success) {
                JOptionPane.showMessageDialog(dialog, "文章添加成功!");
                dialog.dispose();
                loadArticles();
            } else {
                JOptionPane.showMessageDialog(dialog, "文章添加失败!");
            }
        });
        cancelButton.addActionListener(e -> dialog.dispose());
        dialog.add(panel);
        dialog.setVisible(true);
    }
    private void showEditDialog() {
        int selectedRow = articleTable.getSelectedRow();
        if (selectedRow < 0) {
            JOptionPane.showMessageDialog(this, "请先选择要编辑的文章!");
            return;
        }
        Long id = (Long) tableModel.getValueAt(selectedRow, 0);
        Article article = articleService.getArticle(id);
        if (article == null) {
            JOptionPane.showMessageDialog(this, "文章不存在!");
            return;
        }
        JDialog dialog = new JDialog(this, "编辑文章", true);
        dialog.setSize(500, 400);
        dialog.setLocationRelativeTo(this);
        JPanel panel = new JPanel(new GridLayout(5, 2, 5, 5));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        JTextField titleField = new JTextField(article.getTitle());
        JTextField authorField = new JTextField(article.getAuthor());
        JTextField categoryField = new JTextField(article.getCategory());
        JTextArea contentTextArea = new JTextArea(article.getContent(), 5, 20);
        panel.add(new JLabel("标题: "));
        panel.add(titleField);
        panel.add(new JLabel("作者: "));
        panel.add(authorField);
        panel.add(new JLabel("分类: "));
        panel.add(categoryField);
        panel.add(new JLabel("内容: "));
        JScrollPane contentScroll = new JScrollPane(contentTextArea);
        panel.add(contentScroll);
        JButton updateButton = new JButton("更新");
        JButton cancelButton = new JButton("取消");
        panel.add(updateButton);
        panel.add(cancelButton);
        updateButton.addActionListener(e -> {
            boolean success = articleService.updateArticle(
                id,
                titleField.getText(),
                authorField.getText(),
                categoryField.getText(),
                contentTextArea.getText()
            );
            if (success) {
                JOptionPane.showMessageDialog(dialog, "文章更新成功!");
                dialog.dispose();
                loadArticles();
            } else {
                JOptionPane.showMessageDialog(dialog, "文章更新失败!");
            }
        });
        cancelButton.addActionListener(e -> dialog.dispose());
        dialog.add(panel);
        dialog.setVisible(true);
    }
    private void deleteArticle() {
        int selectedRow = articleTable.getSelectedRow();
        if (selectedRow < 0) {
            JOptionPane.showMessageDialog(this, "请先选择要删除的文章!");
            return;
        }
        int confirm = JOptionPane.showConfirmDialog(this, 
            "确定要删除这篇文章吗?", "确认删除", JOptionPane.YES_NO_OPTION);
        if (confirm == JOptionPane.YES_OPTION) {
            Long id = (Long) tableModel.getValueAt(selectedRow, 0);
            if (articleService.deleteArticle(id)) {
                JOptionPane.showMessageDialog(this, "文章删除成功!");
                loadArticles();
            } else {
                JOptionPane.showMessageDialog(this, "文章删除失败!");
            }
        }
    }
    private void viewArticle() {
        int selectedRow = articleTable.getSelectedRow();
        if (selectedRow < 0) {
            JOptionPane.showMessageDialog(this, "请先选择要查看的文章!");
            return;
        }
        Long id = (Long) tableModel.getValueAt(selectedRow, 0);
        Article article = articleService.getArticle(id);
        if (article != null) {
            new ArticleDetailDialog(this, article).setVisible(true);
            loadArticles(); // 更新浏览量
        }
    }
    private void loadArticles() {
        tableModel.setRowCount(0);
        List<Article> articles = articleService.getAllArticles();
        for (Article article : articles) {
            Object[] row = {
                article.getId(),
                article.getTitle(),
                article.getAuthor(),
                article.getCategory(),
                article.getCreateTime().toString(),
                article.getViewCount()
            };
            tableModel.addRow(row);
        }
        updateStatusLabel();
    }
    private void searchArticles() {
        String keyword = searchField.getText().trim();
        if (keyword.isEmpty()) {
            loadArticles();
            return;
        }
        tableModel.setRowCount(0);
        List<Article> articles = articleService.searchArticles(keyword);
        for (Article article : articles) {
            Object[] row = {
                article.getId(),
                article.getTitle(),
                article.getAuthor(),
                article.getCategory(),
                article.getCreateTime().toString(),
                article.getViewCount()
            };
            tableModel.addRow(row);
        }
        updateStatusLabel();
    }
    private void updateStatusLabel() {
        JLabel statusLabel = (JLabel) getContentPane().getClientProperty("statusLabel");
        if (statusLabel != null) {
            statusLabel.setText("共 " + tableModel.getRowCount() + " 篇文章");
        }
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new ArticleApp().setVisible(true);
        });
    }
}

ArticleDetailDialog.java

package com.example.article.gui;
import com.example.article.entity.Article;
import javax.swing.*;
import java.awt.*;
public class ArticleDetailDialog extends JDialog {
    public ArticleDetailDialog(JFrame parent, Article article) {
        super(parent, "文章详情", true);
        setSize(600, 500);
        setLocationRelativeTo(parent);
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        // 标题和基本信息
        JPanel headerPanel = new JPanel(new BorderLayout());
        JLabel titleLabel = new JLabel(article.getTitle());
        titleLabel.setFont(new Font("Arial", Font.BOLD, 18));
        headerPanel.add(titleLabel, BorderLayout.NORTH);
        JPanel metaPanel = new JPanel();
        metaPanel.add(new JLabel("作者: " + article.getAuthor()));
        metaPanel.add(new JLabel("  分类: " + article.getCategory()));
        metaPanel.add(new JLabel("  发布时间: " + article.getCreateTime()));
        metaPanel.add(new JLabel("  浏览量: " + article.getViewCount()));
        headerPanel.add(metaPanel, BorderLayout.CENTER);
        panel.add(headerPanel, BorderLayout.NORTH);
        // 内容
        JTextArea contentTextArea = new JTextArea(article.getContent());
        contentTextArea.setEditable(false);
        contentTextArea.setFont(new Font("宋体", Font.PLAIN, 14));
        JScrollPane scrollPane = new JScrollPane(contentTextArea);
        panel.add(scrollPane, BorderLayout.CENTER);
        // 关闭按钮
        JButton closeButton = new JButton("关闭");
        closeButton.addActionListener(e -> dispose());
        JPanel bottomPanel = new JPanel();
        bottomPanel.add(closeButton);
        panel.add(bottomPanel, BorderLayout.SOUTH);
        add(panel);
    }
}

数据库建表SQL

CREATE DATABASE IF NOT EXISTS article_db DEFAULT CHARACTER SET utf8mb4;
USE article_db;
CREATE TABLE IF NOT EXISTS articles (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,VARCHAR(200) NOT NULL,
    author VARCHAR(50) DEFAULT '匿名',
    category VARCHAR(50),
    content TEXT,
    create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    update_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    view_count INT DEFAULT 0,
    INDEX idx_category (category),
    INDEX idx_create_time (create_time)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

运行说明

  1. 环境要求

    • JDK 8+
    • MySQL 5.7+
    • MySQL JDBC驱动包
  2. 运行步骤

    • 创建数据库并执行SQL脚本
    • 修改DBUtil.java中的数据库连接信息
    • 导入MySQL JDBC驱动jar包
    • 编译并运行ArticleApp.java

功能特点

  1. 文章CRUD操作:完整的新增、查看、编辑、删除功能
  2. 搜索功能:支持按标题、作者、分类搜索
  3. 浏览量统计:自动增加文章点击量
  4. GUI界面:使用Java Swing开发美观的桌面界面
  5. 敏感度展示:实时预览文章内容

这个案例展示了Java在桌面应用开发中的应用,包括数据库操作、面向对象设计、Swing GUI编程等核心技能。

抱歉,评论功能暂时关闭!