博客系统(java | mysql)

Main

package boke;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @Author Li_ZW
 * @Date: 2020/06/13
 * @Time: 17:49
 * @Description
 */
public class Main {
    private static List<String> featureList = new ArrayList<>();
    private static List<Action> actionList = new ArrayList<>();

    private static void initFeatureList() {
        featureList.add("用户注册");
        featureList.add("用户登录");
        featureList.add("查看文章列表");
        featureList.add("发表文章");
        featureList.add("查看指定文章内容");

        featureList.add("评论文章");
        featureList.add("点赞文章");
    }

    private static void initActionList() {
        actionList.add(new UserRegisterAction());
        actionList.add(new UserLoginAction());
        actionList.add(new ArticleListAction());
        actionList.add(new ArticlePublishAction());
        actionList.add(new ArticleDetailAction());
    }

    public static void main(String[] args) {
        initFeatureList();
        initActionList();

        Scanner scanner = new Scanner(System.in);
        while (true) {
            showMenu();
            showPrompt();
            int select = scanner.nextInt();
            doAction(select);
        }
    }

    private static void doAction(int select) {
        if (select == 0) {
            System.out.println("感谢你的使用!");
            System.exit(0);
        }

        System.out.println("您的选择是:" + featureList.get(select-1));
        if (select-1 < actionList.size()) {
            Action action = actionList.get(select-1);
            action.run();
        }else {
            System.out.println("该功能尚未开发,敬请期待...");
        }
    }

    private static void showPrompt() {
        System.out.print("请输入功能的序号> ");
    }

    private static void showMenu() {
        System.out.println("欢迎使用《博客》,支持以下功能:");
        for (int i = 0; i < featureList.size(); i++) {
            System.out.printf("  %d. %s%n", i+1, featureList.get(i));
        }
        System.out.println("  0. 退出");
    }
}

用户注册

package boke;

import com.sun.org.apache.bcel.internal.generic.RETURN;

import java.sql.*;
import java.util.Scanner;

/**
 * @Author Li_ZW
 * @Date: 2020/06/13
 * @Time: 17:50
 * @Description
 */
public class UserRegisterAction implements Action{
    @Override
    public void run() {
        System.out.println("开始用户注册...");
        System.out.println();

        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入用户姓名> ");
        String username = scanner.nextLine();
        System.out.print("请输入用户昵称> ");
        String nickname = scanner.nextLine();
        System.out.print("请输入用户密码> ");
        String password = scanner.nextLine();

        String sql = "insert into users (username,nickname,password) values (?,?,?)";
        try (Connection connection = DBUtil.getConnection()) {
            try (PreparedStatement statement = connection.prepareStatement(sql, Statement. RETURN_GENERATED_KEYS)){
                statement.setString(1,username);
                statement.setString(2,nickname);
                statement.setString(3,password);

                statement.executeUpdate();

                int id;
                try (ResultSet r = statement.getGeneratedKeys()){
                    r.next();
                    id = r.getInt(1);
                }
                System.out.println("注册成功,欢迎您 " + nickname);

                User user = new User();
                user.id = id;
                user.nickname = nickname;
                user.username = username;
                User.login(user);
            }

        }catch (SQLException e) {
            System.out.println("错误: " + e.getMessage());
        }
    }
}

用户登录

package boke;

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

/**
 * @Author Li_ZW
 * @Date: 2020/06/13
 * @Time: 17:50
 * @Description
 */
public class UserLoginAction implements Action {
    @Override
    public void run() {
        System.out.println("开始用户登录...");
        System.out.println();

        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入用户名> ");
        String username = scanner.nextLine();
        System.out.print("请输入密码> ");
        String password = scanner.nextLine();

        try (Connection connection = DBUtil.getConnection()) {
            String sql = "select id,nickname from users where username = ? and password = ?";
            try (PreparedStatement statement = connection.prepareStatement(sql)) {
                statement.setString(1,username);
                statement.setString(2,password);

                try (ResultSet resultSet = statement.executeQuery()) {
                    if (resultSet.next()) {
                        int id = resultSet.getInt(1);
                        String nickname = resultSet.getString(2);
                        User user = new User();
                        user.id = id;
                        user.username = username;
                        user.nickname = nickname;

                        User.login(user);
                    }else {
                        System.out.println("用户名或密码错误,请重新输入!");
                    }
                }
            }
        } catch (SQLException e) {
            System.out.println("错误:" + e.getMessage());
        }
    }

}

