如何用JSP实现在登录的时候判断该用户是否已经登录

如题所述

第1个回答  2016-11-30
登录时判断session是否为空,为空的话则设置一个session,并进行登录操作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14

Login loginBean = null;
HttpSession session = request.getSession(true);
try {
loginBean = (Login) session.getAttribute("login");
if(loginBean == null){
loginBean = new Login();
session.setAttribute("login", loginBean);
}
} catch (Exception e) {
loginBean = new Login();
session.setAttribute("login", loginBean);
}

//下面是登录操作,并给loginBean这个javabean的各个参数赋值,省略

在其他页面里,通过判断先前设置的这个session是否为空,为空的话转向登录页面,否则继续操作:

1
2
3
4
5
6
7
8

HttpSession session = request.getSession(true);
Login loginBean = (Login) session.getAttribute("login");
if(loginBean == null){
response.sendRedirect("login.jsp");
}
else{
//其他操作,省略
}

附:这个一个登录成功后的显示页面:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

<%@page import="com.sun.xml.internal.bind.v2.model.core.ID"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ page import="com.zifangsky.OnlineFriend.model.member.Login"%>
<jsp:useBean id="login" type="com.zifangsky.OnlineFriend.model.member.Login" scope="session"/>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<base href="<%=basePath%>">
<%@ include file="head.txt"%>
</head>
<body>
<center>
<font size=4 color=blue>
<jsp:getProperty name="login" property="backNews"/>
</font>
<font size=3>
<% if(login.isLoginSuccess()){ %>
欢迎回来,尊敬的会员:<jsp:getProperty name="login" property="id"/>
<%}
else{%>
<a href="login.jsp">点击这里,重新登录</a>
<%} %>

</font>
</center>

</body>
</html>

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网