一.创建必要目录
创建webapp/WEB-INF/web.xml
web.xml:配置文件
api:存放前后端交互后端代码
model:用来存放数据库相关代码
db.sql:保存数据库操作代码
二.引入依赖
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
</web-app>
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>BlogSystem</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.14.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
</dependencies>
<!--打包格式-->
<packaging>war</packaging>
<build>
<!--包名-->
<finalName>BlogSystem</finalName>
</build>
</project>
三.数据库设计
对数据库相关代码有疑惑,可以看一看我的以前写的一篇博客
如何使用JDBC(java database connectivity)进行编译
1.对数据库DataSource实现封装,需要使用时才创建
实现DBUtil类
package model;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DBUtil {
private static DataSource dataSource = new MysqlDataSource();
static {
((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/blog_system?characterEncoding=utf8&useSSL=false");
((MysqlDataSource) dataSource).setUser("root");
((MysqlDataSource) dataSource).setPassword("111111");
}
public static Connection getConnection() throws SQLException {
return dataSource.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();
}
}
}
}
创建Blog,User类存放blog,user数据库表,对其相关属性进行Getter and Setter
Blog
package model;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
public class Blog {
private int blogId;
private String title;
private String content;
private Timestamp postTime;
private int userId;
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 Timestamp getPostTimestamp() {
return postTime;
}
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;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
}
User
package model;
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;
}
}
创建BlogDao和UserDao针对blog和user表进行数据库操作,增删改查
BlogDao
package model;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class BlogDao {
//添加博客
public void add(Blog blog) {
Connection connection = null;
PreparedStatement statement = null;
try {
//1.与数据库建立连接
connection = DBUtil.getConnection();
//2.构造SQL语句
String sql = "insert into blog values(null, ?, ?, ?, ? )";
statement = connection.prepareStatement(sql);
statement.setString(1, blog.getTitle());
statement.setString(2, blog.getContent());
statement.setTimestamp(3, blog.getPostTimestamp());
statement.setInt(4, blog.getUserId());
//3.执行SQL语句
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(connection, statement, null);
}
}
//在博客详情页中,根据博客ID查询博客
public Blog selectById(int blogId) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
// 1.和数据库建立连接
connection = DBUtil.getConnection();
// 2.构造 SQL
String sql = "select * from blog where blogId = ?";
statement = connection.prepareStatement(sql);
statement.setInt(1, blogId);
// 3.执行 SQL
resultSet = statement.executeQuery();
// 4.遍历结果集合. 由于 blogId 在 blog 表中是唯一主键只用一个使用if就行了
if (resultSet.next()) {
Blog blog = new Blog();
blog.setBlogId(resultSet.getInt("blogId"));
blog.setTitle(resultSet.getString("title"));
blog.setContent(resultSet.getString("content"));
blog.setPostTime(resultSet.getTimestamp("postTime"));
blog.setUserId(resultSet.getInt("userId"));
return blog;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 5. 释放必要的资源
DBUtil.close(connection, statement, resultSet);
}
return null;
}
//在博客列表页查询所有的博客
public List<Blog> selectAll() {
List<Blog> blogs = new ArrayList<>();
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
// 1.和服务器建立连接.
connection = DBUtil.getConnection();
// 2.构造 SQL 语句
String sql = "select * from blog order by postTime desc";
statement = connection.prepareStatement(sql);
// 3.执行 SQL
resultSet = statement.executeQuery();
// 4.遍历结果集合
while (resultSet.next()) {
Blog blog = new Blog();
blog.setBlogId(resultSet.getInt("blogId"));
blog.setTitle(resultSet.getString("title"));
String content = resultSet.getString("content");
if (content == null) {
content = "";
}
//博客列表页不需要显示全部博客
if (content.length() >= 100) {
content = content.substring(0, 100) + "...";
}
blog.setContent(content);
blog.setPostTime(resultSet.getTimestamp("postTime"));
blog.setUserId(resultSet.getInt("userId"));
blogs.add(blog);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(connection, statement, resultSet);
}
return blogs;
}
//删除指定博客
public void delete(int blogId) {
Connection connection = null;
PreparedStatement statement = null;
try {
// 1.和数据库建立连接.
connection = DBUtil.getConnection();
// 2.构造 SQL
String sql = "delete from blog where blogId = ?";
statement = connection.prepareStatement(sql);
statement.setInt(1, blogId);
// 3.执行 SQL
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 4.关闭资源
DBUtil.close(connection, statement, null);
}
}
}
UserDao
package model;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDao {
//根据 userId 来查用户信息
public User selectById(int userId) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
// 1.和数据库建立连接.
connection = DBUtil.getConnection();
// 2.构造 SQL
String sql = "select * from user where userId = ?";
statement = connection.prepareStatement(sql);
statement.setInt(1, userId);
// 3.执行 SQL
resultSet = statement.executeQuery();
// 4.遍历结果集合
if (resultSet.next()) {
User user = new User();
user.setUserId(resultSet.getInt("userId"));
user.setUsername(resultSet.getString("username"));
user.setPassword(resultSet.getString("password"));
return user;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(connection, statement, resultSet);
}
return null;
}
//在登录时根据用户名查询用户信息
public User selectByUsername(String username) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
// 1.和数据库建立连接.
connection = DBUtil.getConnection();
// 2.构造 SQL
String sql = "select * from user where username = ?";
statement = connection.prepareStatement(sql);
statement.setString(1, username);
// 3.执行 SQL
resultSet = statement.executeQuery();
// 4.遍历结果集合
if (resultSet.next()) {
User user = new User();
user.setUserId(resultSet.getInt("userId"));
user.setUsername(resultSet.getString("username"));
user.setPassword(resultSet.getString("password"));
return user;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(connection, statement, resultSet);
}
return null;
}
//注册用户
public void add(User user) {
Connection connection = null;
PreparedStatement statement = null;
try {
// 1.与数据库建立连接
connection = DBUtil.getConnection();
// 2.构造SQL语句
String sql = "insert into user values(null, ?, ?)";
statement = connection.prepareStatement(sql);
statement.setString(1, user.getUsername());
statement.setString(2, user.getPassword());
// 3.执行sql语句
statement.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
// 4.关闭资源
DBUtil.close(connection, statement, null);
}
}
//删除用户
public void delete(int userId) {
Connection connection = null;
PreparedStatement statement = null;
try {
// 1.与数据库建立连接
connection = DBUtil.getConnection();
// 2.构造SQL语句
String sql = "delete from user where userId = ?";
statement = connection.prepareStatement(sql);
statement.setInt(1, userId);
//3.执行SQL语句
statement.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
//4.关闭用户资源
DBUtil.close(connection, statement, null);
}
}
}
四.前后端交互实现
1..实现登录功能
@WebServlet("/login")
约定前后端交互接口
请求:POST url:login HTTP/1.1
响应:HTTP/1.1 200
前端代码实现
前端使用form标签
username=zuizuiyu&password=123
input中name对应qury string中username,password;
(如果是通过302跳转,前端必须使用form,而ajax收到302,不会进行页面跳转)
<form action="login" method="post">
<h3>登录</h3>
<div class="row">
<span>用户名</span>
<input type="text" id="username" placeholder="手机号/邮箱/用户名" name="username">
</div>
<div class="row">
<span>密码</span>
<input type="password" id="password" name="password">
</div>
<div class="row">
<input type="submit" id="submit" value="登录">
</div>
<div class="row">
<a href="./register.html">注册</a>
</div>
</form>
后端代码实现:
直接使用req.getParameter();获取query string的参数
验证通过后,利用session将user保存起来
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 设置请求的编码. 告诉 servlet 按照啥格式来理解请求
req.setCharacterEncoding("utf8");
// 设置响应的编码. 告诉 servlet 按照啥格式来构造响应
resp.setContentType("text/html;charset=utf8");
// 1.读取query string中的用户名和密码
String username = req.getParameter("username");
String password = req.getParameter("password");
if (username == null || "".equals(username) || password == null || "".equals(password)) {
// 登录失败!!
String html = "<h3>登录失败! 缺少 username 或者 password 字段</h3>";
resp.getWriter().write(html);
return;
}
// 2.读数据库, 看看用户名是否存在, 并且密码是否匹配
UserDao userDao = new UserDao();
User user = userDao.selectByUsername(username);
if (user == null) {
// 用户不存在.
String html = "<h3>登录失败! 用户名或密码错误</h3>";
resp.getWriter().write(html);
return;
}
if (!password.equals(user.getPassword())) {
// 密码不对
String html = "<h3>登录失败! 用户名或密码错误</h3>";
resp.getWriter().write(html);
return;
}
// 3. 用户名密码验证通过, 登录成功, 接下来就创建会话. 使用该会话保存用户信息.
HttpSession session = req.getSession(true);
session.setAttribute("user", user);
//将密码置空,防止在json字符串中获取到用户密码,保障安全
user.setPassword(" ");
// 4. 进行重定向. 跳转到博客列表页
resp.sendRedirect("blog_list.html?userId="+user.getUserId());
}
2.实现注册功能
@WebServlet("/register")
约定前后端交互接口
请求:POST url:register HTTP/1.1
响应:HTTP/1.1 302 Location: login.html,注册完跳转到登录页
前端代码实现:
<form action="register" method="post">
<h3>注册</h3>
<div class="row">
<span>用户名</span>
<input type="text" id="username" placeholder="手机号/邮箱/用户名" name="username">
</div>
<div class="row">
<span>密码</span>
<input type="password" id="password" name="password">
</div>
<div class="row">
<input type="submit" id="register" value="注册">
</div>
</form>
后端代码实现:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设立请求的字符集
req.setCharacterEncoding("utf8");
resp.setContentType("text/html; charset=utf-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
//注册用户名,密码不能为空
if(username == null || password == null ) {
String html = "<h3>用户名或密码不能为空</h3>";
resp.getWriter().write(html);
return;
}
//判断用户名是否存在数据库中
UserDao userDao = new UserDao();
if(userDao.selectByUsername("username") != null) {
String html = "<h3>用户已存在,请重新注册</h3>";
resp.getWriter().write(html);
return;
}
//将username和password加入数据库中
User user = new User();
user.setUsername(username);
user.setPassword(password);
userDao.add(user);
//创建session保存用户信息
HttpSession session = req.getSession(true);
session.setAttribute("user",user);
//防止密码泄露
user.setPassword(" ");
resp.sendRedirect("login.html");
}
3.实现博客列表页
@WebServlet("/blog")
约定前后端交互接口
请求:
GET URL:blog?userId=1 HTTP/1.1
响应:
HTTP/1.1 200
body:(json格式字符串)
[{"blogId":1,"title":"这是我的第一篇博客","content":"从今天开始我要认真敲代码","postTime":"2023-09-15 02:36:28","userId":1,"postTimestamp":1694759788000},
{"blogId":2,"title":"这是我的第二篇博客","content":"从昨天开始我要认真敲代码","postTime":"2023-09-15 02:36:28","userId":1,"postTimestamp":1694759788000},
{"blogId":3,"title":"这是我的第三篇博客","content":"从前天开始我要认真敲代码","postTime":"2023-09-15 02:36:28","userId":1,"postTimestamp":1694759788000}]
前端代码实现:
function getBlogs() {
$.ajax({
type: 'get',
url: 'blog',
success: function(body) {
//由于我引入了jquery 虽然响应的正文是一个 json 字符串,
//但是已经被jquery自动解析成js对象数组了.
// 直接 for 循环遍历即可.
let containerRight = document.querySelector('.container-right');
for (let blog of body) {
// 构造页面内容
// 构造整个博客 div
let blogDiv = document.createElement('div');
blogDiv.className = 'blog';
// 构造标题
let titleDiv = document.createElement('div');
titleDiv.className = 'title';
titleDiv.innerHTML = blog.title;
blogDiv.appendChild(titleDiv);
// 构造发布时间
let dateDiv = document.createElement('div');
dateDiv.className = 'date';
dateDiv.innerHTML = blog.postTime;
blogDiv.appendChild(dateDiv);
// 构造博客摘要
let descDiv = document.createElement('div');
descDiv.className = 'desc';
descDiv.innerHTML = blog.content;
blogDiv.appendChild(descDiv);
// 构造查看全文按钮
let a = document.createElement('a');
a.innerHTML = '查看全文 >>';
//点击之后能跳转到博客详情页.blogId知道是哪一篇博客
a.href = 'blog_detail.html?blogId=' + blog.blogId;
blogDiv.appendChild(a);
// 把 blogDiv 加到父元素中
containerRight.appendChild(blogDiv);
}
}
});
}
// 记得调用
getBlogs();
后端代码实现:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取query String中的blogId字段.
BlogDao blogDao = new BlogDao();
String blogId = req.getParameter("blogId");
if (blogId == null) {
//blogId不存在,说明这次请求是获取博客列表
List<Blog> blogs = blogDao.selectAll();
// 需要把blogs转成符合要求的json格式字符串.
String respJson = objectMapper.writeValueAsString(blogs);
resp.setContentType("application/json; charset=utf8");
resp.getWriter().write(respJson);
}
}
4,实现博客详情页
@WebServlet("/blog")
约定前后端交互接口
请求:
GET URL:blog_detail.html?blogId=1 HTTP/1.1
响应:
HTTP/1.1 200
body:
{"blogId":1,"title":"这是我的第一篇博客","content":"从今天开始我要认真敲代码","postTime":"2023-09-15 02:36:28","userId":1,"postTimestamp":1694759788000}
前端代码实现:
ajax利用location.search获取query string
function getBlogDetail(){
$.ajax({
type: 'get',
url: 'blog' + location.search,
success: function(body){
//通过blogservlet中的get方法传入json格式的blog
//此时body相当于blog;
//构造标题
let h3 = document.querySelector('.container-right h3');
h3.innerHTML = body.title;
//构造时间
let dateDiv = document.querySelector(".date");
dateDiv.innerHTML = body.postTime;
editormd.markdownToHTML('content',{
markdown: body.content
});
}
});
}
getBlogDetail();
后端代码实现:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 尝试获取一下query String中的 blogId.
BlogDao blogDao = new BlogDao();
String blogId = req.getParameter("blogId");
//根据blogId存不存在,判断响应写入是博客详情页,还是博客列表页
if (blogId == null) {
List<Blog> blogs = blogDao.selectAll();
// 需要把 blogs 转成符合要求的 json 格式字符串.
String respJson = objectMapper.writeValueAsString(blogs);
resp.setContentType("application/json; charset=utf8");
resp.getWriter().write(respJson);
} else {
Blog blog = blogDao.selectById(Integer.parseInt(blogId));
if (blog == null) {
System.out.println("当前 blogId = " + blogId + " 对应的博客不存在!");
}
String respJson = objectMapper.writeValueAsString(blog);
resp.setContentType("application/json; charset=utf8");
resp.getWriter().write(respJson);
}
}
5.实现强制登录功能以及用户名显示
@WebServlet("/login")
功能说明:在博客列表页,详情页,登录页加载时发送一个ajax请求,访问服务器,获取当前的登录状态,如果未登录强制跳转到登录页
在获取登录状态的同时,如果成功登陆会创建session存放user信息,利用session获取user,传入前端,在名称的对应标签通过body.username实现名字信息显示到界面上;
约定前后端交互接口:
请求:
GET URL:login HTP/1.1
响应:
HTTP/1.1 200
Content-Type: application/json;charset=utf8
未登录可以规定返回一个空的user
body:
{"userId":0,"username":null,"password":null}
前端代码实现:
function checkLogin() {
$.ajax({
type: 'get',
url: 'login',
success: function(body) {
if (body.userId && body.userId >= 0) {
// 登录成功!!
console.log("当前用户已经登录!!");
//把当前用户的名字显示到界面上.
let h3 = document.querySelector('.container-left .card h3');
h3.innerHTML = body.username;
} else {
// 当前未登录,强制跳转到登录页.
location.assign('login.html');
}
}
});
}
checkLogin();
后端代码实现:
在登录功能的实现时,每次成功登录创建一个新的session用来存放user
我们可以直接获取当前的session判断用户是否登录
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 user = new User();
String respJson = objectMapper.writeValueAsString(user);
resp.getWriter().write(respJson);
return;
}
User user = (User) session.getAttribute("user");
if (user == null) {
user = new User();
String respJson = objectMapper.writeValueAsString(user);
resp.getWriter().write(respJson);
return;
}
// 成功取出了 user 对象, 就直接返回给浏览器即可.可以实现用户名显示
String respJson = objectMapper.writeValueAsString(user);
resp.getWriter().write(respJson);
}
6.实现退出登入功能
@WebServlet("/logout")
约定前后端交互接口:
请求:
GET URL:logout HTTP/1.1
响应:
HTTP/1.1 302
location: login.html(跳转到登录页)
前端代码实现:
<a href="logout">退出登录</a>
后端代码实现:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession httpSession = req.getSession(false);
if (httpSession == null) {
// 未登录状态, 就直接提示出错.
resp.setContentType("text/html; charset=utf8");
resp.getWriter().write("当前未登录!");
return;
}
httpSession.removeAttribute("user");
resp.sendRedirect("login.html");
}
7.实现删除博客功能
@WebServlet("/blogDelete")
约定前后端交互接口:
请求:
GET URL:blogDelete?blogId HTTP/1.1
响应:
HTTP/1.1 302
Location: blog_list.html
前端代码实现:
function getUserInfo() {
$.ajax({
type: 'get',
url: 'login',
success: function(body) {
if (body.userId && body.userId > 0) {
// 获取服务器login的get方法传来的user
getAuthorInfo(body);
} else {
alert("当前未登录,请登录后访问");
// 当前未登录,强制跳转到登录页.
location.assign("login.html");
}
},
error:function() {
alert("当前未登录,请登录后访问");
location.assign("login.html");
}
});
}
getUserInfo();
//此处添加的参数user就是刚才从服务器拿到的当前登录用户的信息
function getAuthorInfo(user){
$.ajax({
type: 'get',
url: "author" + location.search,
success: function(body){
//判断一下用户是否存在
if(body.username){
//如果存在就设置上
let h3 = document.querySelector(".card h3");
h3.innerHTML = body.username;
//然后此时再判断当前的作者和登录的用户是不是同一个,如果是同一个的话,就可以在导航栏里面添加一个删除按键
if(user.username == body.username){
let navDiv = document.querySelector(".nav");
let a = document.createElement("a");
a.innerHTML = '删除';
//a的请求 路径加上要删除的文章id
a.href = "blogDelete" + location.search;
//然后再放到这个div里面
navDiv.appendChild(a);
}
}else{
//如果不存在就提示错误
console.log("获取作者信息失败!" + body.reason);
}
}
});
}
后端代码实现:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf8");
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;
}
//再通过取出这篇文章
String blogId = req.getParameter("blogId");
if(blogId == null || "".equals(blogId)){
//当前博客id不存在
resp.setContentType("text/html;charset=utf8");
resp.getWriter().write("当前blogId参数不正确不能删除!");
return;
}
//然后获取到要删除的博客信息
BlogDao blogDao = new BlogDao();
Blog blog = blogDao.selectById(Integer.parseInt(blogId));
//判断文章是否存在
if(blog == null) {
//当前博客不存在,无法删除
resp.setContentType("text/html;charset=utf8");
resp.getWriter().write("当前博客不存在不能删除!");
return;
}
//再判断当前博客作者和当前用户是不是同一个人
if(user.getUserId() != blog.getUserId()){
//不是同一个用户无法删除
resp.setContentType("text/html;charset=utf8");
resp.getWriter().write("当前登录的用户不是作者,没有权限删除!");
return;
}
//此时就可以进行删除了
blogDao.delete(Integer.parseInt(blogId));
//然后再重定向到博客列表页
resp.sendRedirect("blog_list.html");
}
8.实现删除用户功能
@WebServlet("/userDelete")
约定前后端接口
请求:
GET URL:userDelete HTTP/1.1
响应:
HTTP/1.1 302
Location: login.html(跳转到登陆页面)
前端代码实现:
在博客列表页添加注销功能
直接在导航栏添加个注销标签
function userDelete(user){
$.ajax({
type: 'get',
url: "blog" + location.search,
success: function(body){
let navDiv = document.querySelector(".nav");
let a = document.createElement("a");
a.innerHTML = '注销';
a.href = "userDelete"+location.search;
//然后再放到这个div里面
navDiv.appendChild(a);
}
});
}
userDelete();
后端代码实现
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//emmm,当前session已经保存了user,也可以不用传入userId,直接通过session获取user.getUserId就行
// req.setCharacterEncoding("utf8");
// resp.setContentType("text/html;charset=utf8");
// //获取userId;
// String userId = req.getParameter("userId");
// if(userId == null) {
// resp.getWriter().write("当前UserId参数不正确!");
// return;
// }
//根据userId获取User
// UserDao userDao = new UserDao();
// User user = userDao.selectById(Integer.parseInt(userId));
// if(user == null) {
// resp.getWriter().write("当前用户未登录");
// return;
// }
HttpSession httpSession = req.getSession(false);
if (httpSession == null) {
resp.setContentType("text/html; charset=utf8");
resp.getWriter().write("当前未登录, 无法删除用户!");
return;
}
User user = (User) httpSession.getAttribute("user");
UserDao userDao = new UserDao();
userDao.delete(user.getUserId());
//跳转到登录页
resp.sendRedirect("login.html");
}
待补充...
五.错误总结
出现服务器内部错误
找到代码对应位置
错误分析内部服务器出现错误,表示后端代码出现问题
我们可以知道userId在query string可以正常显示
难道String userId = req.getParameter("userId");没有获取到userId吗?
debug一下
发现获取到userId
看一下是不是数据库操作的问题
跳转到userDao.delete
发现缺少
statement = connection.prepareStatement(sql);
emm( •̀ ω •́ )y,错误比较简单