使用Java方式存cookie(保存用户名和密码)

       public void login(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
Org_employeeBiz org_employeeBiz=new Org_employeeBizImpl();
PrintWriter out = response.getWriter();
// 获取用户名和密码
String loginname = request.getParameter("loginname");
String loginpassword = request.getParameter("loginpassword");
Org_Employee org_Employee = org_employeeBiz.login(loginname,
loginpassword);
if (org_Employee != null) {
String flag=request.getParameter("remember");
if(flag.equals("1")){
//把对象存入cookie中
Cookie cookieName=new Cookie("loginname", loginname);
Cookie cookiePassword=new Cookie("loginpassword", loginpassword);
cookieName.setPath(request.getContextPath());  
cookiePassword.setPath(request.getContextPath());  
cookieName.setMaxAge(60*60);//只保存一分钟 
cookiePassword.setMaxAge(60*60);//只保存一分钟 
response.addCookie(cookieName);
response.addCookie(cookiePassword);
}else{
  //清除cookie
  Cookie cookies[] = request.getCookies();    
      if (cookies != null)    
      {    
          for (int i = 0; i < cookies.length; i++)    
                                    //清空cookie值“”
                 cookies[i].setValue("");
                                    //设置有限时间为0
                 cookies[i].setMaxAge(0);
                                     //添加有效时间为0的cookie
                response.addCookie(cookies[i]);
                  //Cookie cookieName = new Cookie("loginname","");//这边得用"",不能用null    
                 // Cookie cookiePassword = new Cookie("loginpassword","");//这边得用"",不能用null    
                 // cookieName.setPath(request.getContextPath());//设置成跟写入cookies一样的    
                 // cookiePassword.setPath(request.getContextPath());//设置成跟写入cookies一样的    
                 // cookie.setDomain(".wangwz.com");//设置成跟写入cookies一样的    
                 // cookieName.setMaxAge(0);    
                 // cookiePassword.setMaxAge(0);    
                 // response.addCookie(cookieName);    
                  //response.addCookie(cookiePassword);    
              }    
          }    
      }    
}


// 把对象存入session中
request.getSession().setAttribute("org_Employee", org_Employee);
response.sendRedirect("index.jsp");
} else {
out.write("<script>alert('用户名或密码,请重新登录!');location.href='login.jsp'</script>");
}


}
可以使用 `java.net.HttpURLConnection` 类发送 HTTP 请求并获取响应。可以通过以下步骤来实现通过用户名密码获取 HTTP 请求的 Cookie: 1. 创建一个 `java.net.URL` 对象来表示要发送请求的 URL。 2. 打开一个 `java.net.HttpURLConnection` 对象并设置请求方法为 POST。 3. 设置请求头信息,包括 Content-Type 和 User-Agent。 4. 构造请求参数,并将其写入请求体中。 5. 发送请求并获取响应状态码。 6. 读取响应体中的 Cookie 信息,并将其保存。 以下是一个示例代码,其中 `username` 和 `password` 分别表示要发送的用户名密码: ```java import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; public class HttpCookieExample { public static void main(String[] args) throws Exception { String username = "your_username"; String password = "your_password"; String url = "http://example.com/login"; // Step 1: Create URL object URL obj = new URL(url); // Step 2: Open connection HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); // Step 3: Set request headers con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setRequestProperty("User-Agent", "Mozilla/5.0"); // Step 4: Set request parameters String urlParameters = "username=" + URLEncoder.encode(username, "UTF-8") + "&password=" + URLEncoder.encode(password, "UTF-8"); // Write request body con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); // Step 5: Get response status code int responseCode = con.getResponseCode(); // Step 6: Read response body and get cookies BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); String cookie = null; while ((inputLine = in.readLine()) != null) { response.append(inputLine); if(inputLine.contains("Set-Cookie")) { cookie = inputLine.split(";")[0].split("=")[1]; } } in.close(); // Print response and cookie System.out.println("Response Code : " + responseCode); System.out.println("Response Body : " + response.toString()); System.out.println("Cookie : " + cookie); } } ``` 以上示例代码中,我们使用了 `java.net.URLEncoder` 类将用户名密码进行 URL 编码,以便与请求一起发送。在发送请求时,我们需要将请求参数写入请求体中,可以通过 `java.io.DataOutputStream` 类实现。在读取响应体时,我们可以通过 `java.io.BufferedReader` 类逐行读取响应体,并从中提取 Cookie 信息。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值