您的位置:首页 > Web前端 > JavaScript

jsp+servlet判断是否登录以及登录是否失效

2016-10-17 00:00 232 查看
摘要: rt

step1:html表单,表单中记得要有请求地址action=""和请求方式get/post,路径要写对。

<body>
<div class="col-md-12 column" style="height:80px"></div>
<div id="wrap" class="col-md-offset-3 col-md-6 panel panel-info">
<div class="panel-heading">
<h3 class="panel-title col-md-offset-6"><strong>登录</strong></h3>
</div>
<div class="col-md-12 column" style="height:80px"></div>
<form name="loginForm" id="loginForm" role="form" class="form-horizontal col-md-offset-2 col-md-9" action="servlet/LoginInfoServlet" method="get">
<div class="form-group" >
<label for="username" class="col-sm-3 control-label">用户名</label>
<input type="text" name="username" id="username" value="admin" class="form-control field" style="width:40%;display:inline" title="请输入用户名">
</div>
<div class="col-md-12 column" style="height:18px"></div>
<div class="form-group">
<label for="password" class="col-sm-3 control-label">密码</label>
<input type="password" name="password" id="password" value="" class="form-control field" style="width:40%;display:inline" title="请输入密码">
</div>
<div class="form-group">
<div class="col-sm-offset-5 col-sm-2">
<button type="submit" class="btn btn-primary form-control" id="login">登录</button>
</div>
</div>
</form>
</div>
</body>

step2:写step1中form提交的action="servlet/LoginInfoServlet"里的LoginInfoServlet逻辑
主要思路是:接收用户名+密码,对比是不是和预设的一样(这里是写死的,没有访问数据库),是就将用户名和密码保存到seesion中并跳转到操作页面,否则跳转到登录页面(此处最好在登录页面有个校验)。
LoginInfoServlet.java:

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
if(username.equals("admin") && password.equals("123456")){//登录成功
System.out.println("..........A successful login ...............");
request.getSession().setAttribute("sessionname",username);     //用Session保存用户名
request.getSession().setAttribute("sessionpwd",password);        //保存密码
response.sendRedirect("../demoManage.jsp");
}else{
response.sendRedirect("../login.jsp");
}

}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}

step3:

后面每个操作页面页面都在body之后加上如下代码,判断seesion中的数据是否为空,若为空,则跳转到登录页面重新登录。
此处要说明一下,session在两种情况下会为空,一是未登录,直接地址栏输入的操作地址(比如:http://localhost:8080/demo/demoManage.jsp);二是登录失效。有需要的可以将下面的代码再详细判断是登录失效还是未登录。

<%String user=(String)session.getAttribute("sessionname");
if(user==null)
{
%>
<script>
alert('尊敬的用户,您未登录或登录已经失效,请重新登录,谢谢!');
window.location.href="login.jsp";
</script>
<%
}
%>

step4:登录有效时间设置,在web.xml中加上如下代码,比如我设置登录有效时间是15min:

<session-config>
<session-timeout>15</session-timeout>
</session-config>

若是未登录或者登录失效就会弹出以下,点击之后跳转到登录窗口。



这样就基本可以了,此外也可以通过HTTP的状态码(401.1)来判断登录是否失效,有空再研究
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jsp servlet 登录失效