JavaWeb项目-----博客系统

一.设计数据库

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;@Overridepublic 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;@Overridepublic 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();@Overrideprotected 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.检测用户是否登录

如果用户未登录是不能跳转到博客列表的页面

@Overrideprotected 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 || content == null || "".equals(title) || "".equals(content)) {resp.setContentType("text/html; charset=utf8");resp.getWriter().write("标题或者正文为空");return;}Blog blog = new Blog();blog.title=title;blog.userId=user.userId;blog.content=content;BlogDao blogDao = new BlogDao();try {blogDao.insert(blog);} catch (SQLException e) {throw new RuntimeException(e);}resp.sendRedirect("blog_list.html");}

主要功能是处理博客发布相关的操作。首先,它会检查用户是否登录,通过获取用户会话(HttpSession),如果会话不存在或者从会话中获取不到代表用户的User对象,就会向客户端返回“用户未登录! 无法发布博客!”的提示并终止方法执行。如果用户已登录,它会从POST请求中获取博客的标题(title)和内容(content),并且对获取到的标题和内容进行验证,如果标题或者内容为空(null或者空字符串),则向客户端返回“标题或者正文为空”的提示并终止方法。如果标题和内容都有效,它会创建一个Blog对象,将从请求中获取到的标题和内容以及从用户对象中获取到的用户ID设置到Blog对象的属性中。然后通过BlogDao将博客对象插入到数据库中。最后,如果博客插入成功,将客户端重定向到blog_list.html页面,展示博客列表的页面。

在这里插入图片描述

在这里插入图片描述

3.用户登录

package api;import Dao.User;
import Dao.UserDao;
import utils.CloudSmsUtil;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;
@WebServlet("/login")
public class LoginSevlet extends HttpServlet {@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {req.setCharacterEncoding("utf8");String usename = req.getParameter("username");String password=req.getParameter("password");String phone = req.getParameter("phone");String code = req.getParameter("code");if(usename==null||password==null||"".equals(usename)||"".equals(password)||"".equals(phone)||"".equals(code)){resp.setContentType("text/html;charset=utf8");resp.getWriter().write("传过来数值错误");return;}String inoutCode = CloudSmsUtil.PHONE_CODE_MAP.get(phone);if (!code.equals(inoutCode)) {resp.setContentType("text/html;charset=utf8");resp.getWriter().write("验证码错误");return;}UserDao userDao = new UserDao();User user = null;try {user = userDao.getUserByName(usename);} catch (SQLException e) {throw new RuntimeException(e);}if(user==null){resp.setContentType("text/html;charset=utf8");resp.getWriter().write("查无此人");return;}if(!password.equals(user.password)){resp.setContentType("text/html;charset=utf8");resp.getWriter().write("密码错误");return;}HttpSession httpSession = req.getSession(true);httpSession.setAttribute("user",user);resp.sendRedirect("blog_list.html");}
package utils;import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;import java.util.HashMap;
import java.util.Map;public class CloudSmsUtil {private final static String accessKeyId = "LTAI5tEqaD59ckPYDhhxJ3ZF";private final static String accessKeySecret = "x6aD71AB7NmKhlayqhGIN1nt44M0TG";private final static String showStartNoticeTemplate = "SMS_474960284";private final static String signName = "我的学习路";/**ali固定配置参数begin*///短信API产品名称static final String product="Dysmsapi";//短信API产品域名static final String domain="dysmsapi.aliyuncs.com";/**ali固定配置参数end*/public final static Map<String, String> PHONE_CODE_MAP = new HashMap<>();public static boolean sendCheckCode(String phone, String code) {JSONObject params = new JSONObject();params.put("code", code);return  aliSmsSendMsg(showStartNoticeTemplate, phone, params);}private static boolean aliSmsSendMsg(String templateCode, String phone, JSONObject params) {//		System.out.println("alibaba-phone:" + phone + "-code:" + code);System.out.println("配置信息");System.out.println("accessKeyId:" + accessKeyId);System.out.println("accessKeySecret:" + accessKeySecret);System.out.println("signName:" + signName);System.out.println("templateCode:" + templateCode);try {//设置超时时间System.setProperty("sun.net.client.defaultConnectTimeout", "10000");System.setProperty("sun.net.client.defaultReadTimeout", "10000");//初始化ascClientIClientProfile profile= DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);IAcsClient acsClient=new DefaultAcsClient(profile);//组装请求对象SendSmsRequest request=new SendSmsRequest();//使用post提交request.setMethod(MethodType.POST);//待发送的手机号request.setPhoneNumbers(phone);//短信签名request.setSignName(signName);//短信模板IDrequest.setTemplateCode(templateCode);/** 可选:模板中的变量替换JSON串,* 如模板内容为"亲爱的${name},您的验证码为${code}"时,* 此处的值为{"name":"Tom","code":"1454"}*   \  反斜杠为转义字符,使得输出双引号*/request.setTemplateParam(params.toString());//可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者//request.setOutId("1454");SendSmsResponse response=acsClient.getAcsResponse(request);System.out.println(response.getCode() + ":" + response.getMessage());if(response.getCode() != null && response.getCode().equals("OK")) {//请求成功System.out.println("发送成功!");return true;}else {System.out.println(StrUtil.format("发送失败!{}", response.getCode() + ":" + response.getMessage()));return false;}} catch (ServerException e) {e.printStackTrace();return false;} catch (ClientException e) {e.printStackTrace();return false;}}
}
package api;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("/logout")
public class LogouServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {HttpSession httpSession = req.getSession(false);if(httpSession==null){resp.sendRedirect("login.html");return;}httpSession.removeAttribute("user");resp.sendRedirect("login.html");}
}
package api;import Dao.User;
import Dao.UserDao;
import cn.hutool.core.util.RandomUtil;
import utils.CloudSmsUtil;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;@WebServlet("/sendCode")
public class SendSmsCodeSevlet extends HttpServlet {@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {req.setCharacterEncoding("utf8");String phone = req.getParameter("phone");String code = RandomUtil.randomNumbers(4);boolean b = CloudSmsUtil.sendCheckCode(phone, code);
//        resp.setContentType("application/json;charset=utf8");if (b) {System.out.println("[发送验证码]-----------------------验证码为:"+ code);CloudSmsUtil.PHONE_CODE_MAP.put(phone, code);resp.getWriter().write("1");} else {resp.getWriter().write("0");}}@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req, resp);}
}

在这里插入图片描述

在这里插入图片描述

四.新增博客

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);
}
}

