博客系统(后端实现)

104 阅读4分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

准备工作

1.创建maven项目 2.引入依赖。

<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.12.6.1</version>
</dependency>

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
</dependency>

3.创建目录 创建webapp目录

数据库的设计

1.创建数据库、表结构 这就是数据库设计

根据当前需求设计数据库

需求:

1)存储博客

2)获取博客

3)登录校验

根据上面的需求我们可以知道我们需要下面的这些表

i)博客表

ii)用户表

--创建一个库
create database if not exists hc_blog;
--使用这个库
use hc_blog;
--创建博客表
drop table if exists blog;
--博客表里面的元素
create table blog(
--这篇文章的序号
    blogId int primary key auto_increment,
--    这篇文章的标题
    title varchar (1024),
--   mediumtext 可以用这个来接收更长的字符串
    content mediumtext,
--    文章作者的id
    userId int,
--    文章发布时间
    postTime datetime
);
--在博客表里面插入元素
insert into blog value(null , '这是第一篇博客' , '从今天开始,认真学JAVA' , 1 , now());
insert into blog value(null , '这是第二篇博客' , '从今天开始,认真学JAVA' , 1 , now());
insert into blog value(null , '这是第三篇博客' , '从今天开始,认真学JAVA' , 1 , now());
insert into blog value(null , '这是第四篇博客' , '从今天开始,认真学JAVA' , 2 , now());
--创建用户表
drop table if exists user;
--用户表详情
create table user(
--用户的ID
    userId int primary key auto_increment,
--    用户的名字
    username varchar(1024) unique ,
--用户的密码
    password varchar(1024)
);
--插入用户元素
insert into user values(null , '橘黄小鹿' , '0706');

之后我们可以直接复制到数据库里面执行一下。

和数据库建立连接

为了方便操作,我们可以创建一个类,专门来保存数据库的一些操作。

private static final String URL = "jdbc:mysql://127.0.0.1:3306/hc_blog?characterEncoding=utf8&useSSL=false";
private static final String USERNAME = "root";
private static final String PASSWORD = "111111";
private static volatile DataSource dataSource = null;

然后就是要和数据库连接了。

private static DataSource getDataSource(){
    if(dataSource == null){
        synchronized (DBUtil.class){
            if(dataSource == null){
                dataSource = new MysqlDataSource();
                ((MysqlDataSource)dataSource).setUrl(URL);
                ((MysqlDataSource)dataSource).setUser(USERNAME);
                ((MysqlDataSource)dataSource).setPassword(PASSWORD);
            }
        }
    }
    return dataSource;
}
public static Connection getConnection() throws SQLException {
    return getDataSource().getConnection();
}

当然,数据库里面还是有很多需要手动关闭的资源的,我们也弄在一起。

