当前位置:   article > 正文

实现博客系统_csdn博客

csdn博客

目录

一、博客系统简介

二、准备工作 

三、设计实现数据库 

四、封装数据库 

创建User类和Blog类

使用JDBC连接数据库

创建BlogDAO类操作数据库中的Blog表 

创建UserDAO类操作数据库中的user表 

五、实现具体功能 

1、实现博客列表页

约定前后端交互接口

服务器端 

客户端 

2、实现博客详情页 

约定前后端交互接口

服务器端 

客户端 

 3、实现登录页

 约定前后端交互接口

服务器端 

客户端 

4、实现强制要求登陆 

约定前后端交互接口 

服务器端 

客户端 

5、实现显示用户信息 

约定前后端交互接口 

服务器端

客户端

6、实现发布博客 

实现前后端交互接口

服务器端 

客户端 

7、删除博客 

约定前后端交互接口

服务器端 

客户端 

8、实现注销功能 

约定前后端交互接口

服务器端 

客户端 

六、效果展示 


一、博客系统简介

现进行登录确认身份,登录成功后进入博客列表页,在博客列表页可以选择查看全文,如果是自己写的博客也可以选择删除。

二、准备工作 

创建一个maven项目,在pom.xml中引入Mysql依赖、Servlet依赖以及Jackson依赖。

  1. <dependencies>
  2. <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
  3. <dependency>
  4. <groupId>mysql</groupId>
  5. <artifactId>mysql-connector-java</artifactId>
  6. <version>5.1.47</version>
  7. </dependency>
  8. <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
  9. <dependency>
  10. <groupId>javax.servlet</groupId>
  11. <artifactId>javax.servlet-api</artifactId>
  12. <version>3.1.0</version>
  13. <scope>provided</scope>
  14. </dependency>
  15. <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
  16. <dependency>
  17. <groupId>com.fasterxml.jackson.core</groupId>
  18. <artifactId>jackson-databind</artifactId>
  19. <version>2.13.5</version>
  20. </dependency>
  21. </dependencies>

创建目录结构,并将前端页面文件添加到目录中。 

 web.xml文件的内容如下:

  1. <!DOCTYPE web-app PUBLIC
  2. "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
  3. "http://java.sun.com/dtd/web-app_2_3.dtd" >
  4. <web-app>
  5. <display-name>Archetype Created Web Application</display-name>
  6. </web-app>

三、设计实现数据库 

创建blog_system数据库。

 create database blog_system ;

创建blog表,有blogId(博客编号) 、title(博客标题)、content(博客内容)、userId(作者编号)、postTime(发布时间)这些属性。

  1. create table blog
  2. (
  3. blogId int primary key auto_increment,
  4. title varchar(1024),
  5. content mediumtext,
  6. userId int,
  7. postTime datetime
  8. );

向blog表中插入一些数据。

  1. insert into blog values(null, '这是第一篇博客', '从今天开始, 我要认真学 Java', 1, now());
  2. insert into blog values(null, '这是第二篇博客', '从昨天开始, 我要认真学 Java', 1, now());
  3. insert into blog values(null, '这是第三篇博客', '从前天开始, 我要认真学 Java', 1, now());
  4. insert into blog values(null, '这是第一篇博客', '从今天开始, 我要认真学 C++', 2, now());
  5. insert into blog values(null, '这是第二篇博客', '从昨天开始, 我要认真学 C++', 2, now());

创建user表,有userId(用户编号)、userName(用户名)、password(密码)这些属性。

  1. create table user(
  2. userId int primary key auto_increment,
  3. userName varchar(100) unique ,
  4. password varchar (100)
  5. );

同样也向user表中插入一些数据。

  1. insert into user values(null,'zhangyi','1234');
  2. insert into user values(null,'zhanger','1234');
  3. insert into user values(null,'zhangsan','1234');

四、封装数据库 

