文章目录
- 教你手把手完成博客系统(三)
- 7.实现显示用户信息
- 1.约定前后端交互接口
- 2.前端通过ajax发起请求
- 3.服务器处理请求
- 8.实现退出登录
- 1.约定前后端的接口
- 2.前端发起请求
- 3.服务器处理请求
- 9.实现发布博客
- 1.约定前后端的交互接口
- 2.前端构造请求
- 3.服务器处理请求
教你手把手完成博客系统(三)
源码在文末~
7.实现显示用户信息
-
在博客列表页获取到是那个用户登录的
-
在博客详情页获取到是哪个用户书写的
1.约定前后端交互接口
//博客列表页
//请求
GET /userInfo
//响应
HTTP/1.1 200 OK
application/json
{
userId:1
username:"zhangsan"
}
//博客详情页
//请求
GET /authorInfo?blogId=1
//响应
HTTP/1.1 200 OK
application/json
{
userId:1
username:"zhangsan"
}
2.前端通过ajax发起请求
//定义一个函数,获取当前登录的用户信息
function getUserInfo(){
$.ajax({
type:'get',
url:'userInfo',
success:function(body){
//把拿到的相应数据,显示在页面上
let h3 = document.querySelector('.card h3');
h3.innerHTML=user.username;
}
})
}
getUserInfo();
function getAuthorInfo() {
$.ajax({
type: 'get',
url: 'getAuthorInfo' + location.search,
success: function (user) {
let h3 = document.querySelector('.card h3');
h3.innerHTML=user.username;
}
});
}
getAuthorInfo()
3.服务器处理请求
package servlet;
import com.fasterxml.jackson.databind.ObjectMapper;
import model.*;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
/**
* Created with IntelliJ IDEA.
* Description:
* User: Lenovo
* Author: Weng-Jiaming
* Date: 2024-05-22
* Time: 21:02
*/
@WebServlet("/html/authorInfo")
public class AuthorInfoServlet extends HttpServlet {
private ObjectMapper objectMapper = new ObjectMapper();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.先拿到请求中的blogId
String blogId = req.getParameter("blogId");
if (blogId == null) {
resp.setContentType("text/html;charset=utf8");
resp.getWriter().write("请求中缺少blogId");
return;
}
//2.在blog表中,查询到对应的blog对象
BlogDao blogDao = new BlogDao();
Blog blog = blogDao.getBlog(Integer.parseInt(blogId));
if (blog == null) {
resp.setContentType("text/html;charset=utf8");
resp.getWriter().write("blogId没有找到");
return;
}
//3.根据blog对象中的userId,从user表中查到对应的作者
UserDao userDao = new UserDao();
User user = userDao.getUserById(blog.getUserId());
if (user == null) {
resp.setContentType("text/html;charset=utf8");
resp.getWriter().write("userId没有找到");
return;
}
//4.把user对象返回到浏览器
user.setPassword("");
String respJson = objectMapper.writeValueAsString(user);
resp.setContentType("application/json;charset=utf8");
resp.getWriter().write(respJson);
}
}
package servlet;
import com.fasterxml.jackson.databind.ObjectMapper;
import model.User;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
/**
* Created with IntelliJ IDEA.
* Description:
* User: Lenovo
* Author: Weng-Jiaming
* Date: 2024-05-22
* Time: 20:13
*/
@WebServlet("/html/userInfo")
public class UserInfoServlet extends HttpServlet {
private ObjectMapper objectMapper = new ObjectMapper();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//从会话中,拿到用户信息进行返回
HttpSession session = req.getSession(false);
if (session == null) {
//未登录
resp.setContentType("text/html;charset=utf8");
resp.getWriter().write("当前用户未登录");
return;
}
User user = (User) session.getAttribute("user");
if (user==null){
//未登录
resp.setContentType("text/html;charset=utf8");
resp.getWriter().write("当前用户未登录");
return;
}
//避免返回密码等安全信息
user.setPassword("");
//两个都有,把user对象转成json,返回给浏览器
String respJson = objectMapper.writeValueAsString(user);
resp.setContentType("application/json;charset=utf8");
resp.getWriter().write(respJson);
}
}
8.实现退出登录
在这几个页面的导航栏中,都有“注销”按钮
通过点击,触发GET请求,服务器会把会话里的user这个Attribute进行删除
HttpSession session = req.getSession(false);
if (session == null) {
//未登录
resp.setContentType("text/html;charset=utf8");
resp.getWriter().write("当前用户未登录");
return;
}
User user = (User) session.getAttribute("user");
if (user == null) {
//未登录
resp.setContentType("text/html;charset=utf8");
resp.getWriter().write("当前用户未登录");
return;
}
在判定用户是否登录的逻辑中,要同时验证 会话存在 和 user这个Attributey也存在。只要破坏一个,就可以使登录状态发生改变。通过removeAttribute这样的方法,可以将user这个Attributey删除
1.约定前后端的接口
//请求
GET /logout
//响应
直接重定向到博客登录页
HTTP/1.1 302
Location:login.html
2.前端发起请求
直接给这个a标签设置href属性
<a href="logout">注销</a>
3.服务器处理请求
package servlet;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
/**
* Created with IntelliJ IDEA.
* Description:
* User: Lenovo
* Author: Weng-Jiaming
* Date: 2024-05-22
* Time: 21:46
*/
@WebServlet("/html/logout")
public class LogoutServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.拿到session对象
HttpSession session = req.getSession(false);
if (session==null){
//如果不存在
resp.setContentType("text/html;charset=utf8");
resp.getWriter().write("当前您尚未登录");
return;
}
//2.把会话中的user的属性删除
session.removeAttribute("user");
//3.跳转到登录页
resp.sendRedirect("login.html");
}
}
9.实现发布博客
点击提交的时候,构造请求,把标题和正文都传输到服务器。服务器把这些数据都存入数据库
这里采用form构造
1.约定前后端的交互接口
//请求
POST /blog
Content-Type:x-www-form-urlencoded
title=这是标题&content=这是正文
//响应
HTTP/1.1 302
Location:blog_list.html
2.前端构造请求
<form action="blog" method="post">
<div class="title">
<input type="text" name="title">
<button>发布文章</button>
</div>
<div id="editor">
<!-- 这正文这里,用隐藏的textarea标签 -->
<!-- 多行编辑框 把name属性加到textarea上 -->
<textarea name="content" style="display: none;"></textarea>
</div>
</form>
let edit = editormd('editor', {
width: "90%",
height: "calc(100% - 60px)",
path: "./editor.md/lib/",
markdown: "###开始编写博客",
saveHTMLToTextarea:true
// 会把在编辑器中输入的内容,在textarea里也保存一份
})
3.服务器处理请求
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.读取请求的参数
req.setCharacterEncoding("utf8");
String title = req.getParameter("title");
String content = req.getParameter("content");
if (title == null || title.length() == 0 || content == null || content.length() == 0) {
resp.setContentType("text/html;charset=utf8");
resp.getWriter().write("当前标题或内容为空,无法发布");
return;
}
//2.构造blog对象
Blog blog = new Blog();
blog.setTitle(title);
blog.setContent(content);
//从会话中获取
HttpSession session = req.getSession(false);
if (session==null){
resp.setContentType("text/html;charset=utf8");
resp.getWriter().write("当前用户未登录");
return;
}
User user = (User) session.getAttribute("user");
if (user==null){
resp.setContentType("text/html;charset=utf8");
resp.getWriter().write("当前用户未登录");
return;
}
blog.setUserId(user.getUserId());
//3.插入到数据库中
BlogDao blogDao = new BlogDao();
blogDao.insert(blog);
//4.返回一个302重定向报文
resp.sendRedirect("blog_list.html");
}
查看源代码,请点击:博客系统完整代码
点击移步博客主页,欢迎光临~