Web在线聊天室 --- 退出登录
Posted 满眼*星辰
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Web在线聊天室 --- 退出登录相关的知识,希望对你有一定的参考价值。
退出登录
删除客户端中保存的session
接口设计
请求:
GET /logout
响应:
HTTP/1.1 200 OK
ok: 1,
reason: xxx
前端ajax异步回调函数
logout()
console.log("logout");
app.login.isLogin = false;
app.user.name = null;
$.ajax(
url: 'logout',
type: 'get',
success: function(body, status)
if(body.ok)
window.location.reload();
else
alert(body.reason);
);
,
编写servlet的doGet方法
package org.example.servlet;
import org.example.model.Response;
import org.example.model.User;
import org.example.util.Util;
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;
/**
* Created with IntelliJ IDEA.
* Description:退出登录
* User: starry
* Date: 2021 -05 -28
* Time: 22:03
*/
@WebServlet("/logout")
public class LogoutServlet extends HttpServlet
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json");
HttpSession session = req.getSession(false);
if (session != null)
User user = (User)session.getAttribute("user");
if (user != null)
//用户已登录,删除session中保存的用户信息(注销)
session.removeAttribute("user");
//注销成功,返回ok:true
Response response = new Response();
response.setOk(true);
resp.getWriter().println(Util.serialize(response));
return;
//用户未登录
Response response = new Response();
response.setReason("用户未登录,不允许访问");
resp.getWriter().println(Util.serialize(response));
实现效果
点击退出登录
转为未登录状态
以上是关于Web在线聊天室 --- 退出登录的主要内容,如果未能解决你的问题,请参考以下文章
ASP.NET SignalR 与 LayIM2.0 配合轻松实现Web聊天室 之 用 Redis 实现用户在线离线状态消息处理