Use cookies

From Documentation

Stop.png This documentation is for an older version of ZK. For the latest one, please click here.


Stop.png This documentation is for an older version of ZK. For the latest one, please click here.


For a Web application, cookies are used for maintaining specific information about users at client browser side. In the following example, when you click the button, a cookie named "user" will be set and get.

<window use="MyWindow">
	<button label="cookie" forward="onCookie()"/>
</window>

And MyWindow.java,

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.zkoss.zk.ui.Executions;
import org.zkoss.zul.Window;
 
public class MyWindow extends Window {	
	public void onCookie(){
		try {
			//add cookie
			HttpServletResponse response = (HttpServletResponse)Executions.getCurrent().getNativeResponse();
			Cookie userCookie = new Cookie("user", "xxx123");
			response.addCookie(userCookie);
			
			//get cookie
			Cookie [] cookies = ((HttpServletRequest)Executions.getCurrent().getNativeRequest()).getCookies();
			System.out.println(cookies[0].getName());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}



Last Update : 2022/01/19

Copyright © Potix Corporation. This article is licensed under GNU Free Documentation License.