jsp+servlet實戰酷炫部落格+聊天系統
阿新 • • 發佈:2020-12-26
專案介紹
本專案使用jsp+servlet+mysql架構搭建可聊天的酷炫部落格系統。介面非常好看,除了登入註冊個人中心修改外,部落格還新增背景音樂,可線上交友聊天,發表動態,相互評論等,喜歡的博文還能新增收藏。
開發環境:
- jdk 8
- intellij idea
- tomcat 8
- mysql 5.7
所用技術:
- jsp+servlet
- js+ajax
- layui
- jdbc+C3P0
部落格訪問地址
http://localhost:8090/indexServlet
專案目錄結構
執行效果
-
登入
-
首頁
-
動態評論
-
關注列表
-
個人資料
-
聊天頁面
核心程式碼:
- 註冊使用郵箱驗證碼
//郵件物件 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 ="[email protected]"; //傳送人郵箱--測試郵箱 //傳送郵件方法 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 ; } }
- 上傳頭像
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(); } }
- 個人聊天(傳送訊息及讀取訊息實現)
//訊息採用讀取資料庫模式實現,並非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" style="width: 99%;height: 75px; border: none;outline: none;" name="" rows="" cols=""></textarea>
<button class="sendBtn">傳送(s)</button>
</div>
</div>
</div>
</div>
</div>
- 關注 粉絲 喜歡統計
//每一項根據使用者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版本及其他三方開源的通訊主件版本,敬請關注及更新