I\'ve initialized cooke like this in my JSP,
String timeStamp = new SimpleDateFormat(\"dd:MM:yyyy_HH:mm:ss:SSS\").format(Calendar.getInstance().getTime());
t
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
HttpSession session = request.getSession();
AccountDAO db = new AccountDAO();
Account ac = (Account) db.getAll(username, password);
if (ac != null) {
String remember = request.getParameter("remember");
if (remember != null) {
Cookie c_user = new Cookie("username", username);
Cookie c_pass = new Cookie("password", password);
c_user.setMaxAge(3600 * 24 * 30);
c_pass.setMaxAge(3600 * 24 * 30);
response.addCookie(c_user);
response.addCookie(c_pass);
session.setAttribute("display_name", ac.getDisplayName());
request.getRequestDispatcher("Detail.jsp").forward(request, response);
} else {
session.setAttribute("display_name", ac.getDisplayName());
request.getRequestDispatcher("Detail.jsp").forward(request, response);
}
} else {
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
In kotlin it will be much shorter:
fun HttpServletRequest.getCookie( name: String) = cookies.firstOrNull { it.name == name }
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = "";
String password = "";
// Get an array of Cookies associated with this domain
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals("username")) {
username = cookies[i].getValue();
}
if (cookies[i].getName().equals("password")) {
password = cookies[i].getValue();
}
}
}
AccountDAO l = new AccountDAO();
Account a = l.getAll(username, password);
if (a != null) {
request.getRequestDispatcher("Detail.jsp").forward(request, response);
} else {
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
You are using the wrong method for reading the cookies..
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("cookieName")) {
//do something
//value can be retrieved using #cookie.getValue()
}
}
}
use this. No need to detect the cookie for particular user just deactivate it.
Ready to use generic method:
public static Cookie getCookie(HttpServletRequest request, String name) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(name)) {
return cookie;
}
}
}
return null;
}
Cookie[] cookies = request.getCookies();
int i = 0;
for (Cookie cookie : cookies ) {
Sytem.out.println(cookies[i].getName());
Sytem.out.println(cookies[i].getValue());
i++;
}