如何测试Java / J2EE中是否启用了cookie

时间:2021-01-11 07:28:32

Testing:

return request.getCookies() == null;

is not an appropriate way test. Is there another way?

不是一种合适的测试方式。还有另一种方式吗?

2 个解决方案

#1


4  

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>

#2


6  

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);
    }
}

#1


4  

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>

#2


6  

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);
    }
}