一.设计数据库
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">查看全文 >> </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 = '查看全文 >>';
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;
}
}
}