Implementation of session (login and logout) and cookies (remember username and password)

Both session and cookie can also be used to save customer data, however, session saves data on the server side, while cookie saves data on the client side as a file
                login and logout
 
                 1. After logging in, save the username into the session:

request.getSession.setAttribute("userName","用户名");

                  That's it:

HttpSession s=request.getSession();//getSession() is equivalent to getSession(false).getSession(true) and creates a Session regardless of whether it currently exists. s.setAttribute("userName","username");

                2. Output username

System.out.println(request.getSession().getAttribute("userName"));

                3. Log out

request.getSession().removeAttribute("userName"));

 

           Remember username and password  

           

             1. Add data, set the validity period

//Use public void addCookie(Cookie cookie) method and public void setMaxAge(int expiry) method

Cookie cookie=new Cookie("user",username);

cookie.setMaxAge(60*60);//Valid for one hour

response.addCookie(cookie);

             2.获取数据

//使用public Cookie[] getCookies()方法

Cookie []cookies=request.getCookies();

String user="";

for(int i=0;i<cookies.length;i++){

if(cookies[i].getName.equals("user")){

user=cookies[i].getValue;

}

}

           3.在输入用户名的input框中调用

 

<input type="text" name="userName"value="<%=user>"

 

 

           4.禁用cookie(cookie资料容易被窃取,所以有的用户会禁用cookie)

 

               浏览器--》工具--》Internet选项--》隐私--》高级--》替代自动cookie处理--》将阻止选项勾选--》确定

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326771343&siteId=291194637