How do you check if cookies are allowed in Java / J2EE

Testing:

return request.getCookies() == null; 

not a suitable way. Is there another way?

+4
source share
2 answers

Typically, you want to use JavaScript to determine if client browser cookies are allowed:

 <script type="text/javascript"> var cookieEnabled=(navigator.cookieEnabled)? true : false //if not IE4+ nor NS6+ if (typeof navigator.cookieEnabled=="undefined" && !cookieEnabled){ document.cookie="testcookie" cookieEnabled=(document.cookie.indexOf("testcookie")!=-1)? true : false } //if (cookieEnabled) //if cookies are enabled on client browser //do whatever </script> 
+4
source

Set a cookie and try to read it.

 import javax.servlet.*; import javax.servlet.http.*; public class Test4Cookies extends HttpServlet { private static final Cookie cookie = new Cookie( "hello" , "world" ); private static final String paramName = "foo"; private static final String successURI = "/success.htm"; private static final String failureURI = "/failure.htm"; public void doPost(HttpServletRequest req, HttpServletResponse res) { if ( req.getParameter( paramName ) == null ) { res.addCookie( cookie ); res.sendRedirect(req.getRequestURI() +"?"+ paramName +"=bar" ); } else { res.sendRedirect (( req.getCookies().length == 0 ) ? failureURI : successURI ) } public void doGet(HttpServletRequest req, HttpServletResponse res) { doPost(req, res); } } 
+6
source

All Articles