jsp之登陆页面和cookie

时间:2022-12-13 17:07:59

功能:简单的登陆程序,进入首页as1.jsp,如果是首次登陆,跳转到登陆界面login.jsp,成功后,保存cookie,跳转到index.jsp,设置flag,再回到as1.jsp




as1.jsp

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%

if(session.getAttribute("flag") != null && session.getAttribute("flag").equals("ok")){
out.print("<h1>welcome.</h1>");
}else{
%>
<jsp:forward page="login.jsp"/>

<% } %>

注意这里的else不可以省略大括号,否则算代码不完整,无法执行


login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%
String pName = request.getParameter("name");
String pLove = request.getParameter("love");
Cookie[] cookies = request.getCookies();
if(pName != null){
Cookie c = new Cookie("name",pName);
c.setMaxAge(300);
response.addCookie(c);
}else{
if(cookies != null){
for(int i = 0;i<cookies.length;i++){
if(cookies[i].getName().equals("name")){
pName = cookies[i].getValue();
}
}
}
}

if(pLove != null){
Cookie c = new Cookie("love",pLove);
c.setMaxAge(300);
response.addCookie(c);
}else{
if(cookies != null){
for(int i = 0;i<cookies.length;i++){
if(cookies[i].getName().equals("love")){
pLove = cookies[i].getValue();
}
}
}
}

%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>

<body>
<h1 align="center">测试cooki</h1>
<hr>

<form action="index.jsp" method='post'>
姓名:<input type='text' name='name' value='<%=pName%>'><br>
兴趣:<input type='text' name='love' value='<%=pLove%>'>
<input type='submit' value='tijiao'>
</form>
</body>
</html>

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>

<body>
<%
if(request.getParameter("name").equals("admin") && request.getParameter("love").equals("123")){
System.out.println("2222");
session.setAttribute("flag","ok");
session.setMaxInactiveInterval(-1);
%>
<jsp:forward page="as1.jsp"/>
<% }
else{
out.print("<h1>error msg</h1>");
}
%>
</body>
</html>