用户

package boke;

/**
 * @Author Li_ZW
 * @Date: 2020/06/13
 * @Time: 17:49
 * @Description
 */
public class User {
    int id;
    String username;
    String nickname;

    private static User currentUser = null;

    public static void login(User user) {
        currentUser = user;
        System.out.println("刚刚登陆的用户信息是:" + currentUser);
    }

    public static User getCurrentUser() {
        return currentUser;
    }

    public static boolean isLogined() {
        return currentUser != null;
    }

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

mysql

package boke;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Author Li_ZW
 * @Date: 2020/06/13
 * @Time: 17:49
 * @Description
 */
public class DBUtil {
    private static DataSource dataSource = null;

    static {
        initDataSource();
    }

    private static void initDataSource() {
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        mysqlDataSource.setServerName("127.0.0.1");
        mysqlDataSource.setPort(3306);
        mysqlDataSource.setUser("root");
        mysqlDataSource.setPassword("hello");
        mysqlDataSource.setDatabaseName("li_boke");
        mysqlDataSource.setUseSSL(false);
        mysqlDataSource.setCharacterEncoding("utf8");

        dataSource = mysqlDataSource;
    }

    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
}

Action接口

package boke;

/**
 * @Author Li_ZW
 * @Date: 2020/06/13
 * @Time: 17:48
 * @Description
 */
public interface Action {
    void run();
}

查看文章列表

package boke;

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

/**
 * @Author Li_ZW
 * @Date: 2020/06/13
 * @Time: 17:48
 * @Description
 */
public class ArticleListAction implements Action {
    @Override
    public void run() {
        try (Connection connection = DBUtil.getConnection()) {
            List<String[]> articleList = new ArrayList<>();

            String sql = "select id, author_id, title, published_at from articles order by published_at desc";
            try (PreparedStatement statement = connection.prepareStatement(sql)) {
                try (ResultSet rs = statement.executeQuery()) {
                    while (rs.next()) {
                        String[] article = new String[4];
                        String id = rs.getString("id");
                        String authorId = rs.getString("author_id");
                        String title = rs.getString("title");
                        String publishedAt = rs.getString("published_at");
                        article[0] = id;
                        article[1] = authorId;
                        article[2] = title;
                        article[3] = publishedAt;

                        articleList.add(article);
                    }
                }
            }
            Set<String> authorIdSet = new HashSet<>();
            for (String[] article: articleList) {
                String authorId = article[1];
                authorIdSet.add(authorId);
            }

            StringBuilder querySql = new StringBuilder("select id, nickname from users where id in (");
            for (int i = 1; i < authorIdSet.size(); i++) {
                querySql.append("?,");
            }
            querySql.append("?)");
            System.out.println("DEBUG: " + querySql.toString());

            Map<String, String> userIdToNicknameMap = new HashMap<>();
            try (PreparedStatement statement = connection.prepareStatement(querySql.toString())) {
                int i = 1;
                for (String id : authorIdSet) {
                    statement.setString(i++, id);
                }

                try (ResultSet rs = statement.executeQuery()) {
                    while (rs.next()) {
                        String id = rs.getString("id");
                        String nickname = rs.getString("nickname");
                        userIdToNicknameMap.put(id, nickname);
                    }
                }
            }

            System.out.printf("#ID  | 标题                  | 作者    | 发表时间%n");
            for (String[] article : articleList) {
                String id = article[0];
                String authorId = article[1];
                String authorNickname = userIdToNicknameMap.get(authorId);
                String title = article[2];
                String publishedAt = article[3];

                System.out.printf("%-4s | %-40s | %-10s | %s%n", id, title, authorNickname, publishedAt);
            }
        }catch (SQLException e) {
            System.out.println("错误:" + e.getMessage());
        }
    }
}

发表文章

package boke;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

/**
 * @Author Li_ZW
 * @Date: 2020/06/13
 * @Time: 17:49
 * @Description
 */
public class ArticlePublishAction implements Action {
    @Override
    public void run() {
        if (!User.isLogined()) {
            System.out.println("** 需要先登录,才能操作该功能!!");
            return;
        }

        System.out.println("发表文章中 ...");
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入文章标题> ");
        String title = scanner.nextLine();
        System.out.println("请输入文章正文> ");
        String content = scanner.nextLine();
        int authorId = User.getCurrentUser().id;
        Date publishedAt = new Date();

        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String publishedAtStr = format.format(publishedAt);

        try (Connection c = DBUtil.getConnection()) {
            String sql = "insert into articles (author_id, title, published_at, content) values (?, ?, ?, ?)";
            try (PreparedStatement s = c.prepareStatement(sql)) {
                s.setInt(1, authorId);
                s.setString(2, title);
                s.setString(3, publishedAtStr); // "2020-06-08 20:10:38"
                s.setString(4, content);

                s.executeUpdate();

                System.out.println("《" + title + "》 文章发表成功!");
            }
        } catch (SQLException e) {
            System.out.println("错误:" + e.getMessage());
        }
    }
}

查看指定文章

package boke;

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

/**
 * @Author Li_ZW
 * @Date: 2020/06/13
 * @Time: 17:48
 * @Description
 */

public class ArticleDetailAction implements Action {
    @Override
    public void run() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入要查看的文章的id> ");
        String id = scanner.nextLine();
        String authorId = null;
        String title = null;
        String content = null;
        String publishedAt = null;
        int likeCount = 0;