创建User类和Blog类

  1. public class Blog {
  2. private int blogId;
  3. private String title;
  4. private String content;
  5. private int userId;
  6. private Timestamp postTime;
  7. public Blog(int blogId, String title, String content, int userId, Timestamp postTime) {
  8. this.blogId = blogId;
  9. this.title = title;
  10. this.content = content;
  11. this.userId = userId;
  12. this.postTime = postTime;
  13. }
  14. public int getBlogId() {
  15. return blogId;
  16. }
  17. public void setBlogId(int blogId) {
  18. this.blogId = blogId;
  19. }
  20. public String getTitle() {
  21. return title;
  22. }
  23. public void setTitle(String title) {
  24. this.title = title;
  25. }
  26. public String getContent() {
  27. return content;
  28. }
  29. public void setContent(String content) {
  30. this.content = content;
  31. }
  32. public int getUserId() {
  33. return userId;
  34. }
  35. public void setUserId(int userId) {
  36. this.userId = userId;
  37. }
  38. public String getPostTime() {
  39. SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  40. return simpleDateFormat.format(postTime);
  41. }
  42. public void setPostTime(Timestamp postTime) {
  43. this.postTime = postTime;
  44. }
  45. }
  1. public class User {
  2. private int userId;
  3. private String userName;
  4. private String password;
  5. public User(int userId, String userName, String password) {
  6. this.userId = userId;
  7. this.userName = userName;
  8. this.password = password;
  9. }
  10. public int getUserId() {
  11. return userId;
  12. }
  13. public void setUserId(int userId) {
  14. this.userId = userId;
  15. }
  16. public String getUserName() {
  17. return userName;
  18. }
  19. public void setUserName(String userName) {
  20. this.userName = userName;
  21. }
  22. public String getPassword() {
  23. return password;
  24. }
  25. public void setPassword(String password) {
  26. this.password = password;
  27. }
  28. }

使用JDBC连接数据库

创建DBUtil连接数据库以及相关资源的关闭。

  1. public class DBUtil {
  2. private static final String url = "jdbc:mysql://127.0.0.1:3306/blog_system?characterEncoding=utf8&useSSL=false";
  3. private static final String user = "root";
  4. private static final String password = "1234";
  5. private static volatile DataSource dataSource;
  6. private static DataSource getDataSource(){
  7. if(dataSource == null){
  8. synchronized (DBUtil.class){
  9. if (dataSource == null){
  10. dataSource = new MysqlDataSource();
  11. ((MysqlDataSource)dataSource).setURL(url);
  12. ((MysqlDataSource)dataSource).setUser(user);
  13. ((MysqlDataSource)dataSource).setPassword(password);
  14. }
  15. }
  16. }
  17. return dataSource;
  18. }
  19. public static Connection getConnection() throws SQLException {
  20. return (Connection) getDataSource().getConnection();
  21. }
  22. public static void closeResource(Connection connection, PreparedStatement statement, ResultSet resultSet) {
  23. if(connection != null){
  24. try {
  25. connection.close();
  26. } catch (SQLException e) {
  27. e.printStackTrace();
  28. }
  29. }
  30. if(statement != null){
  31. try {
  32. statement.close();
  33. } catch (SQLException e) {
  34. e.printStackTrace();
  35. }
  36. }
  37. if(resultSet != null){
  38. try {
  39. resultSet.close();
  40. } catch (SQLException e) {
  41. e.printStackTrace();
  42. }
  43. }
  44. }
  45. }