在这里插入图片描述

五.获取个人ID

package api;import Dao.Blog;
import Dao.BlogDao;
import Dao.User;
import Dao.UserDao;
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;@WebServlet("/user")
public class UserServlet extends HttpServlet {private ObjectMapper objectMapper = new ObjectMapper();@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String blogId = req.getParameter("blogId");if (blogId == null) {HttpSession session = req.getSession(false);if (session == null) {User user = new User();String respJson = objectMapper.writeValueAsString(user);resp.setContentType("application/json; charset=utf8");resp.getWriter().write(respJson);return;}User user = (User) session.getAttribute("user");if (user == null) {user = new User();String respJson = objectMapper.writeValueAsString(user);resp.setContentType("application/json; charset=utf8");resp.getWriter().write(respJson);return;}String respJson = objectMapper.writeValueAsString(user);resp.setContentType("application/json; charset=utf8");resp.getWriter().write(respJson);} else {BlogDao blogDao = new BlogDao();Blog blog = null;try {blog = blogDao.getBlog(Integer.parseInt(blogId));} catch (SQLException e) {throw new RuntimeException(e);}if (blog == null) {User user = new User();String respJson = objectMapper.writeValueAsString(user);resp.setContentType("application/json; charset=utf8");resp.getWriter().write(respJson);return;}UserDao userDao = new UserDao();User user = null;try {user = userDao.getUserById(blog.userId);} catch (SQLException e) {throw new RuntimeException(e);}if (user == null) {user = new User();String respJson = objectMapper.writeValueAsString(user);resp.setContentType("application/json; charset=utf8");resp.getWriter().write(respJson);return;}String respJson = objectMapper.writeValueAsString(user);resp.setContentType("application/json; charset=utf8");resp.getWriter().write(respJson);}}
}

在这里插入图片描述

六.总效果展示

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

七.总代码

1.代码分层

在这里插入图片描述

2.前端代码