public static void close(Connection connection , PreparedStatement statement, ResultSet resultSet){
    if(resultSet != null){
        try {
            resultSet.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    if(statement != null){
        try {
            statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    if(connection != null){
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

之后我们要创建两个类来接收数据库里面的内容,

对象处理

分别是bolg和user来接收数据库中两个表的内容

blog类

public class Blog {
    private int blogId;
    private String title;
    private String content;
    private int userId;
    private Timestamp postTime;

    public int getBlogId() {
        return blogId;
    }

    public void setBlogId(int blogId) {
        this.blogId = blogId;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getPostTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return simpleDateFormat.format(postTime);
    }

    public void setPostTime(Timestamp postTime) {
        this.postTime = postTime;
    }
}

User类

public class User {
    private int userId;
    private String username;
    private String password;

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    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;
    }
}

当然我们还要多这两个类的内容进行增删查改的内容

对于blog的增删查改

public class BlogDao {
//    添加博客
    public void insert(Blog blog){
//        拿到连接和发送sql语句
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = DB.getConnection();
            String sql = "insert into blog values(null , ? , ? , ? , now())";
            statement = connection.prepareStatement(sql);
            statement.setString(1,blog.getTitle());
            statement.setString(2,blog.getContent());
            statement.setInt(3,blog.getUserId());
            statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DB.close(connection , statement , null);
        }
    }
//    查找博客
    public List<Blog> selectAll(){
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        List<Blog> blogs = new ArrayList<>();
        try {
            connection = DB.getConnection();
            String sql = "select * from blog order by postTime desc";
            statement = connection.prepareStatement(sql);
            resultSet = statement.executeQuery();
            while(resultSet.next()){
                Blog blog = new Blog();
                blog.setBlogId(resultSet.getInt("blogId"));
                blog.setTitle(resultSet.getString("title"));
                String content = resultSet.getString("content");
                if(content.length() > 50){
                    content = content.substring(0 , 50) + "...";
                }
                blog.setContent(content);
                blog.setUserId(resultSet.getInt("userId"));
                blog.setPostTime(resultSet.getTimestamp("postTime"));
                blogs.add(blog);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DB.close(connection,statement,resultSet);
        }
        return blogs;
    }
//    选择某一篇博客
    public Blog selectOne(int blogId){
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        Blog curBlog = new Blog();
        try {
            connection = DB.getConnection();
            String sql = "select * from blog where blogId = ?";
            statement = connection.prepareStatement(sql);
            statement.setInt(1 , blogId);
            resultSet = statement.executeQuery();
            if(resultSet.next()){
                curBlog.setBlogId(resultSet.getInt("blogId"));
                curBlog.setTitle(resultSet.getString("title"));
                curBlog.setContent(resultSet.getString("content"));
                curBlog.setUserId(resultSet.getInt("userId"));
                curBlog.setPostTime(resultSet.getTimestamp("postTime"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DB.close(connection,statement,resultSet);
        }
        return curBlog;
    }
//    删除博客
    public void delete(int blogId){
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = DB.getConnection();
            String sql = "delete from blog where blogId = ?";
            statement = connection.prepareStatement(sql);
            statement.setInt(1,blogId);
            statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DB.close(connection , statement , null);
        }
    }
}

对于user的增删查改

public class UserDao {
//    用名字来查找用户
    public User selectName(String username){
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        User user = new User();
        try {
            connection = DB.getConnection();
            String sql = "select * from user where username = ?";
            statement = connection.prepareStatement(sql);
            statement.setString(1,username);
            resultSet = statement.executeQuery();
            if(resultSet.next()){
                user.setUsername(resultSet.getString("username"));
                user.setUserId(resultSet.getInt("userId"));
                user.setPassword(resultSet.getString("password"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DB.close(connection,statement,resultSet);
        }
        return user;
    }
//    用id来查找用户
    public User selectId(int userId){
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        User user = new User();
        try {
            connection = DB.getConnection();
            String sql = "select * from user where userId = ?";
            statement = connection.prepareStatement(sql);
            statement.setInt(1,userId);
            resultSet = statement.executeQuery();
            if(resultSet.next()){
                user.setUsername(resultSet.getString("username"));
                user.setUserId(resultSet.getInt("userId"));
                user.setPassword(resultSet.getString("password"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DB.close(connection,statement,resultSet);
        }
        return user;
    }
}

之后我们要做到的就是登录还有博客相关的处理

servlet操作

关于登录的操作

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        resp.setCharacterEncoding("utf8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println("username=" + username + ", password=" + password);
        if (username == null || "".equals(username) || password == null || "".equals(password)) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("当前的用户名或密码为空!");
            return;
        }
        UserDao userDao = new UserDao();
        User user = userDao.selectName(username);
        if (user == null || !user.getPassword().equals(password)) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("用户名或密码错误!");
            return;
        }
        HttpSession session = req.getSession(true);
        session.setAttribute("user", user);
        resp.sendRedirect("blog_list.html");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");
        HttpSession session = req.getSession(false);
        if (session == null) {
            User user = new User();
            resp.getWriter().write(objectMapper.writeValueAsString(user));
            return;
        }
        User user = (User) session.getAttribute("user");
        if (user == null) {
            user = new User();
            resp.getWriter().write(objectMapper.writeValueAsString(user));
            return;
        }
        user.setPassword("");
        resp.getWriter().write(objectMapper.writeValueAsString(user));
    }
}

关于博客的管理操作

@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BlogDao blogDao = new BlogDao();
        String param = req.getParameter("blogId");
        if(param == null){
            List<Blog> blogs = blogDao.selectAll();
            String respJson = objectMapper.writeValueAsString(blogs);
            resp.setContentType("application/json; charset=utf8");
            resp.getWriter().write(respJson);
        }else{
            int blogId = Integer.parseInt(param);
            Blog cur = blogDao.selectOne(blogId);
            String respJson = objectMapper.writeValueAsString(cur);
            resp.setContentType("application/json; charset=utf8");
            resp.getWriter().write(respJson);
        }
    }
}