创建BlogDAO类操作数据库中的Blog表 

  1. public class BlogDAO {
  2. //获取博客表中的所有博客信息
  3. public List<Blog> getAllBlogs() {
  4. List<Blog> list = new LinkedList<>();
  5. Connection connection = null;
  6. PreparedStatement statement = null;
  7. ResultSet resultSet = null;
  8. try {
  9. connection = DBUtil.getConnection();
  10. String sql = "select * from blog order by postTime desc";
  11. statement = connection.prepareStatement(sql);
  12. resultSet = statement.executeQuery();
  13. while(resultSet.next()){
  14. Blog blog = new Blog();
  15. blog.setBlogId(resultSet.getInt("blogId"));
  16. String content = resultSet.getString("content");
  17. if(content.length() > 50){
  18. content = content.substring(0,50);
  19. }
  20. blog.setContent(content);
  21. blog.setTitle(resultSet.getString("title"));
  22. blog.setUserId(resultSet.getInt("userId"));
  23. blog.setPostTime(resultSet.getTimestamp("postTime"));
  24. list.add(blog);
  25. }
  26. } catch (SQLException e) {
  27. e.printStackTrace();
  28. }finally {
  29. DBUtil.closeResource(connection,statement,resultSet);
  30. }
  31. return list;
  32. }
  33. //获取指定id的博客
  34. public Blog getBlog(int blogId) {
  35. Connection connection = null;
  36. PreparedStatement statement = null;
  37. ResultSet resultSet = null;
  38. try {
  39. connection = DBUtil.getConnection();
  40. String sql = "select * from blog where userId = ?";
  41. statement = connection.prepareStatement(sql);
  42. statement.setInt(1,blogId);
  43. resultSet = statement.executeQuery();
  44. Blog blog = new Blog();
  45. if(resultSet.next()) {
  46. blog.setBlogId(resultSet.getInt("blogId"));
  47. blog.setContent(resultSet.getString("content"));
  48. blog.setTitle(resultSet.getString("title"));
  49. blog.setUserId(resultSet.getInt("userId"));
  50. blog.setPostTime(resultSet.getTimestamp("postTime"));
  51. return blog;
  52. }
  53. } catch (SQLException e) {
  54. e.printStackTrace();
  55. } finally {
  56. DBUtil.closeResource(connection,statement,resultSet);
  57. }
  58. return null;
  59. }
  60. //插入一篇博客
  61. public void addBlog(Blog blog) throws SQLException {
  62. Connection connection = null;
  63. PreparedStatement statement = null;
  64. try {
  65. connection = DBUtil.getConnection();
  66. String sql = "insert into blog values(null,?,?,?,now())";
  67. statement = connection.prepareStatement(sql);
  68. statement.setString(1,blog.getTitle());
  69. statement.setString(2, blog.getContent());
  70. statement.setInt(3,blog.getUserId());
  71. statement.executeUpdate();
  72. } catch (SQLException e) {
  73. e.printStackTrace();
  74. } finally {
  75. DBUtil.closeResource(connection,statement,null);
  76. }
  77. }
  78. //删除一篇博客
  79. public void deleteBlog(int blogId) throws SQLException {
  80. Connection connection = null;
  81. PreparedStatement statement = null;
  82. try {
  83. connection = DBUtil.getConnection();
  84. String sql = "delete from blog where userId = ?";
  85. statement = connection.prepareStatement(sql);
  86. statement.setInt(1,blogId);
  87. statement.executeUpdate();
  88. } catch (SQLException e) {
  89. e.printStackTrace();
  90. } finally {
  91. DBUtil.closeResource(connection,statement,null);
  92. }
  93. }
  94. }

创建UserDAO类操作数据库中的user表 

  1. public class UserDAO {
  2. //通过用户名查询用户信息
  3. public User getUserByName(String name){
  4. Connection connection = null;
  5. PreparedStatement statement = null;
  6. ResultSet resultSet = null;
  7. try {
  8. connection = DBUtil.getConnection();
  9. String sql = "select * from user where userName = ?";
  10. statement = connection.prepareStatement(sql);
  11. statement.setString(1,name);
  12. resultSet = statement.executeQuery();
  13. if(resultSet.next()){
  14. User user = new User();
  15. user.setUserId(resultSet.getInt("userId"));
  16. user.setUserName(resultSet.getString("userName"));
  17. user.setPassword(resultSet.getString("password"));
  18. return user;
  19. }
  20. } catch (SQLException e) {
  21. e.printStackTrace();
  22. } finally {
  23. DBUtil.closeResource(connection,statement,resultSet);
  24. }
  25. return null;
  26. }
  27. //通过id查询用户信息
  28. public User getUserById(int userId){
  29. Connection connection = null;
  30. PreparedStatement statement = null;
  31. ResultSet resultSet = null;
  32. try {
  33. connection = DBUtil.getConnection();
  34. String sql = "select * from user where userId = ?";
  35. statement = connection.prepareStatement(sql);
  36. statement.setInt(1,userId);
  37. resultSet = statement.executeQuery();
  38. if(resultSet.next()){
  39. User user = new User();
  40. user.setUserId(resultSet.getInt("userId"));
  41. user.setUserName(resultSet.getString("userName"));
  42. user.setPassword(resultSet.getString("password"));
  43. return user;
  44. }
  45. } catch (SQLException e) {
  46. e.printStackTrace();
  47. } finally {
  48. DBUtil.closeResource(connection,statement,resultSet);
  49. }
  50. return null;
  51. }
  52. //删除用户
  53. public void deleteUser(int userId) throws SQLException {
  54. Connection connection = null;
  55. PreparedStatement statement = null;
  56. try {
  57. connection = DBUtil.getConnection();
  58. String sql = "delete from user where userId = ?";
  59. statement = connection.prepareStatement(sql);
  60. statement.setInt(1,userId);
  61. statement.executeUpdate();
  62. } catch (SQLException e) {
  63. e.printStackTrace();
  64. } finally {
  65. DBUtil.closeResource(connection,statement,null);
  66. }
  67. }
  68. }

