Java Cookie的使用以及一个小案例



首先,在jsp文件中做一个<form>表单:

<form action = "LoginServlet" method = "post">
   用户名<input type = "text" id = "username" name = "username"><br>
   密码<input type = "password" id = "pwd" name = "pwd"><br>
   <select id = "timelength" name = "timelength">
   		<option value ="0" selected >everytime</option>
   		<option value = "10">10days</option>
   		<option value = "20">20days</option>
   </select><br>
   <input type = "submit" value = "登陆">

在写入cookie的获取代码:
 <%String username = null;
  	String password = null;
  	//获取请求当中的所有cookie对象
  	Cookie[] cookies = request.getCookies();
  	//只要存在cookie就查找是否有name为"username"或者"password"
  	if(cookies!=null){
  		//进行遍历
  		for(Cookie cookie:cookies){
  			if(cookie.getName().equals("username")){
  				username = cookie.getValue();
  			}
  			if(cookie.getName().equals("password")){
  				password = cookie.getValue();
  			}
  		}
  	}
  	//如果存在,则直接跳转到LoginServlet,进行登陆验证,不再需要输入用户名和密码
  	if(username!=null&&password != null){
  		request.getRequestDispatcher("LoginServlet?username="+username+"&pwd="+password).forward(request, response);
  	}
  %>

新建LoginServlet

doPost方法中写

		String username = request.getParameter("username");
		String pwd = request.getParameter("pwd");
		if (username.equals("walter")&&pwd.equals("123")) {
			System.out.println("did");
			String timelength = request.getParameter("timelength");
			int days = 0;
			if (timelength!=null) {
				days = Integer.parseInt(timelength);
			}
			if(days!=0){
				Cookie usernameCookie = new Cookie("username", username);
				Cookie passwordCookie = new Cookie("password", "pwd");
				usernameCookie.setMaxAge(days*24*3600);
				passwordCookie.setMaxAge(days*24*3600);
				response.addCookie(usernameCookie);
				response.addCookie(passwordCookie);
			}
			request.getRequestDispatcher("jj.jsp").forward(request, response);
			
			
		}
	}
这样下次就可以直接登陆jj.jsp了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值