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

news2024/11/7 15:26:00

一.设计数据库

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 || 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 {
    @Override
    protected 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");
            //初始化ascClient
            IClientProfile 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);
            //短信模板ID
            request.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 {
    @Override
    protected 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 {
    @Override
    protected 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");
        }

    }

    @Override
    protected 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();

    @Override
    protected 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');
                debugger
                for (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();
    @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);
        }


    }

    @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 || 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 {
    @Override
    protected 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");
    }

    @Override
    protected 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 {
    @Override
    protected 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 {
    @Override
    protected 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");
        }

    }

    @Override
    protected 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();

    @Override
    protected 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;

    @Override
    public 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;

    @Override
    public 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");
            //初始化ascClient
            IClientProfile 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);
            //短信模板ID
            request.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.coloradmin.cn/o/2235104.html

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

相关文章

一文读懂:AIOps 从自动化运维到智能化运维

今天跟大家聊一聊AIOps&#xff08;人工智能运维&#xff09; 为了应对企业面临着日益复杂的运营挑战&#xff0c;AIOps&#xff08;人工智能运维&#xff09;作为一种创新的方法应运而生&#xff0c;结合了人工智能和机器学习技术&#xff0c;来提升IT运营的效率和性能。 这…

从0开始学习Linux——文件目录

往期目录&#xff1a; 从0开始学习Linux——简介&安装 从0开始学习Linux——搭建属于自己的Linux虚拟机 从0开始学习Linux——文本编辑器 从0开始学习Linux——Yum工具 从0开始学习Linux——远程连接工具 上期教程我们学习了如何使用远程连接工具去连接Linux系统&#xff0…

C++入门基础知识140—【关于C++ 类构造函数 析构函数】

成长路上不孤单&#x1f60a;&#x1f60a;&#x1f60a;&#x1f60a;&#x1f60a;&#x1f60a; 【14后&#x1f60a;///C爱好者&#x1f60a;///持续分享所学&#x1f60a;///如有需要欢迎收藏转发///&#x1f60a;】 今日分享关于C 类构造函数 & 析构函数的相关内容…

MSC“名实之辩”:精准鉴定只为精准治疗

前 言 MSC是一群来源广泛、能够体外增殖分化的异质性细胞。MSC具有免疫调节、促进组织修复等作用&#xff0c;应用于多种疾病的治疗。由于科学进程、习惯等原因&#xff0c;MSC具有多种名称。自先秦以来&#xff0c;就有“名实之辩”&#xff0c;今日我们就讲一讲MSC的名称与…

零基础 Vue 入门:个人主页完整示例教程” “Vue 实战:构建简洁美观的个人主页界面” “从零开始使用 Vue 构建个人主页,包含详细代码解析”

效果图 博客教程&#xff1a;使用 Vue 构建简易个人主页界面 目录 前言项目结构和准备HTML 与 CSS 布局Vue 数据绑定和渲染功能实现总结 前言 本教程将带你逐步使用 Vue.js 创建一个简易的“个人主页”界面。通过学习该项目&#xff0c;你将掌握 Vue 的基本数据绑定、指令的…

(二)基于Bayes方法的道路分割

一、实验目的 1、实验目标 学习掌握Bayes定理&#xff08;Bayes Theorem&#xff09;的基本原理及推导过程&#xff0c;以及公式中的先验概率、条件概率、后验概率、相似度等概念。在MATLAB的概率分布函数基础上&#xff0c;通过编写程序&#xff0c;实现图像块内结果统计和序…

从新手到专家:7款电脑平面设计软件评测

平面设计在时尚、广告等多个领域扮演着重要角色&#xff0c;而创作出独特且富有创意的设计作品则需要依赖优秀的电脑平面设计软件。市场上的电脑平面设计软件众多&#xff0c;每款软件都有其独到之处。本文将为你推荐几款值得关注的电脑平面设计软件&#xff0c;并分析它们的特…

Django安装

在终端创建django项目 1.查看自己的python版本 输入对应自己本机python的版本&#xff0c;列如我的是3.11.8 先再全局安装django依赖包 2.在控制窗口输入安装命令&#xff1a; pip3.11 install django 看到Successflully 说明我们就安装成功了 python的Scripts文件用于存…

elementui中的新增弹窗在新增数据成功后再新增 发现数据无法清除解决方法