五、实现具体功能 

1、实现博客列表页

约定前后端交互接口

  1. //请求
  2. GET/blog
  3. //响应
  4. {
  5. {
  6. blogId:xx;
  7. title:xxx;
  8. content:xxxx;
  9. userId:xx;
  10. postTime:xxx;
  11. },
  12. {
  13. blogId:xx;
  14. title:xxx;
  15. content:xxxx;
  16. userId:xx;
  17. postTime:xxx;
  18. },
  19. ……
  20. }

服务器端 

重写doGet方法来获取数据库中的博客列表,设置响应格式为Json,字符集为utf8,先定义一个Json对象objectMapper,然后利用blogDAO对象从数据库中获取到所有的博客,并将其存到List中,然后利用Json对象将其转换成字符串,并写进响应中。

  1. //获取数据库中的博客列表
  2. @Override
  3. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  4. ObjectMapper objectMapper = new ObjectMapper();
  5. //设置响应格式
  6. resp.setContentType("application/json;charset=utf8");
  7. BlogDAO blogDAO = new BlogDAO();
  8. List<Blog> blogs = blogDAO.getAllBlogs();
  9. //将blogs对象装成Json格式的字符串
  10. String respJson = objectMapper.writeValueAsString(blogs);
  11. resp.getWriter().write(respJson);
  12. }

客户端 

页面加载的时候利用ajax访问服务器,获取到数据库中的博客列表,因为博客列表的数目不确定,就需要构造div,对body进行遍历,向div中添加各种元素。

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>blog-list</title>
  6. <link rel="stylesheet" href="common.css">
  7. <link rel="stylesheet" href="container.css">
  8. </head>
  9. <body>
  10. <div class="nav">
  11. <img src="logo.jpg">
  12. <span class="name">博客系统</span>
  13. <span class="blank"></span>
  14. <a href="#">主页</a>
  15. <a href="#">写博客</a>
  16. <a href="#">注销</a>
  17. </div>
  18. <div class="container">
  19. <div class="left">
  20. <div class="card">
  21. <img class="avatar" src="x.jpg" >
  22. <h3>小郭同学</h3>
  23. <a class="gitee" href="#"> gitee地址</a>
  24. <div class="counter">
  25. <span>文章</span>
  26. <span>专栏</span>
  27. </div>
  28. <div class="counter">
  29. <span>6</span>
  30. <span>2</span>
  31. </div>
  32. </div>
  33. </div>
  34. <div class="right">
  35. <!--<div class="blog">
  36. <div class="title">&lt;!&ndash;第一篇博客&ndash;&gt;</div>
  37. <div class="time">&lt;!&ndash;2022-6-09&ndash;&gt;</div>
  38. <div class="desc">&lt;!&ndash; Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium error esse impedit magni placeat possimus repellendus veniam, veritatis voluptas? Cum deserunt explicabo neque non placeat quaerat quam? At, blanditiis, non!&ndash;&gt;</div>
  39. <a class="a" href="#">查看全文</a>
  40. </div>-->
  41. </div>
  42. </div>
  43. <script src="https://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
  44. <script>
  45. //在页面加载的时候,利用ajax向服务器发送请求,获取到博客列表信息后,在页面进行显示
  46. function getBlogList(){
  47. $.ajax({
  48. type:'get',
  49. url:'blog',
  50. success:function(body){
  51. //获取到的body是JS对象的数组,因为数组大小每次可能都不一样,就需要构造div
  52. let rightDiv = document.querySelector('.right');
  53. for(let blog of body){
  54. let blogDiv = document.createElement('div');
  55. blogDiv.className = 'blog';
  56. let titleDiv = document.createElement('div');
  57. titleDiv.className = 'title';
  58. titleDiv.innerHTML = blog.title;
  59. blogDiv.appendChild(titleDiv);
  60. let postTimeDiv = document.createElement('div');
  61. postTimeDiv.className = 'postTime';
  62. postTimeDiv.innerHTML = blog.postTime;
  63. blogDiv.appendChild(postTimeDiv);
  64. let descDiv = document.createElement('div');
  65. descDiv.className = 'desc';
  66. descDiv.innerHTML = blog.content;
  67. blogDiv.appendChild(descDiv);
  68. let a = document.createElement('a');
  69. a.innerHTML = '查看全文';
  70. a.href = 'blog-detail.html?blogId='+blog.blogId;
  71. blogDiv.appendChild(a);
  72. rightDiv.appendChild(blogDiv);
  73. }
  74. },
  75. error:function(){
  76. alert('获取博客列表失败')
  77. }
  78. })
  79. };
  80. getBlogList();
  81. </script>
  82. </body>
  83. </html>

