login.jsp--表单并验证
<span style="font-size:14px;"><%@ page language="java" contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="login.jsp" method="post" name="myform">
用户名:<input type="text" name="name"><br> 密 码:<input
type="password" name="password"><br> <input
type="submit" value="提交"> <input type="reset" value="重置">
</form>
<%
String name=request.getParameter("name");
String psw=request.getParameter("password");
if (!(name == null || "".equals(name) || psw == null
|| "".equals(psw))) {
if ("admin".equals(name) && "123456".equals(psw)) {
response.setHeader("refresh", "2;URL = welcome.jsp");
session.setAttribute("userid", name);//将登陆的用户名保存到session中
session.setAttribute("password",psw);
%>
<h3>用户登录成功,2秒后跳转</h3>
<h3>
如果没有跳转,请按<a href="welcome.jsp">这里</a>
</h3>
<%
} else {
%>
<h3>输入信息有误</h3>
<%
}
}
%>
</body>
</html></span>
welcome.jsp首页
<%@ page language="java" contentType="text/html" pageEncoding="UTF-8"%>
<%-- <%@ page package="import javax.servlet.http.*" %> --%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
if(session.getAttribute("userid")!=null){
%>
<h3>
欢迎<%=session.getAttribute("userid") %>欢迎光临本系统, <a href="logout.jsp">注销</a>!
</h3>
<%
}else{//非法用户,没有登录过,则session范围内没有属性存在
%>
<h3>
请先进行系统的<a href="login.jsp">登录</a>
</h3>
<%
}
%>
</body>
</html>
log_out.jsp注销
<%@ page language="java" contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
response.setHeader("refresh", "2;URL=login.jsp");
session.invalidate();//注销
%>
<h3>你已经成功推出本系统,两秒返回首页</h3>
<h3>如果没有返回,请按<a href="login.jsp">这里</a></h3>
</body>
</html>
上述是通过session进行登陆验证
完成此类功能的其他方法(会话跟踪技术)
四种会话跟踪技术:
- 通过session提供的方法保存
- 使用Cookie保存信息
- 通过表单的隐藏域保存信息
- 通过地址重写的方式保存信息
根据不同的情况选择不同的操作。
如果客户端禁用了Cookie操作,只能通过隐藏域或者地址重写的方式保存
例如:将SessionId设置在地址之后
welcome.jspJSESSIONID=。。。。。。。(sessionid)
这种情况会有安全方面的隐患,所以一般使用session保存,客户端是否禁用Cookie,不属于开发人员关心的问题。