elementui中的新增弹窗在新增数据成功后再新增 发现数据无法清除解决方法 试过网上其他方法&#xff0c;发现表单清空数据还是有问题&#xff0c;索性用下面方法解决: // 给弹框里面添加 v-ifvisible测试无问题&#xff0c;暂时先这样解决&#xff0c;如果有其他方法&#x…

计算机网络——路由器构成

算路由表是分布式去算——你算你的&#xff0c;我算我的 输出队列非先来先传 调度发生在哪里 缓存队列一般是应对——来数据方向的速度过快问题

PMP–一、二、三模、冲刺–分类–7.成本管理–技巧–挣值分析

文章目录 技巧一模7.成本管理--4.控制成本--数据分析--挣值分析--进度绩效指数&#xff08;SPI&#xff09;是测量进度效率的一种指标&#xff0c;表示为挣值与计划价值之比&#xff0c;反映了项目团队完成工作的效率。 当 SPI小于 1.0 时&#xff0c;说明已完成的工作量未达到…

CentOS 7 更换软件仓库

CentOS 7 于2024年6月30日停止维护&#xff0c;官方仓库已经没有软件了&#xff0c;想要继续使用 &#xff0c;需要更换软件仓库&#xff0c;这里更换到阿里云的软件仓库 https://developer.aliyun.com/mirror/ 查看目前可用的软件数量 yum repolist 更换软件仓库&#xff1a…

Dermaseptin;抗菌肽;皮抑菌肽;ALWKTMLKKLGTMALHAGKAALGAAADTISQGTQ;136212-91-4

【Dermaseptin 简介】 Dermaseptin&#xff0c;也被称为皮抑菌肽&#xff0c;是一类由蛙类皮肤分泌的多阳离子抗菌肽&#xff0c;主要存在于树蛙科&#xff08;Hylid frogs&#xff09;的蛙类&#xff0c;特别是 Agalychnis 和 Phyllomedusa 属的蛙类。它具有显著的抗菌活性&a…

在培训班学网络安全有用吗

在当今数字化时代&#xff0c;网络安全问题日益凸显&#xff0c;成为了企业和个人关注的焦点。随着对网络安全人才需求的不断增长&#xff0c;各种网络安全培训班也如雨后春笋般涌现。然而&#xff0c;在培训班学网络安全真的有用吗? 一、网络安全的重要性与挑战 1. 信息时代的…

微积分复习笔记 Calculus Volume 1 - 4.7 Applied Optimization Problems

4.7 Applied Optimization Problems - Calculus Volume 1 | OpenStax

绿色能源发展关键:优化风电运维体系

根据QYResearch调研团队最新发布的《全球风电运维市场报告2023-2029》显示&#xff0c;预计到2029年&#xff0c;全球风电运维市场的规模将攀升至307.8亿美元&#xff0c;并且在接下来的几年里&#xff0c;其年复合增长率&#xff08;CAGR&#xff09;将达到12.5%。 上述图表及…

软件工程笔记一

目录 软件的概念、特性和分类 软件与程序 软件的特性 软件的分类 软件危机与软件工程 软件危机 如何摆脱软件危机? 软件工程概念的提出 什么是软件工程&#xff1f; 软件工程的若干定义 系统工程的目标 软件工程的基本原理 软件工程的目标 软件的质量特性 软件生存…

【数据结构】线性表——顺序表

文章目录 一、线性表二、顺序表2.1概念及结构2.2、顺序表接口实现2.2.1、顺序表的动态存储2.2.2、顺序表初始化2.2.3、检查空间判断进行增容2.2.4、顺序表尾插、尾删2.2.5、顺序表头插、头删2.2.6、顺序表查找2.2.7、顺序表在pos位置插入x2.2.8、顺序表删除pos位置的值2.2.9、顺…

stable diffusion 大模型

本节内容&#xff0c;给大家带来的是stable diffusion的基础模型课程。基础模型&#xff0c;我们有时候也称之为大模型。在之前的课程中&#xff0c;我们已经多次探讨过大模型&#xff0c;并且也见识过一些大模型绘制图片的独特风格&#xff0c;相信大家对stable diffusion大模…

ChatPaper.ai:研究生文献阅读的AI助手利器

为什么选择 ChatPaper.ai&#xff1f; 作为研究生&#xff0c;我们每天都面临着大量文献阅读的挑战。一篇关键论文往往需要反复阅读数小时&#xff0c;还要做笔记、提取要点、理解创新点&#xff0c;这个过程既耗时又费力。ChatPaper.ai&#xff08;ChatPaper.ai - Chat with …