2、实现博客详情页 

约定前后端交互接口

  1. //请求
  2. GET/blog?blogId=1
  3. //响应
  4. HTTP/1.1 200 OK
  5. Content-Type:application/json
  6. {
  7. blogId:xx;
  8. title:xxx;
  9. content:xxxx;
  10. userId:xx;
  11. postTime:xxx;
  12. }

服务器端 

可以在实现博客列表详情页列表的服务器端代码进行扩充,首先查看请求参数中是否有blogId,若有则表示是指定一篇博客,就利用BlogDAO对象获取到指定的博客,然后写到响应中。

  1. @WebServlet("/blog")
  2. public class BlogServlet extends HttpServlet {
  3. //获取数据库中的博客列表
  4. @Override
  5. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  6. ObjectMapper objectMapper = new ObjectMapper();
  7. //设置响应格式
  8. resp.setContentType("application/json;charset=utf8");
  9. BlogDAO blogDAO = new BlogDAO();
  10. String result = req.getParameter("blogId");
  11. if(result == null){
  12. List<Blog> blogs = blogDAO.getAllBlogs();
  13. //将blogs对象装成Json格式的字符串
  14. String respJson = objectMapper.writeValueAsString(blogs);
  15. resp.getWriter().write(respJson);
  16. }else{
  17. Blog blog = blogDAO.getBlog(Integer.parseInt(result));
  18. String respJson = objectMapper.writeValueAsString(blog);
  19. resp.getWriter().write(respJson);
  20. }
  21. }
  22. }

客户端 

查看全文时就会跳转到博客详情页,利用ajax来处理响应,对于content由于在编辑博客时用的markdown字符串进行编辑的,但是展示时需要渲染后的结果,就需要利用引入editor依赖来完成。

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Blog-detail</title>
  6. <link rel="stylesheet" href="common.css">
  7. <link rel="stylesheet" href="container.css">
  8. <!-- 引入 editor.md 的依赖 -->
  9. <link rel="stylesheet" href="editor.md/css/editormd.min.css" >
  10. <script src="js/jquery.min.js"></script>
  11. <script src="editor.md/lib/marked.min.js"></script>
  12. <script src="editor.md/lib/prettify.min.js"></script>
  13. <script src="editor.md/editormd.js"></script>
  14. </head>
  15. <body>
  16. <div class="nav">
  17. <img src="logo.jpg">
  18. <span class="name">博客系统</span>
  19. <span class="blank"></span>
  20. <a href="#">主页</a>
  21. <a href="#">写博客</a>
  22. <a href="#">注销</a>
  23. </div>
  24. <div class="container">
  25. <div class="left">
  26. <div class="card">
  27. <img class="avatar" src="x.jpg" >
  28. <h3>小郭同学</h3>
  29. <a class="gitee" href="#"> gitee地址</a>
  30. <div class="counter">
  31. <span>文章</span>
  32. <span>专栏</span>
  33. </div>
  34. <div class="counter">
  35. <span>6</span>
  36. <span>2</span>
  37. </div>
  38. </div>
  39. </div>
  40. <div class="right">
  41. <div class="blog">
  42. <h3 class="title"></h3>
  43. <div class="postTime"></div>
  44. <div id="desc">
  45. </div>
  46. <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
  47. <script>
  48. function getBlog(){
  49. //在页面加载的时候,利用ajax向服务器发送请求,获取到博客列表信息后,在页面进行显示
  50. $.ajax({
  51. type:'get',
  52. //表示blog=blogId
  53. url:'blog'+location.search,
  54. success:function(body){
  55. let h3 = document.querySelector(".blog>h3");
  56. h3.innerHTML = body.title;
  57. let postTime = document.querySelector(".postTime");
  58. postTime.innerHTML = body.postTime;
  59. //由于在编辑博客时用的markdown字符串进行编辑的,但是展示时需要渲染后的结果
  60. // let content = document.querySelector('.desc');
  61. // content.innerHTML = body.content;
  62. editormd.markdownToHTML('desc', {
  63. markdown: body.content
  64. });
  65. },
  66. error:function(){
  67. alert("查看全文失败!");
  68. }
  69. });
  70. }
  71. getBlog();
  72. </script>
  73. </body>
  74. </html>

 3、实现登录页

 约定前后端交互接口

