Question #52715

Explain me about cookies and how it is used to get the previous log-in time without changing the value on pressing refresh button.
1

Expert's answer

2015-05-29T11:38:19-0400
<!DOCTYPE html>
<html>
<head>
<script></script>
</head>
</html>


Cookies are small pieces of data stored on the client-side by the web browser. They can be used to store information about the user's session, such as the time they logged in. Here's an example of how you can use cookies to store and retrieve the login time in a JSP page:


<%@ page import="java.util.Date" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%
    // Set the login time cookie
    Cookie loginTimeCookie = new Cookie("loginTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    loginTimeCookie.setMaxAge(60 * 60 * 24); // Expires in 24 hours
    response.addCookie(loginTimeCookie);
    // Get the login time cookie
    Cookie[] cookies = request.getCookies();
    String loginTime = "";
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("loginTime")) {
                loginTime = cookie.getValue();
                break;
            }
        }
    }
%>
<html>
<head>
    <title>Login Time Example</title>
</head>
<body>
    <h1>Welcome to our website!</h1>
    <p>You last logged in at: <%= loginTime %></p>
</body>
</html>


In this example, when the user logs in, a cookie named "loginTime" is created with the current date and time. This cookie is then sent back to the client, where it is stored by the browser. On subsequent requests, the server can retrieve the cookie and display the login time to the user. Even if the user refreshes the page, the login time will remain the same because the cookie value is not changed.

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!
LATEST TUTORIALS
APPROVED BY CLIENTS