目录
准备工作
创建用户类博客类与连接数据库
创建博客类
创建用户类
创建连接数据库工具类
实现对数据库数据博客的操作
实现对数据库用户的操作
创建数据库语句
登录页面
前端
后端
博客列表
前端
注销登录
写入数据
判断用户是否登录
替换页面用户昵称
后端
处理注销登录 LogoutServlet/doGet
处理获取所有博客 BlogServlet/doGet
处理判断用户是否登录 loginServlet/doGet
处理替换页面用户昵称 UserinfoServlet/doGet
博客详情页
前端
注销登录
查询博客
判断用户是否登录
将博客详情页昵称替换为当前博客作者昵称/是否显示删除博客
后端
处理注销登录 LogoutServlet/doGet
处理查询博客 BlogServlet/doGet
处理判断用户是否登录 LoginServlet/doGet
处理将博客详情页昵称替换为当前博客作者昵称/是否显示删除博客 UserinfoServlet/doGet
博客编辑页
前端
后端 BlogServlet/doPost
部署
准备工作
下载jdk
下载tomcat
加权限
安装mysql
使用maven打包
访问
在main下创建webapp文件夹下再创建WEB-INF文件夹下再创建web.xml文件
web.xml
Archetype Created Web Application 需要用到
这些均在Maven Repository: Search/Browse/Explore (mvnrepository.com)网址内下载
之后复制代码粘贴到pom.xml下的
javax.servlet javax.servlet-api 3.1.0 provided com.fasterxml.jackson.core jackson-databind 2.13.5 com.mysql mysql-connector-j 8.0.33 war blog_system 博客包含
之后ALT+Insert生成Get和Set方法(时间的get方法有所改变,需要格式化为日期格式)
package model; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.SimpleTimeZone; //表示博客 public class Blog { private int blogId; private String title; private String content; private int userId; private Timestamp postTime; 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 int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getPostTime() { //把时间戳构造成日期结构 SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return simpleDateFormat.format(this.postTime); } public void setPostTime(Timestamp postTime) { this.postTime = postTime; } } 生成Get、Set方法
package model; //表示用户 public class User { private int userId; private String username; private String password; private int isYourBlog=0; public int getIsYourBlog() { return isYourBlog; } public void setIsYourBlog(int isYourBlog) { this.isYourBlog = isYourBlog; } 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; } } 获取数据库连接 管理数据库的创建配置和管理
package model; import com.mysql.cj.jdbc.MysqlDataSource; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class DBUtil { //定义私有静态的DataSource对象,用于存储数据库连接信息。 //volatile确保了对这个变量的读写操作都是原子性的,即使再多线程环境下 //对这个变量访问也是线程安全的 private volatile static DataSource dataSource=null; //获取数据库连接 管理数据库的创建、配置和管理 private static javax.sql.DataSource getDataSource() { //如果为空时 加锁 if(dataSource==null){ synchronized (DBUtil.class){ if (dataSource == null) { dataSource = new MysqlDataSource(); ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/blog_system?characterEncoding=utf8&useSSL=false"); ((MysqlDataSource)dataSource).setUser("root"); ((MysqlDataSource)dataSource).setPassword("monan1946"); } } } return dataSource; } //这个方法是从DataSource获取一个具体的数据库连接 //它通常在需要执行数据库操作时调用,比如执行SQL查询或更新 public static Connection getConnection() throws SQLException { return getDataSource().getConnection(); } //关闭数据库连接 public static void close(Connection connection, PreparedStatement statement, ResultSet resultSet){ if (resultSet!=null){ try { resultSet.close(); } catch (SQLException e) { throw new RuntimeException(e); } } if(statement!=null){ try { statement.close(); } catch (SQLException e) { throw new RuntimeException(e); } } if(connection!=null){ try { connection.close(); } catch (SQLException e) { throw new RuntimeException(e); } } } } 与数据库连接后,查询数据库,插入数据,删除数据操作
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; //import static jdk.nashorn.internal.objects.NativeString.substring; //Dao Data Access Object 用来访问数据的对象 //针对博客的增删改查 public class BlogDao { //插入博客 public void insert(Blog blog){ Connection connection=null; PreparedStatement statement=null; try { //与数据库建立连接 connection = DBUtil.getConnection(); //构造SQL语句 String sql = "insert into blog values(null,?,?,?,now())"; //写入sql语句 statement = connection.prepareStatement(sql); //写入问号对应的数据 statement.setString(1, blog.getTitle()); statement.setString(2, blog.getContent()); statement.setInt(3, blog.getUserId()); //执行sql int ret = statement.executeUpdate(); if (ret == 1) { System.out.println("插入成功"); } else { System.out.println("插入失败"); } }catch (SQLException e) { e.printStackTrace(); }finally { //关闭连接 DBUtil.close(connection,statement,null); } } //查询所有博客 public List selectAll(){ Connection connection=null; PreparedStatement statement=null; ResultSet resultSet=null; List blogs=new ArrayList<>(); try { //与数据库建立连接 connection=DBUtil.getConnection(); //构造sql //让新的先读取 页面新的在最上面 String sql="select * from blog order by postTime desc"; //写入sql statement=connection.prepareStatement(sql); //执行SQL resultSet=statement.executeQuery(); //遍历结果集合 while (resultSet.next()){ Blog blog=new Blog(); blog.setBlogId(resultSet.getInt("blogId")); blog.setTitle(resultSet.getString("title")); String content=resultSet.getString("content"); // //如果长度大于100时,只截取100个字符作为摘要 if(content.length()>100){ content=content.substring(0,100); } //如果不大于100 不截取 blog.setContent(content); blog.setUserId(resultSet.getInt("userId")); blog.setPostTime(resultSet.getTimestamp("postTime")); blogs.add(blog); } } catch (SQLException e) { e.printStackTrace(); }finally { //关闭连接 DBUtil.close(connection,statement,resultSet); } return blogs; } //查询一篇博客 public Blog selectOne(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 来查询. blogId 是自增主键, 不能重复. // 此处的查询结果不可能是多条记录. 只能是 1 条或者 0 条. 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 throwables) { throwables.printStackTrace(); } finally { // 5. 关闭资源 DBUtil.close(connection, statement, resultSet); } return null; } //删除博客 public void delete(int blogId){ Connection connection=null; PreparedStatement statement=null; ResultSet resultSet=null; try { //建立连接 connection =DBUtil.getConnection(); //构造SQL语句 String sql="delete from blog where blogId=?"; //写入sql statement=connection.prepareStatement(sql); //替换? statement.setInt(1,blogId); //执行sql int ret=statement.executeUpdate(); if(ret==1){ System.out.println("删除成功"); } else{ System.out.println("删除失败"); } } catch (SQLException e) { e.printStackTrace(); }finally { DBUtil.close(connection,statement,null); } } } 对数据库内的数据进行操作
package model; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; //Dao Data Access Object 用来访问数据的对象 //针对用户的增删改查 public class UserDao { //查询用户 public User selectByName(String username){ Connection connection=null; PreparedStatement statement=null; ResultSet resultSet=null; try { //建立连接 connection=DBUtil.getConnection(); //构造sql语句 String sql="select * from user where username=?"; //写入sql statement=connection.prepareStatement(sql); //填入问号 statement.setString(1,username); //执行sql resultSet=statement.executeQuery(); 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 selectById(int userId){ Connection connection=null; PreparedStatement statement=null; ResultSet resultSet=null; try { //建立连接 connection=DBUtil.getConnection(); //构造sql语句 String sql="select * from user where userId=?"; //写入sql statement=connection.prepareStatement(sql); //填入问号 statement.setInt(1,userId); //执行sql resultSet=statement.executeQuery(); 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; } } 需要把创建数据库的语句放入db.sql中,方便后续更换数据库使用
create database blog_system; use blog_system; create table blog( blogId int primary key auto_increment, --主键 自增 博客ID title varchar(1024), --博客标题 content mediumtext, --博客正文 mediutext类型很长 userId int, --作者id postTime datetime --发布事件 ); create table blog( blogId int primary key auto_increment, title varchar(1024), content mediumtext, userId int, postTime datetime ); create table user( userId int primary key auto_increment, --用户id username varchar(128) unique , --用户名 password varchar(128) --密码 ); create table user( userId int primary key auto_increment, username varchar(128) unique , password varchar(128) ); 
login/loginServlet
前端将用户写入的数据已post方法提交给后端
登录页 登录
package controller; import model.User; import model.UserDao; 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; @WebServlet("/login") public class loginServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //告诉servlet(服务器)按照utf格式解析请求中的body //如果不使用这个 中文格式的会乱码 req.setCharacterEncoding("utf8"); //告诉浏览器 按照utf8格式解析响应 // resp.setCharacterEncoding("utf8"); resp.setContentType("text/html;charset=utf8"); String username=req.getParameter("username"); String password=req.getParameter("password"); // System.out.println(username); // System.out.println(password); // if(username.equals("user")&&password.equals("123")){ // resp.getWriter().write("登录成功"); // } // else // { // resp.getWriter().write("用户名或密码错误"); // } UserDao userDao=new UserDao(); User user=userDao.selectByName(username); if(user==null){ resp.getWriter().write("用户名或密码错误"); return; } if(!user.getPassword().equals(password)){ resp.getWriter().write("用户名或密码错误"); return; } //到这里就是登录成功了 //构造会话 cookie HttpSession session= req.getSession(); //把信息存到cookie内,方便后续使用 session.setAttribute("user",user); //登录成功后 跳转页面 resp.sendRedirect("blog_list.html"); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //验证登录状态 //如果用户未登录,强制重定向到登录页面 //如果用户已登录,不做动作 //取查询session HttpSession session=req.getSession(false); if(session==null){ //如果连session都没有 返回403状态码 //403状态码就是代表用户未登录的状态码 resp.setStatus(403); return; } //取cookie查找是否有user这个用户 //这个user不是用户名 而是user内的用户名 User user= (User) session.getAttribute("user"); if(user==null){ //没有这个用户,说明未登录 resp.setStatus(403); return; } //到这说明用户已经登录成功 resp.setStatus(200); } } 
前端使用ajax方法,所以需要引入jquery
jquery需要从jQuery CDN 链接内点击minified 复制
https://code.jquery.com/jquery-3.7.1.min.js 之后引入即可使用
前端整体代码
墨轩博客页 注意:注销登录和注销账号是不同的,注销登录即退出登录,而注销账户是删除账号
注销