!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>博客详情页</title><link rel="stylesheet" href="css/common.css"><link rel="stylesheet" href="css/blog_detail.css"><!-- 一定要引入 editormd 的依赖, 才能使用这里的方法 --><script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script><link rel="stylesheet" href="editor.md/css/editormd.min.css" /><script src="editor.md/lib/marked.min.js"></script><script src="editor.md/lib/prettify.min.js"></script><script src="editor.md/editormd.js"></script>
</head>
<body>
<!-- 导航栏. nav 是 导航 这个词的缩写 -->
<div class="nav"><!-- logo --><img src="image/logo2.jpg" alt=""><div class="title">我的博客系统</div><!-- 只是一个空白, 用来把后面的链接挤过去 --><!-- 这是一个简单粗暴的写法~~ --><div class="spacer"></div><a href="blog_list.html">主页</a><a href="blog_edit.html">写博客</a><!-- 这里的地址回头再说 --><a href="logout">注销</a>
</div>
<!-- 页面的主体部分 -->
<div class="container"><!-- 左侧信息 --><div class="container-left"><!-- 这个 div 表示整个用户信息的区域 --><div class="card"><!-- 用户的头像 --><img src="image/kun.jpg" alt=""><!-- 用户名 --><h3>小新要加油</h3><!-- github 地址 --><a href="https://www.github.com">github 地址</a><!-- 统计信息 --><div class="counter"><span>文章</span><span>分类</span></div><div class="counter"><span>2</span><span>1</span></div></div></div><!-- 右侧信息 --><div class="container-right"><h3>这是我的第一篇博客</h3><div class="date">2023-05-11 20:00:00</div><div class="content"><h3></h3><div class="date"></div><div id="content"></div></div></div><script src="js/app.js"></script><script>function getUrlParam(url, paramName) {const reg = new RegExp('(^|&)' + paramName + '=([^&]*)(&|$)', 'i');const result = url.slice(url.indexOf('?') + 1).match(reg);if (result !== null) {return decodeURIComponent(result[2]);}return null;}function getBlog(blogId) {$.ajax({url: 'blog?blogId=' + blogId,type: 'get',success: function(body) {// body = JSON.parse(body)// 根据拿到的响应数据, 构造页面内容.let h3 = document.querySelector('.container-right h3');h3.innerHTML = body.title;let dateDiv = document.querySelector('.container-right .date');dateDiv.innerHTML = body.postTime;editormd.markdownToHTML('content', { markdown: body.content });}});}getBlog(getUrlParam(window.location.href, 'blogId'));checkLogin();function getUser() {$.ajax({type: 'get',url: 'user' + location.search,success: function(body) {// body 就是解析后的 user 对象了.let h3 = document.querySelector('.card h3');h3.innerHTML = body.username;}})}getUser();</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>博客编辑页</title><link rel="stylesheet" href="css/common.css"><link rel="stylesheet" href="css/blog_edit.css"><script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script><!-- 引入 editor.md 的依赖 --><link rel="stylesheet" href="editor.md/css/editormd.min.css" /><script src="editor.md/lib/marked.min.js"></script><script src="editor.md/lib/prettify.min.js"></script><script src="editor.md/editormd.js"></script>
</head>
<body>
<!-- 导航栏. nav 是 导航 这个词的缩写 -->
<div class="nav"><!-- logo --><img src="image/logo2.jpg" alt=""><div class="title">我的博客系统</div><!-- 只是一个空白, 用来把后面的链接挤过去 --><!-- 这是一个简单粗暴的写法~~ --><div class="spacer"></div><a href="blog_list.html">主页</a><a href="blog_edit.html">写博客</a><!-- 这里的地址回头再说 --><a href="logout">注销</a>
</div><!-- 博客编辑页的版心 -->
<div class="blog-edit-container"><form action="blog" method="post"><!-- 标题编辑区 --><div class="title"><input type="text" id="title-input" name="title"><input type="submit" id="submit"></div><!-- 博客编辑器 --><!-- 把 md 编辑器放到这个 div 中 --><div id="editor"><textarea name="content" style="display: none"></textarea></div></form>
</div><script src="js/app.js"></script>
<script>var editor = editormd("editor", {// 这里的尺寸必须在这里设置. 设置样式会被 editormd 自动覆盖掉.width: "100%",// 设定编辑器高度height: "calc(100% - 50px)",// 编辑器中的初始内容markdown: "# 在这里写下你的留言",// 指定 editor.md 依赖的插件路径path: "editor.md/lib/"});checkLogin();
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>博客列表页</title><link rel="stylesheet" href="css/common.css"><link rel="stylesheet" href="css/blog_list.css">
</head>
<body>
<!-- 导航栏. nav 是 导航 这个词的缩写 -->
<div class="nav"><!-- logo --><img src="image/logo2.jpg" alt=""><div class="title">我的博客系统</div><!-- 只是一个空白, 用来把后面的链接挤过去 --><!-- 这是一个简单粗暴的写法~~ --><div class="spacer"></div><a href="blog_list.html">主页</a><a href="blog_edit.html">写博客</a><!-- 这里的地址回头再说 --><a href="logout">注销</a>
</div><!-- 页面的主体部分 -->
<div class="container"><!-- 左侧信息 --><div class="container-left"><!-- 这个 div 表示整个用户信息的区域 --><div class="card"><!-- 用户的头像 --><img src="image/kun.jpg" alt=""><!-- 用户名 --><h3>勇敢的小新</h3><!-- github 地址 --><a href="https://www.github.com">github 地址</a><!-- 统计信息 --><div class="counter"><span>文章</span><span>分类</span></div><div class="counter"><span>2</span><span>1</span></div></div></div><!-- 右侧信息 --><div class="container-right"><!-- <div class="blog"><div class="title">我的第一篇博客博客博客博客</div><div class="date">2023-05-11 20:00:00</div><div class="desc">从今天起, 我要认真敲代码. Lorem ipsum dolor sit amet consectetur, adipisicing elit. Debitis repellendus voluptatum, reiciendis rem consectetur incidunt aspernatur eveniet excepturi magni quis sint, provident est at et pariatur dolorem aliquid fugit voluptatem.</div><a href="blog_detail.html?blogId=1">查看全文 &gt;&gt; </a></div> --></div>
</div>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script src="js/app.js"></script>
<script>// 编写 js 代码.// 构造 http 请求, 获取到博客列表数据, 并展示到页面上.function getBlogs() {$.ajax({type: 'get',url: 'blog',success: function(body) {// 就需要根据响应的内容, 构造出 html 片段, 展示到页面上.// 由于服务器响应中已经设置了 Content-Type 为 application/json, 此时// jQuery 就能够自动的把此处响应的内容解析成 js 对象数组.let containter = document.querySelector('.container-right');debuggerfor (let blog of JSON.parse(body)) {// 根据当前这个 blog 构造出一个 html 片段.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.href = 'blog_detail.html?blogId=' + blog.blogId;a.innerHTML = '查看全文 &gt;&gt;';blogDiv.appendChild(a);// 最后把拼好的 blogDiv 添加到 container 的后面containter.appendChild(blogDiv);}}});}getBlogs();checkLogin();function getUser() {$.ajax({type: 'get',url: 'user',success: function(body) {// body 就是解析后的 user 对象了.let h3 = document.querySelector('.card h3');h3.innerHTML = body.username;}})}getUser();</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>博客登录页</title><link rel="stylesheet" href="css/common.css"><link rel="stylesheet" href="css/login.css">
</head>
<body>
<!-- 导航栏. nav 是 导航 这个词的缩写 -->
<div class="nav"><!-- logo --><img src="image/logo2.jpg" alt=""><div class="title">电信ydx的博客系统</div><!-- 只是一个空白, 用来把后面的链接挤过去 --><!-- 这是一个简单粗暴的写法~~ --><div class="spacer"></div><a href="blog_list.html">主页</a><a href="blog_edit.html">写博客</a>
</div><!-- 登录页的版心 -->
<div class="login-container"><!-- 登录对话框 --><div class="login-dialog"><h3>登录</h3><!-- 使用 form 包裹一下下列内容, 便于后续给服务器提交数据 --><form action="login" method="post"><div class="row"><span>用户名</span><input type="text" id="username" name="username"></div><div class="row"><span>密码</span><input type="password" id="password" name="password"></div><div class="row"><span>手机号</span><input type="text" id="phone" name="phone"><button id="sendCode">发送验证码</button></div><div class="row" id="phoneCheckCode" style="display: none"><span>验证码</span><input type="text" id="code" name="code"></div><div class="row" id="sendPhoneCheckCode"></div><div class="row"><input type="submit" id="submit" value="登录"></div></form></div>
</div>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script src="js/app.js"></script>
<script>document.getElementById('sendCode').addEventListener('click', function(event) {event.preventDefault();// 这里可以添加其他逻辑$('#sendCode').on('click', function() {var phone = $("#phone").val()$.ajax({type: 'get',url: 'sendCode?phone='+phone,success: function(body) {if (body=="0") {alert("发送失败")return} else {alert("发送成功")$("#sendCode").hide()$("#phoneCheckCode").show()return;}}});});});$(document).ready(function() {// 在这里写入需要在页面加载后执行的代码console.log('页面已加载完毕!');});</script>
</body>
</html>

3.后端代码

1.api

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();@Overrideprotected 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);}}@Overrideprotected 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 || content == null || "".equals(title) || "".equals(content)) {resp.setContentType("text/html; charset=utf8");resp.getWriter().write("标题或者正文为空");return;}Blog blog = new Blog();blog.title=title;blog.userId=user.userId;blog.content=content;BlogDao blogDao = new BlogDao();try {blogDao.insert(blog);} catch (SQLException e) {throw new RuntimeException(e);}resp.sendRedirect("blog_list.html");}
}
package api;import Dao.User;
import Dao.UserDao;
import utils.CloudSmsUtil;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;
@WebServlet("/login")
public class LoginSevlet extends HttpServlet {@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {req.setCharacterEncoding("utf8");String usename = req.getParameter("username");String password=req.getParameter("password");String phone = req.getParameter("phone");String code = req.getParameter("code");if(usename==null||password==null||"".equals(usename)||"".equals(password)||"".equals(phone)||"".equals(code)){resp.setContentType("text/html;charset=utf8");resp.getWriter().write("传过来数值错误");return;}String inoutCode = CloudSmsUtil.PHONE_CODE_MAP.get(phone);if (!code.equals(inoutCode)) {resp.setContentType("text/html;charset=utf8");resp.getWriter().write("验证码错误");return;}UserDao userDao = new UserDao();User user = null;try {user = userDao.getUserByName(usename);} catch (SQLException e) {throw new RuntimeException(e);}if(user==null){resp.setContentType("text/html;charset=utf8");resp.getWriter().write("查无此人");return;}if(!password.equals(user.password)){resp.setContentType("text/html;charset=utf8");resp.getWriter().write("密码错误");return;}HttpSession httpSession = req.getSession(true);httpSession.setAttribute("user",user);resp.sendRedirect("blog_list.html");}@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {HttpSession httpSession =req.getSession(false);if(httpSession==null){resp.setStatus(403);return;}User user =(User)httpSession.getAttribute("user");resp.setStatus(200);}
}
package api;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("/logout")
public class LogouServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {HttpSession httpSession = req.getSession(false);if(httpSession==null){resp.sendRedirect("login.html");return;}httpSession.removeAttribute("user");resp.sendRedirect("login.html");}
}
package api;import Dao.User;
import Dao.UserDao;
import cn.hutool.core.util.RandomUtil;
import utils.CloudSmsUtil;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;@WebServlet("/sendCode")
public class SendSmsCodeSevlet extends HttpServlet {@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {req.setCharacterEncoding("utf8");String phone = req.getParameter("phone");String code = RandomUtil.randomNumbers(4);boolean b = CloudSmsUtil.sendCheckCode(phone, code);
//        resp.setContentType("application/json;charset=utf8");if (b) {System.out.println("[发送验证码]-----------------------验证码为:"+ code);CloudSmsUtil.PHONE_CODE_MAP.put(phone, code);resp.getWriter().write("1");} else {resp.getWriter().write("0");}}@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req, resp);}
}
package api;import Dao.Blog;
import Dao.BlogDao;
import Dao.User;
import Dao.UserDao;
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;@WebServlet("/user")
public class UserServlet extends HttpServlet {private ObjectMapper objectMapper = new ObjectMapper();@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String blogId = req.getParameter("blogId");if (blogId == null) {HttpSession session = req.getSession(false);if (session == null) {User user = new User();String respJson = objectMapper.writeValueAsString(user);resp.setContentType("application/json; charset=utf8");resp.getWriter().write(respJson);return;}User user = (User) session.getAttribute("user");if (user == null) {user = new User();String respJson = objectMapper.writeValueAsString(user);resp.setContentType("application/json; charset=utf8");resp.getWriter().write(respJson);return;}String respJson = objectMapper.writeValueAsString(user);resp.setContentType("application/json; charset=utf8");resp.getWriter().write(respJson);} else {BlogDao blogDao = new BlogDao();Blog blog = null;try {blog = blogDao.getBlog(Integer.parseInt(blogId));} catch (SQLException e) {throw new RuntimeException(e);}if (blog == null) {User user = new User();String respJson = objectMapper.writeValueAsString(user);resp.setContentType("application/json; charset=utf8");resp.getWriter().write(respJson);return;}UserDao userDao = new UserDao();User user = null;try {user = userDao.getUserById(blog.userId);} catch (SQLException e) {throw new RuntimeException(e);}if (user == null) {user = new User();String respJson = objectMapper.writeValueAsString(user);resp.setContentType("application/json; charset=utf8");resp.getWriter().write(respJson);return;}String respJson = objectMapper.writeValueAsString(user);resp.setContentType("application/json; charset=utf8");resp.getWriter().write(respJson);}}
}

2.Dao

import com.fasterxml.jackson.annotation.JsonFormat;import java.sql.Timestamp;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;@Overridepublic String toString() {return "Blog{" +"blogId=" + blogId +", title='" + title + '\'' +", content='" + content + '\'' +", userId=" + userId +", postTime=" + postTime +'}';}}
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);
}
}
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();}}}
package Dao;public class User {public int  userId;public String username;public String  password;@Overridepublic String toString() {return "User{" +"userId=" + userId +", username='" + username + '\'' +", password='" + password + '\'' +'}';}
}
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;}
}