使用form表单来进行提交

  1. //请求
  2. POST/login
  3. Content-Type:application/x-www-form-urlencoded
  4. username=?&password=?
  5. //响应
  6. HTTP/1.1 302
  7. Location:blog_list.html

服务器端 

先将请求和响应都按照utf8进行解析避免出现乱码,然后获取到请求中的userName和password判断是否与数据库匹配,若匹配就创建会话跳转到博客列表页。

  1. @WebServlet("/login")
  2. public class LoginServlet extends HttpServlet {
  3. @Override
  4. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  5. req.setCharacterEncoding("utf8");
  6. resp.setCharacterEncoding("utf8");
  7. resp.setContentType("text/html;charset=utf8");
  8. String userName = req.getParameter("userName");
  9. String password = req.getParameter("password");
  10. if(userName == null || "".equals(userName) || password == null || "".equals(password)){
  11. resp.getWriter().write("用户名或密码不能为空");
  12. return;
  13. }
  14. UserDAO userDAO = new UserDAO();
  15. User user = userDAO.getUserByName(userName);
  16. if(user != null && user.getPassword().equals(password)){
  17. //创建会话
  18. HttpSession session = req.getSession(true);
  19. //将信息存储到绘画中
  20. session.setAttribute("user",user);
  21. //返回重定向报文,跳转到详情页
  22. resp.sendRedirect("blog-list.html");
  23. }else{
  24. resp.getWriter().write("用户名或密码错误");
  25. }
  26. }
  27. }

客户端 

利用form表单进行提交。

  1. <form action="login" method="post">
  2. <div class="row">
  3. <span>用户名</span>
  4. <span><input class="input" type="text" name="userName"></span>
  5. </div>
  6. <div class="row">
  7. <span>密码</span>
  8. <span><input class="input" type="password" name="password"></span>
  9. </div>
  10. <div class="submit">
  11. <input type="submit" id="submit" value="提交">
  12. </div>
  13. </form>

4、实现强制要求登陆 

对于博客列表页和博客详情页等都需要在登录成功的基础上来进行后序的操作。

约定前后端交互接口 

登录状态就返回当前用户的信息,未登录就返回userId为0的对象。

  1. //请求
  2. GET/login
  3. //响应
  4. HTTP/1.1 200 OK
  5. Content-Type:application/json
  6. {
  7. userId:xx,
  8. userName
  9. }

服务器端 

先判断是否创建会话,再判断会话中是否存在user对象,两种情况等都满足表示已经登录,否则就是未登录状态。

  1. //获取当前的登录状态
  2. @Override
  3. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  4. ObjectMapper objectMapper = new ObjectMapper();
  5. resp.setContentType("application/json;charset=utf8");
  6. HttpSession session = req.getSession(false);
  7. User user = new User();
  8. if(session == null){
  9. //未创建会话,表示未登录
  10. resp.getWriter().write(objectMapper.writeValueAsString(user));
  11. return;
  12. }
  13. user = (User)session.getAttribute("user");
  14. if(user == null){
  15. //会话中没有user对象
  16. user = new User();
  17. resp.getWriter().write(objectMapper.writeValueAsString(user));
  18. return;
  19. }
  20. //将密码信息不返回给前端
  21. user.setPassword("");
  22. resp.getWriter().write(objectMapper.writeValueAsString(user));
  23. }

客户端 

在博客列表页和详情页等加入该方法来判断是否登录,若未登录就跳转到登录页面进行登录。

  1. //获取当前登录状态
  2. function getUserInfo(pageName){
  3. $.ajax({
  4. type:'get',
  5. url:'login',
  6. success:function(body){
  7. //判定body中的user对象是否有效
  8. if(body.userId && body.userId > 0){
  9. //表示登录成功,暂时不做处理
  10. }else{
  11. alert("您当前尚未登录");
  12. //跳转到登录页
  13. location.assign('blog-login.html');
  14. }
  15. },
  16. error:function(){
  17. alert("您当前尚未登录");
  18. //跳转到登录页
  19. location.assign('blog-login.html');
  20. }
  21. });
  22. }

5、实现显示用户信息 

在登录之后,博客详情页能显示当前作者的个人信息。 

