Struts 2 accessing Cookie object in Controller


            Actions implementing the CookiesAware interface will receive a Map of filtered cookies via the setCookiesMap method. Please note that the CookieInterceptor needs to be activated to receive a cookies map.

Code

To cookie in browser

package com.candidjava;

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

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class AddCookies extends ActionSupport implements ServletResponseAware {
	
	private static final long serialVersionUID = 1L;
	private HttpServletResponse response;
	private String username;

	
	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	@Override
	public String execute(){
		
		Cookie cookie = new Cookie("key", username);
		cookie.setMaxAge(60 * 60 * 24);
		response.addCookie(cookie);
		return SUCCESS;
	}
}

To get cookie from browser

package com.candidjava;

import java.util.Iterator;
import java.util.Map;

import java.util.Set;

import org.apache.struts2.interceptor.CookiesAware;

import com.opensymphony.xwork2.ActionSupport;

public class ShowCookies extends ActionSupport implements CookiesAware {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	Map<String,String> cookies;

	public Map<String,String> getCookies() {
		return cookies;
	}

	public void setCookiesMap(Map<String,String> cmap) {
		this.cookies = cmap;
	}

	@Override
	public String execute(){
		
		String cvalue=cookies.get("key");
		System.out.println(cvalue);
		
	
		return SUCCESS;
	}
}

Screenshot

            

            

Download

        Struts 2 cookieaware war

        Struts 2 cookieaware maven zip




Related Post

Comments


©candidjava.com