        try (Connection c = DBUtil.getConnection()) {
            // 1. 查找文章信息
            String queryArticleSql = "select author_id, title, content, published_at from articles where id = ?";
            try (PreparedStatement s = c.prepareStatement(queryArticleSql)) {
                s.setString(1, id);
                try (ResultSet rs = s.executeQuery()) {
                    if (!rs.next()) {
                        System.out.println("** 没有这篇文章!!");
                        return;
                    }

                    authorId = rs.getString("author_id");
                    title = rs.getString("title");
                    content = rs.getString("content");
                    publishedAt = rs.getString("published_at");
                }
            }

            // 2. 查询点赞数量
            String likeCountSql = "select count(*) from like_relations where article_id = ?";
            try (PreparedStatement s = c.prepareStatement(likeCountSql)) {
                s.setString(1, id);
                try (ResultSet rs = s.executeQuery()) {
                    rs.next();
                    likeCount = rs.getInt(1);
                }
            }

            // 3. 查询评论信息
            List<String[]> commentList = new ArrayList<>();
            String queryCommentSql = "select user_id, content, published_at from comments where article_id = ? order by published_at desc";
            try (PreparedStatement s = c.prepareStatement(queryCommentSql)) {
                s.setString(1, id);
                try (ResultSet rs = s.executeQuery()) {
                    while (rs.next()) {
                        String[] comment = new String[3];
                        comment[0] = rs.getString("user_id");
                        comment[1] = rs.getString("content");
                        comment[2] = rs.getString("published_at");

                        commentList.add(comment);
                    }
                }
            }

            // 4. 根据用户id,查询用户昵称
            // 用户id来自(作者id + 评论者id)
            Set<String> userIdSet = new HashSet<>();
            userIdSet.add(authorId);
            for (String[] comment : commentList) {
                userIdSet.add(comment[0]);
            }

            StringBuilder queryNicknameSql = new StringBuilder("select id, nickname from users where id in (");
            for (int i = 1; i < userIdSet.size(); i++) {
                queryNicknameSql.append("?, ");
            }
            queryNicknameSql.append("?)");

            Map<String, String> userIdToNicknameMap = new HashMap<>();
            try (PreparedStatement s = c.prepareStatement(queryNicknameSql.toString())) {
                int i = 1;
                for (String userId : userIdSet) {
                    s.setString(i++, userId);
                }

                try (ResultSet rs = s.executeQuery()) {
                    while (rs.next()) {
                        userIdToNicknameMap.put(rs.getString("id"), rs.getString("nickname"));
                    }
                }
            }

            // 5. 根据所有的信息,进行显示
            System.out.println(title);
            System.out.println(userIdToNicknameMap.get(authorId));
            System.out.println(publishedAt);
            System.out.println("点赞人数: " + likeCount);
            System.out.println("==================================================");
            System.out.println(content);
            System.out.println("==================================================");
            for (String[] comment : commentList) {
                System.out.println(userIdToNicknameMap.get(comment[0]) + "|" + comment[1] + "|" + comment[2]);
            }

        } catch (SQLException e) {
            System.out.println("错误:" + e.getMessage());
        }
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值