一.设计数据库
1.创建数据库
create database if not exists java108_blog_system character set utf8;
drop table if exists user;
drop table if exists blog;
2.创建博客列表
create table blog(
blogId int primary key auto_increment,
title varchar(20),
content varchar(4006),
userId int,
postTime datetime
);
3.创建用户列表
create table user(
userId int primary key auto_increment,
username varchar(64) unique,
password varchar(64)
);
4.确认表创建成功
insert into user values(1,"zhangsan","123"),(2,"lisi","123");
insert into blog values(1,"这是我的第一篇博客","从今天开始我要好好写代码",1,"2024-07-14 19:00:00");
insert into blog values(2,"这是我的第二篇博客","从昨天开始我要好好写代码",2,"2024-07-14 19:00:01");
insert into blog values(3,"这是我的第三篇博客","从明天开始我要好好写代码",3,"2024-07-14 19:00:02");
二.封装数据库
创建包Dao用来放数据库代码
1.创建Dbuc类
数据库建立连接
package Dao;
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 Dbuc {
private static DataSource dataSource = null;
private static DataSource getDataSource(){
if(dataSource==null){
synchronized (Dbuc.class){
if(dataSource==null){
dataSource=new MysqlDataSource();
((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1/java108_blog_system?characterEncoding=utf8&useSSL=false");
((MysqlDataSource)dataSource).setUser("root");
// ((MysqlDataSource)dataSource).setUser("java108");
((MysqlDataSource)dataSource).setPassword("123456");
}
}
}
return dataSource;
}
public static Connection getConnect() throws SQLException {
return getDataSource().getConnection();
}
public static void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) throws SQLException {
if(resultSet!=null){
resultSet.close();
}
if(connection!=null){
connection.close();
}
if(preparedStatement!=null){
preparedStatement.close();
}
}
}
2.创建博客类
public class Blog {
public int blogId;
public String title;
public String content;
public int userId;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public Timestamp postTime;
@Override
public String toString() {
return "Blog{" +
"blogId=" + blogId +
", title='" + title + '\'' +
", content='" + content + '\'' +
", userId=" + userId +
", postTime=" + postTime +
'}';
}
}
3.创建用户类
package Dao;
public class User {
public int userId;
public String username;
public String password;
@Override
public String toString() {
return "User{" +
"userId=" + userId +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
4.封装博客增删查改
package Dao;
import javax.xml.transform.Result;
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 insert(Blog blog) throws SQLException {
Connection connection = Dbuc.getConnect();
String sql = "insert into blog values(null,?,?,?,now())";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,blog.title);
preparedStatement.setString(2,blog.content);
preparedStatement.setInt(3,blog.userId);
preparedStatement.executeUpdate();
Dbuc.close(connection,preparedStatement,null);
}
public List<Blog> getBlogs() throws SQLException {
List<Blog> list1= new ArrayList<>();
Connection connection = Dbuc.getConnect();
String sql = "select* from blog order by postTime desc";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
ResultSet resultSet= preparedStatement.executeQuery();
while(resultSet.next()){
Blog blog = new Blog();
blog.blogId = resultSet.getInt("blogId");
blog.title=resultSet.getString("title");
blog.content=resultSet.getString("content");
blog.userId=resultSet.getInt("userId");
blog.postTime=resultSet.getTimestamp("postTime");
list1.add(blog);
}
Dbuc.close(connection,preparedStatement,resultSet);
return list1;
}
public Blog getBlog(int blogId) throws SQLException {
Connection connection = Dbuc.getConnect();
String sql = "select* from blog where blogId=?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,blogId);
ResultSet resultSet= preparedStatement.executeQuery();
if(resultSet.next()){
Blog blog = new Blog();
blog.blogId = resultSet.getInt("blogId");
blog.title=resultSet.getString("title");
blog.content=resultSet.getString("content");
blog.userId=resultSet.getInt("userId");
blog.postTime=resultSet.getTimestamp("postTime");
return blog;
}
Dbuc.close(connection,preparedStatement,resultSet);
return null;
}
public void delete(int blogId) throws SQLException {
Connection connection = Dbuc.getConnect();
String sql = "delete from blog where blogId=?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,blogId);
preparedStatement.executeUpdate();
Dbuc.close(connection,preparedStatement,null);
}
}
5.封装用户类增删查改
package Dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDao {
public User getUserById(int userId) throws SQLException {
Connection connection = Dbuc.getConnect();
String sql = "select* from user where userId=?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,userId);
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
User user = new User();
user.userId=resultSet.getInt("userId");
user.password=resultSet.getString("password");
user.username=resultSet.getString("username");
return user;
}
Dbuc.close(connection,preparedStatement,resultSet);
return null;
}
public User getUserByName(String username) throws SQLException {
Connection connection = Dbuc.getConnect();
String sql = "select* from user where username=?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,username);
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
User user = new User();
user.userId=resultSet.getInt("userId");
user.password=resultSet.getString("password");
user.username=resultSet.getString("username");
return user;
}
Dbuc.close(connection,preparedStatement,resultSet);
return null;
}
}
三.博客详情页
package api;
import Dao.Blog;
import Dao.BlogDao;
import Dao.User;
import com.fasterxml.jackson.databind.ObjectMapper;
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;
import java.sql.SQLException;
import java.util.List;
@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 blogId = req.getParameter("blogId");
if(blogId==null){
List<Blog> blogs = null;
try {
blogs = blogDao.getBlogs();
} catch (SQLException e) {
throw new RuntimeException(e);
}
String res = objectMapper.writeValueAsString(blogs);
resp.setContentType("appliaction/jason;charset=utf8");
resp.getWriter().write(res);
}else{
Blog blog = null;
try {
blog = blogDao.getBlog(Integer.parseInt(blogId));
} catch (SQLException e) {
throw new RuntimeException(e);
}
String str = objectMapper.writeValueAsString(blog);
resp.setContentType("application/json;charset=utf8");
resp.getWriter().write(str);
}
}
如果前端没有传入指定id那么展示全部内容,如果传入指定id查询指定用户博客。
通过抓包观察:
2.检测用户是否登录
如果用户未登录是不能跳转到博客列表的页面
@Override
protected void doPost(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;
}
req.setCharacterEncoding("utf8");
String title = req.getParameter("title");
String content = req.getParameter("content");
if (title == null |