JSP简单的Cookie登录demo

<%@page import="java.net.URLDecoder"%>
<%@page language ="java" contentType="text/html;charset=GB18030" pageEncoding="utf-8" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>use request</title>
</head>
<body>
<%
	 Cookie[] cookies = request.getCookies();
	 String user = "";
	 String date = "";
	 if(cookies != null){
		 for(Cookie c : cookies){
			 if(c.getName().equals("mrCookie")){
				 user = URLDecoder.decode(c.getValue().split("#")[0]);
				 date = c.getValue().split("#")[1];
			 }
		 }
	 }
	 
	 if("".equals(user) && "".equals(date)){
%>
	first come
	<form action = "deal.jsp" method = "post">
		input name: <input name = "user" type = "text" value="">
		<input type="submit" value="ok"> 
	</form>
<% 
	}else{ 
%>
		welcome [<b><%=user %></b>] again<br>
		<%=date %>
<% }%>

	
</body>
</html>
<%@page import="java.net.URLEncoder"%>
<%@page language ="java" contentType="text/html;charset=GB18030" pageEncoding="utf-8" %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>use request</title>
</head>
<body>
<% 
	request.setCharacterEncoding("GB18030");
	String user = URLEncoder.encode(request.getParameter("user"),"utf-8");
	Cookie cookie = new Cookie("mrCookie", user + "#" + new java.util.Date().toLocaleString());
	
	cookie.setMaxAge(60*60*24*30);
	response.addCookie(cookie);
%>

<script type="text/javascript">window.location.href="ysh.jsp"</script>

</body>
</html>


猜你喜欢

转载自blog.csdn.net/qq_27469549/article/details/80405020