发布博客
在原来的编辑页面点击发布文章按钮,是不会有什么效果的。
这是因为此时还不能实现前后端的交互。
1. 约定前后端交互接口
请求使用 POST,路径是 /blog
title=这是标题&content=这是正文
请求中要有 body,按照 form 表单的方式添加进去。
响应使用 HTTP/1.1 302
跳转到列表页:Location: blog.list.html
在一篇博客当中,它有 blogId、title、content、userId、postTime 属性。
只有 title 和 content 是需要自己获取的,blogId 是自增主键,数据库会自己生成;
userId 是作者信息,看提交博客的用户是谁,直接从会话中拿即可;
postTime 是当前的时间。
2. 服务器代码
在之前实现好的 BlogServlet 类中重写一个 doPost 方法。
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 发布博客
// 读取请求,构造 Blog 对象,插入数据库即可
HttpSession httpSession = req.getSession(false);
if (httpSession == null) {
// 未登录
resp.setContentType("text/html; charset=utf8");
resp.getWriter().write("当前未登录,无法发布博客!!!");
return;
}
User user =