如何测试在 Java/J2EE 中是否启用了 cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/318938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 11:56:19 来源:igfitidea点击:
How do you test if cookies are enabled in Java/J2EE
提问by Stephane Grenier
Testing:
测试:
return request.getCookies() == null;
is not an appropriate way test. Is there another way?
不是一个合适的方式测试。还有其他方法吗?
采纳答案by digitalsanctum
You generally want to use JavaScript to determine if the client's browser has cookies enabled:
您通常希望使用 JavaScript 来确定客户端的浏览器是否启用了 cookie:
<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's browser
//do whatever
</script>
回答by RealHowTo
Set a cookie and try to read it back.
设置一个 cookie 并尝试读取它。
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);
}
}

