共计 8704 个字符,预计需要花费 22 分钟才能阅读完成。
我的项目介绍
本我的项目应用 jsp+servlet+mysql 架构搭建可聊天的酷炫博客零碎。界面十分难看,除了登录注册集体核心批改外,博客还增加背景音乐,可在线交友聊天,发表动静,互相评论等,喜爱的博文还能增加珍藏。
开发环境:
- jdk 8
- intellij idea
- tomcat 8
- mysql 5.7
所用技术:
- jsp+servlet
- js+ajax
- layui
- jdbc+C3P0
博客拜访地址
http://localhost:8090/indexServlet
我的项目目录构造
运行成果
- 登录
- 首页
- 动静评论
- 关注列表
- 个人资料
- 聊天页面
外围代码:
1. 注册应用邮箱验证码
// 邮件对象
public class EmailModel {
private String title;// 题目
private String receiverEmail;// 接管人邮箱
private String text;// 发送内容
public static String register="欢送来到微博客 n 您的注册为:";
public static String registerTitle="注册验证码";
public static String findPwdTitle="找回明码:";
public static String findPwdText="找回明码验证码:";
}
// 邮件发送
public class EmailUtils {
private final static String authorizationCode="khdotvxxxxdba"; // 受权码 - 本人设置
private final static String senderEmail ="1022287044@qq.com"; // 发送人邮箱 -- 测试邮箱
// 发送邮件办法
public static int sendEmail(EmailModel emailModel){try{ Properties props = new Properties(); // 开启 debug 调试
props.setProperty("mail.debug", "false"); // 发送服务器须要身份验证
props.setProperty("mail.smtp.auth", "true"); // 设置邮件服务器主机名
props.setProperty("mail.host", "smtp.qq.com"); // 发送邮件协定名称
props.setProperty("mail.transport.protocol", "smtp"); MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); props.put("mail.smtp.ssl.enable", "true"); props.put("mail.smtp.ssl.socketFactory", sf); Session session = Session.getInstance(props); Message msg = new MimeMessage(session); msg.setSubject(emailModel.getTitle());// 题目
StringBuilder builder = new StringBuilder(); builder.append(emailModel.getText()); msg.setText(builder.toString()); msg.setFrom(new InternetAddress(senderEmail));// 发送人的邮箱地址
Transport transport = session.getTransport(); // 发送人的邮箱地址 // 你的邮箱明码或者受权码
transport.connect("smtp.qq.com", senderEmail, authorizationCode); transport.sendMessage(msg, new Address[] {new InternetAddress(emailModel.getReceiverEmail()) });// 接管人的邮箱地址
transport.close(); return 1;}catch (Exception e){e.printStackTrace(); return 0; } }}
// 注册及发送邮箱验证码
public void doGet(HttpServletRequest request, HttpServletResponse response) {try{ PrintWriter printWriter=response.getWriter(); HttpSession session=request.getSession(); String action = request.getParameter("action"); String userName=request.getParameter("userName"); String password=request.getParameter("password"); if("sendEmail".equals(action)){ // 发送验证码
String receiverEmail=request.getParameter("receiverEmail"); String type=request.getParameter("type"); String authCode=RandomUtil.randomNumbers(4); EmailModel emailModel=new EmailModel(); if("register".equalsIgnoreCase(type)){ // 注册
User search=new User(); search.setUserName(receiverEmail); search=userService.getUser(search); if(null!=search){printWriter.println("2"); return; }else{emailModel.setTitle(EmailModel.registerTitle); emailModel.setText(EmailModel.register+authCode); } }else{ // 找回明码
emailModel.setTitle(EmailModel.findPwdTitle); emailModel.setText(EmailModel.findPwdText+authCode); } System.out.println("邮箱验证码:"+authCode);
emailModel.setReceiverEmail(receiverEmail); int result= EmailUtils.sendEmail(emailModel); session.setAttribute(receiverEmail+"#EmailCode",authCode);// 注册验证码
printWriter.println(result);
}else if("doRegister".equals(action)){ // 注册验证
String authCode=request.getParameter("authCode");// 验证码
String sessionCode=(String)session.getAttribute(userName+"#EmailCode");// 注册验证码
if(null==sessionCode){printWriter.println("3"); // 验证码为空,请先获取邮箱验证码
}else if(!sessionCode.equals(authCode)){printWriter.println("2"); // 验证码谬误
}else{User user=new User(); user.setUserName(userName); user.setNickName(userName); user.setPassword(password); int result=userService.addUser(user); printWriter.println(result); // 验证胜利
} } }catch (Exception e){e.printStackTrace(); return ; }}
2. 上传头像
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
try { // 配置上传参数
PrintWriter printWriter = response.getWriter(); String fileName = ""; DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); String userId = request.getParameter("userId"); String type = request.getParameter("type"); if (null != userId && !"".equals(userId)) {List<FileItem> formItems = upload.parseRequest(request); for (FileItem item : formItems) { // 迭代表单数据
if (!item.isFormField()) {String fileName2 = item.getName(); // 重置乱码中文
fileName = RandomUtil.randomString(5) + (fileName2.substring(fileName2.indexOf("."))); String filePath = String.format("%s/%s", SystemConfig.fileUploadPath, fileName); File storeFile = new File(filePath); item.write(storeFile); // 保留文件到硬盘
} } if (null == type || "".equalsIgnoreCase(type)) {String userUpload = SessionUtils.getUserUpload(Integer.valueOf(userId), request); if (null != userUpload && !"".equalsIgnoreCase(userUpload)) {userUpload = userUpload + fileName + ",";} else {userUpload = fileName + ",";} SessionUtils.setUserUpload(Integer.valueOf(userId), userUpload, request); printWriter.println("0"); } else if ("headPic".equalsIgnoreCase(type)) {// 头像
SessionUtils.setUserHeadPic(Integer.valueOf(userId), fileName, request); printWriter.println("0"); } } else {printWriter.println("0"); // 用户信息未找到
} printWriter.close();} catch (Exception ex) {ex.printStackTrace(); }}
3. 集体聊天(发送音讯及读取音讯实现)
// 音讯采纳读取数据库模式实现,并非 socket 或者其余通信主件
public void doGet(HttpServletRequest request, HttpServletResponse response) {HttpSession session=request.getSession(); PrintWriter printWriter=response.getWriter(); String action = request.getParameter("action"); User user= SessionUtils.getUser(request); if ("sendMsg".equals(action)) { // 发送音讯
String message=request.getParameter("message"); String receiveId=request.getParameter("receiveId"); Chat chat=new Chat(); chat.setUserId(user.getId()); chat.setUserName(user.getNickName()); chat.setMessage(message); chat.setStatus(0); chat.setReceiveId(Integer.valueOf(receiveId)); chat.setCreateTime(DateUtil.formatDateTime(new Date())); Posts posts=new Posts(); posts.setReleaseId(user.getId()); chatService.addChat(chat); printWriter.println("0"); session.setAttribute(user.getId()+":"+receiveId,message); // 增加推送
Notice notice=new Notice(); notice.setNoticeUserId(Integer.valueOf(receiveId)); notice.setUserId(user.getId()); notice.setNoticeType(3); notice.setIsRead(0); Notice isExtis=noticeService.getNotice(notice); if(null==isExtis){System.out.println("增加推送");
notice.setUserName(user.getUserName()); notice.setPostTitle(message); noticeService.addNotice(notice); // 增加告诉
}else{System.out.println("有未读音讯,不增加推送");
} }else if ("getMsg".equals(action)) { // 获取音讯
String sendUserId=request.getParameter("sendUserId"); // 发送人 id
String receiveId=request.getParameter("receiveId"); // 接管人
Chat chat=new Chat(); chat.setUserId(Integer.valueOf(sendUserId)); chat.setReceiveId(Integer.valueOf(receiveId)); chat.setStatus(0); List<Chat> list=chatService.getChatList(chat); if(list.size()>0){printWriter.println(JSONUtil.toJsonStr(list)); for(Chat c:list){c.setStatus(1); chatService.updateChat(c); } }else{printWriter.println(""); } printWriter.close();}}
// 前端 jsp 页面代码
<div class="qqBox">
<div class="BoxHead"> <div class="headImg"> <img src="images/upload/${userInfo.headPic}" /> <!-- 以后本人 -->
<input value="images/upload/${loginUser.headPic}" id="loginUserHeadPic" type="hidden"/> <input value="${loginUser.id}" id="sendUserId" type="hidden"/>
<!-- 对方好友 -->
<input value="images/upload/${userInfo.headPic}" id="userInfoHeadPic" type="hidden"/> <input value="${userInfo.id}" id="receiveId" type="hidden"/> </div> <div class="internetName">${userInfo.userName}</div> </div> <div class="context"> <div class="conRight"> <div class="Righthead"> <div class="headName">${userInfo.nickName}</div> <div class="headConfig"> <ul> <li><img src="images/chat/20170926103645_06.jpg"/></li> <li><img src="images/chat/20170926103645_08.jpg"/></li> <li><img src="images/chat/20170926103645_10.jpg"/></li> <li><img src="images/chat/20170926103645_12.jpg"/></li> </ul> </div> </div> <div class="RightCont"> <ul class="newsList">
</ul> </div> <div class="RightFoot"> <div class="footTop"> <ul> <li><img src="images/chat/20170926103645_31.jpg"/></li> <li class="ExP"><img src="images/chat/20170926103645_33.jpg"/></li> <li><img src="images/chat/20170926103645_35.jpg"/></li> <li><img src="images/chat/20170926103645_37.jpg"/></li> <li><img src="images/chat/20170926103645_39.jpg"/></li> <li><img src="images/chat/20170926103645_41.jpg" alt=""/></li> <li><img src="images/chat/20170926103645_43.jpg"/></li> <li><img src="images/chat/20170926103645_45.jpg"/></li> </ul> </div> <div class="inputBox"> <textarea id="dope"name="" rows=""cols=""></textarea> <button class="sendBtn"> 发送 (s)</button>
</div> </div> </div> </div></div>
4. 关注 粉丝 喜爱统计
// 每一项依据用户 id 独自统计在组装数据
public void getLikeFansNul(Integer userId,HttpServletRequest request){String fansSql="select count(id) from t_likeuser where likeUserId="+userId; int fansNum= JDBCUtils.getCount(fansSql); String likeSql="select count(id) from t_likeuser where userid="+userId; int likeNum= JDBCUtils.getCount(likeSql); String collectSql="select count(id) from t_collection where userid="+userId; int collectNum= JDBCUtils.getCount(collectSql); CountsVo countsVo=new CountsVo(fansNum,likeNum,collectNum); SessionUtils.setCountsVo(countsVo,request);}
我的项目注意事项
1: 珍藏和关注才会有告诉
2:珍藏本人的推文没有告诉
3:聊天音讯推送如果有一条以后人发送的音讯未读时,只保留一条未读音讯
4:音讯采纳读取数据库模式实现,并非 socket 或者其余通信主件, 前期会独自起一个我的项目实现 socket 版本及其他三方开源的通信主件版本,敬请关注及更新
正文完