进入博客详情页之后能显示作者的个人信息。  

约定前后端交互接口 

  1. //请求
  2. GET/user
  3. //响应
  4. {
  5. userId:xx,
  6. userName:xxx
  7. }
  8. //请求
  9. GET/user?userId=xx
  10. //响应
  11. {
  12. userId:xx,
  13. userName:xxx
  14. }

服务器端

在数据库中先得到当前博客的id,再获取到其作者信息。

  1. @WebServlet("/authorInfo")
  2. public class AuthorServlet extends HttpServlet {
  3. @Override
  4. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  5. resp.setContentType("application/json;charset=utf8");
  6. //获取到指定博客的作者信息
  7. String param = req.getParameter("blogId");
  8. if (param == null || "".equals(param)) {
  9. resp.getWriter().write("{\"ok\":false,\"reason:\":\"参数缺失!\"}");
  10. return;
  11. }
  12. BlogDAO blogDAO = new BlogDAO();
  13. Blog blog = blogDAO.getBlog(Integer.parseInt(param));
  14. if(blog == null){
  15. resp.getWriter().write("{\"ok\":false,\"reason:\":\"要查询的博客不存在!\"}");
  16. return;
  17. }
  18. UserDAO userDAO = new UserDAO();
  19. User author = userDAO.getUserById(blog.getUserId());
  20. if(author == null){
  21. resp.getWriter().write("{\"ok\":false,\"reason:\":\"要查询的用户不存在!\"}");
  22. return;
  23. }
  24. ObjectMapper objectMapper = new ObjectMapper();
  25. author.setPassword("");
  26. resp.getWriter().write(objectMapper.writeValueAsString(author));
  27. }
  28. }

客户端

只需要在登录成功时将用户名改成当前登录的用户名。

  1. function changeUserName(userName){
  2. let h3 = document.querySelector('.card>h3');
  3. h3.innerHTML = userName;
  4. }

在进入博客列表详情页时显示作者名。 

  1. function getAuthorInfo(user){
  2. $.ajax({
  3. type:'get',
  4. url:'authorInfo'+location.search,
  5. success:function(body){
  6. if(body.userName){
  7. changeUserName(body.userName);
  8. }else{
  9. alert("获取作者信息失败")
  10. }
  11. },
  12. error:function(){
  13. alert("获取作者信息失败")
  14. }
  15. });
  16. }

6、实现发布博客 

实现前后端交互接口

  1. //请求
  2. POST/blog
  3. Content-Type:application/x-www-form-urlencoded
  4. //响应
  5. HTTP/1.1 302
  6. Location:blog_list.html

服务器端 

先确保用户是登录状态,然后再确认发表的博客标题和内容都不能为空,然后将发表的博客插入到数据库中,页面跳转到博客列表页。

  1. //发表博客
  2. @Override
  3. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  4. req.setCharacterEncoding("utf8");
  5. resp.setCharacterEncoding("utf8");
  6. resp.setContentType("text/html;charset=utf8");
  7. ObjectMapper objectMapper = new ObjectMapper();
  8. HttpSession session = req.getSession(false);
  9. if(session == null){
  10. resp.getWriter().write("用户未登录");
  11. return;
  12. }
  13. User user = (User)session.getAttribute("user");
  14. if(user == null){
  15. resp.getWriter().write("用户未登录");
  16. return;
  17. }
  18. String title = req.getParameter("title");
  19. String content = req.getParameter("content");
  20. if(title == null || "".equals(title) || content == null || "".equals(title)){
  21. resp.getWriter().write("提交博客失败,缺少博客标题或内容");
  22. return;
  23. }
  24. Blog blog = new Blog();
  25. blog.setUserId(user.getUserId());
  26. blog.setTitle(title);
  27. blog.setContent(content);
  28. BlogDAO blogDAO = new BlogDAO();
  29. try {
  30. blogDAO.addBlog(blog);
  31. } catch (SQLException e) {
  32. e.printStackTrace();
  33. }
  34. resp.sendRedirect("blog-list.html");
  35. }

客户端 