3.utils

package utils;import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;import java.util.HashMap;
import java.util.Map;public class CloudSmsUtil {private final static String accessKeyId = "LTAI5tEqaD59ckPYDhhxJ3ZF";private final static String accessKeySecret = "x6aD71AB7NmKhlayqhGIN1nt44M0TG";private final static String showStartNoticeTemplate = "SMS_474960284";private final static String signName = "我的学习路";/**ali固定配置参数begin*///短信API产品名称static final String product="Dysmsapi";//短信API产品域名static final String domain="dysmsapi.aliyuncs.com";/**ali固定配置参数end*/public final static Map<String, String> PHONE_CODE_MAP = new HashMap<>();public static boolean sendCheckCode(String phone, String code) {JSONObject params = new JSONObject();params.put("code", code);return  aliSmsSendMsg(showStartNoticeTemplate, phone, params);}private static boolean aliSmsSendMsg(String templateCode, String phone, JSONObject params) {//		System.out.println("alibaba-phone:" + phone + "-code:" + code);System.out.println("配置信息");System.out.println("accessKeyId:" + accessKeyId);System.out.println("accessKeySecret:" + accessKeySecret);System.out.println("signName:" + signName);System.out.println("templateCode:" + templateCode);try {//设置超时时间System.setProperty("sun.net.client.defaultConnectTimeout", "10000");System.setProperty("sun.net.client.defaultReadTimeout", "10000");//初始化ascClientIClientProfile profile= DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);IAcsClient acsClient=new DefaultAcsClient(profile);//组装请求对象SendSmsRequest request=new SendSmsRequest();//使用post提交request.setMethod(MethodType.POST);//待发送的手机号request.setPhoneNumbers(phone);//短信签名request.setSignName(signName);//短信模板IDrequest.setTemplateCode(templateCode);/** 可选:模板中的变量替换JSON串,* 如模板内容为"亲爱的${name},您的验证码为${code}"时,* 此处的值为{"name":"Tom","code":"1454"}*   \  反斜杠为转义字符,使得输出双引号*/request.setTemplateParam(params.toString());//可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者//request.setOutId("1454");SendSmsResponse response=acsClient.getAcsResponse(request);System.out.println(response.getCode() + ":" + response.getMessage());if(response.getCode() != null && response.getCode().equals("OK")) {//请求成功System.out.println("发送成功!");return true;}else {System.out.println(StrUtil.format("发送失败!{}", response.getCode() + ":" + response.getMessage()));return false;}} catch (ServerException e) {e.printStackTrace();return false;} catch (ClientException e) {e.printStackTrace();return false;}}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/6093.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

算法练习——双指针

前言&#xff1a;大佬写博客给别人看&#xff0c;菜鸟写博客给自己看&#xff0c;我是菜鸟。 学前须知&#xff08;对自己&#xff09;&#xff1a;这里的指针不一定指地址&#xff01;也可能是数组下标。 1&#xff1a;移动零(双指针) 题目要求&#xff1a; 解题思路&#x…

vue3实现一个无缝衔接、滚动平滑的列表自动滚屏效果,支持鼠标移入停止移出滚动

文章目录 前言一、滚动元素相关属性回顾一、实现分析二、代码实现示例&#xff1a;2、继续添加功能&#xff0c;增加鼠标移入停止滚动、移出继续滚动效果2、继续完善 前言 列表自动滚屏效果常见于大屏开发场景中&#xff0c;本文将讲解用vue3实现一个无缝衔接、滚动平滑的列表自…

vscode翻译插件

vscode翻译插件 需求 &#xff1a; 在编写代码的时候&#xff0c; 打印或者定义变量的时候总是想不起来英文名称&#xff0c; 所有就开发了一款中文转换为英文的插件。 功能 1、目前支持选中中文&#xff0c;右键选择打印或者变量进行转换。 2、目前支持选中中文&#xff0…

Linux -- 初识线程

目录 线程的初步认识 为什么需要线程 怎么让代码分成多个执行流并发执行呢&#xff1f; 管理线程 线程的初步认识 线程是进程内部的一个执行分支&#xff0c;线程是CPU调度的基本单位。 在Linux操作系统中&#xff0c;线程是程序执行流的最小单位。一个进程可以包含多个线…

基于IM场景下的Wasm初探:提升Web应用性能|得物技术

一、何为Wasm &#xff1f; Wasm&#xff0c;全称 WebAssembly&#xff0c;官网描述是一种用于基于堆栈的虚拟机的二进制指令格式。Wasm被设计为一个可移植的目标&#xff0c;用于编译C/C/Rust等高级语言&#xff0c;支持在Web上部署客户端和服务器应用程序。 Wasm 的开发者参…

Linux SSH免密登入以及配置脚本

一、ssh原理简单介绍 客户端生成一对公钥和私钥&#xff0c;并将自己的公钥发送到服务器上 其中公钥用来加密&#xff0c;私钥用来解密。 二、ssh免密登入实现步骤详解 我这就以服务器controller和客户端compute来做为例子 2.1、首先在controller上输入ssh-keygen -t rsa …

Flutter 获取照片权限的时候是否要获取存储权限?

获取存储权限 Permission.storage.request(); 获取照片权限通常意味着访问相册&#xff0c;而访问相册可能还需要外部存储权限&#xff0c;因为照片通常存储在设备的外部存储中。所以&#xff0c;当你请求照片权限时&#xff0c;你也需要检查并请求外部存储权限。 是不是所有…

一个基于Rust适用于 Web、桌面、移动设备等的全栈应用程序框架

大家好&#xff0c;今天给大家分享一个用 Rust 语言编写的、受 React 启发的前端框架Dioxus&#xff0c;旨在为构建跨平台的用户界面提供高效、高性能的解决方案。 项目介绍 Dioxus项目的诞生源于开发者们对于更高效、更灵活的跨平台UI解决方案的渴望。 随着技术的发展&#…

IntelliJ Idea设置自定义快捷键

我IDEA的快捷键是自己修改成了和Eclipse相似&#xff0c;然后想要跳转到某个方法的上层抽象方法没有对应的快捷键&#xff0c;IDEA默认的是Ctrl U &#xff08;Windows/Linux 系统&#xff09; 或 Command U &#xff08;Mac 系统&#xff09;&#xff0c;但是我的不起作用&a…

前深度学习时代-经典的推荐算法

参考自《深度学习推荐系统》—— 王喆&#xff0c;用于学习记录。 1.协同过滤 “协同过滤”就是协同大家的反馈、评价和意见一起对海量的信息进行过滤&#xff0c;从中筛选出目标用户可能感兴趣的信息的推荐过程。 基于用户相似度进行推荐的协同过滤算法 UserCF 用户相似度…

达梦数据守护集群_动态增加实时备库

目录 1、概述 2、实验环境 2.1环境信息 2.2配置信息 2.3 查看初始化参数 3、动态增加实时备库 3.1数据准备 3.2配置新备库 3.3动态增加MAL配置 3.4 关闭守护进程及监视器 3.5修改归档&#xff08;方法1&#xff1a;动态添加归档配置&#xff09; 3.6 修改归档&…

6.qsqlquerymodel源码分析

目录 继承关系入口浅析qsqlquery刷新数据 扩展列或者移除列以及取别名读取数据与增减行读取数据 下一章节&#xff1a;如何使用qsqlquerymodel 与 qtableview实现自定义表格 继承关系 qsqlquerymodel 继承与qabstracttablemodel 入口 负责填充数据 void QSqlQueryModel::s…

【JavaEE】认识线程

一、引入线程 在任务管理器界面可以看到很多进程&#xff0c;可以利用CPU多核心这一点来更有效的执行这些进程&#xff0c;即在处理过程中将CPU的多个时间片分配给每个进程&#xff0c;这样的 "多进程编程"就可以起到并发编程的效果&#xff0c;因为进程可以被调度到…

qt QStatusBar详解

1、概述 QStatusBar是Qt框架提供的一个小部件&#xff0c;用于在应用程序窗口底部显示状态信息。它可以显示一些固定的文本和图标&#xff0c;并且可以通过API动态更新显示内容。QStatusBar通常是一个水平的窗口部件&#xff0c;能够显示多行文本内容&#xff0c;非常适合用于…

【Ubuntu】ubuntu 22.04 设置 Xorg 弃用 Wayland

# 编辑gdm3配置文件 sudo vim /etc/gdm3/custom.conf # 重启gdm3 sudo systemctl restart gdm3方式一&#xff1a;如果进行上述操作后&#xff0c;有对比度严重错误问题&#xff0c;请执行下列命令 # 安装驱动 sudo ubuntu-drivers autoinstall 方式二&#xff1a;推荐尝试方式…

日语学习的难易程度

日语学习的难易程度是一个相对主观的问题&#xff0c;它受到多种因素的影响&#xff0c;包括个人的语言学习能力、学习方法、学习时间、学习资源的可获得性以及个人对日语文化的兴趣和投入程度等。以下是对日语学习难易程度的一些分析&#xff1a; 优点与易学之处 文字系统&am…

WPF 打包

打包为单个exe文件直接运行 - - -版本.NET8 新建WPF项目 右键 - 发布 选择发布文件夹 选择发布文件夹 选择发布文件夹 配置 配置,保存 发布 WPF 打包为exe安装程序 示例 实现思路 引导项目中嵌入其它项目可运行目录的zip引导项目中解压zip文件到指定文件夹是…

RTC精度及校准

RTC精度偏差&#xff1a; RTC的基准时间和精度与石英晶体的频率相关&#xff0c;晶体的谐振频率取决于温度&#xff0c;因此RTC性能与温度相关&#xff0c;晶体的频率偏差是晶体正常频率的温度反转函数。 一、硬件方面&#xff1a; 1.使用高精度振荡器的RTC模块&#xff1b; …

C++ Qt6 QtQuick/QML入门进阶与项目实战视频教程

课程介绍 C Qt这些年在PC客户端、嵌入式、汽车座舱仪表等领域应用很广泛&#xff0c;例如剪映专业版、微信4.0、亿图脑图、Steam、美图秀秀、腾讯会议、钉钉(部分模块)等都是使用C QWidget/QML开发。特别是QML这种声明式UI开发更加快捷&#xff0c;QML的界面开发效率相对于QWid…

Linux:防火墙和selinux对服务的影响

1-1selinux 1-1 SELinux是对程序、文件等权限设置依据的一个内核模块。由于启动网络服务的也是程序&#xff0c;因此刚好也 是能够控制网络服务能否访问系统资源的一道关卡。 1-2 SELinux是通过MAC的方式来控制管理进程&#xff0c;它控制的主体是进程&#xff0c;而目标则是…