利用form表单将内容进行提交。

  1. <form action="blog" method="post" style="height:100%">
  2. <div class="title">
  3. <input type="text" placeholder="在此处输入标题" name="title" id="title">
  4. <!-- <button>发布文章</button> -->
  5. <input type="submit" value="发布文章" id="submit">
  6. </div>
  7. <!-- 放置 md 编辑器 -->
  8. <div id="editor">
  9. <!-- 为了进行 form 的提交, 此处搞一个 textarea 多行编辑框, 借助这个编辑框来实现表单的提交 -->
  10. <!-- 可以设置 editor.md, 让编辑器把 markdown 内容也同步的保存到这个隐藏的 textarea 中, 从而可以进行 form 提交 -->
  11. <textarea name="content" style="display:none"></textarea>
  12. </div>
  13. </form>

7、删除博客 

约定前后端交互接口

  1. //请求
  2. GET/user?blogId=x
  3. //响应
  4. {
  5. userId:xx;
  6. userName:xxx;
  7. isYourBlog: 1, // 1 表示当前博客就是登陆者的博客. 0 表示当前博客不是登陆者的博客.
  8. }

服务器端 

先判断当是否为登录状态,然后判断当前作者与登录用户是否一致,若相同则在数据库中删除该博客,然后将页面跳转到博客列表页。

  1. @WebServlet("/blogDelete")
  2. public class DeleteBlogServlet extends HttpServlet {
  3. @Override
  4. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  5. resp.setContentType("application/json;charset=utf8");
  6. HttpSession session = req.getSession(false);
  7. if(session == null){
  8. resp.getWriter().write("用户未登录");
  9. return;
  10. }
  11. User user = (User)session.getAttribute("user");
  12. if (user == null) {
  13. resp.getWriter().write("用户未登录");
  14. return;
  15. }
  16. String blogId = req.getParameter("blogId");
  17. if(blogId == null || "".equals(blogId)){
  18. resp.getWriter().write("博客编号有误");
  19. return;
  20. }
  21. BlogDAO blogDAO = new BlogDAO();
  22. Blog blog = blogDAO.getBlog(Integer.parseInt(blogId));
  23. if(blog == null || "".equals(blog)){
  24. resp.getWriter().write("待删除的博客不存在");
  25. return;
  26. }
  27. if(user.getUserId() != blog.getUserId()){
  28. resp.getWriter().write("不是本博客的作者,无法删除");
  29. return;
  30. }
  31. try {
  32. blogDAO.deleteBlog(Integer.parseInt(blogId));
  33. } catch (SQLException e) {
  34. e.printStackTrace();
  35. }
  36. resp.sendRedirect("blog-list.html");
  37. }
  38. }

客户端 

在列表详情页如果判断当前的作者是正在登录的用户,就新增一个删除超链接,可以进行删除。

  1. function getAuthorInfo(user){
  2. $.ajax({
  3. type:'get',
  4. url:'authorInfo'+location.search,
  5. success:function(body){
  6. if(body.userName){
  7. changeUserName(body.userName);
  8. if(body.userName == user.userName){
  9. let navDiv = document.querySelector('.nav');
  10. let a = document.createElement('a');
  11. a.innerHTML='删除';
  12. a.href = 'blogDelete' +location.search;
  13. navDiv.appendChild(a);
  14. }
  15. }else{
  16. alert("获取作者信息失败")
  17. }
  18. },
  19. error:function(){
  20. alert("获取作者信息失败")
  21. }
  22. });
  23. }

8、实现注销功能 

约定前后端交互接口

  1. //请求
  2. GET/logout
  3. //响应
  4. HTTP/1.1 302
  5. Location:login.html

服务器端 

先确认是否创建会话以确保登录状态,然后删除会话信息,并将登录的用户从数据库中删除,注销后跳转到登录页面。

  1. @WebServlet("/logout")
  2. public class LogoutServlet extends HttpServlet {
  3. @Override
  4. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  5. resp.setContentType("application/json;charset=utf8");
  6. HttpSession session = req.getSession(false);
  7. if(session == null){
  8. resp.getWriter().write("用户未登录");
  9. return;
  10. }
  11. User user = (User)session.getAttribute("user");
  12. //删除会话信息
  13. session.removeAttribute("user");
  14. UserDAO userDAO = new UserDAO();
  15. try {
  16. userDAO.deleteUser(user.getUserId());
  17. System.out.println(user.getUserId());
  18. } catch (SQLException e) {
  19. e.printStackTrace();
  20. }
  21. resp.sendRedirect("blog-login.html");
  22. }
  23. }

客户端 

 将注销超链接的href修改为logout。

<a href="logout">注销</a>

六、效果展示 

 

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/513044
推荐阅读
相关标签
  

闽ICP备14008679号