java - BHSM-Servlet 不允许浏览器缓存用户名

标签 java jquery http servlets http-status-code-301

我有一个要求,即不应将值缓存在服务器或浏览器中作为域和 session 上的 cookie。

所以我选择永久重定向到这个值

小服务程序:

@Override
protected void service(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    String key = request.getParameter("key");
    String val = request.getContentType();
    if (val != null && val.length() == 0) {
        val = null;
    }
    String repeatText = request.getParameter("repeatText");
    if (val != null && repeatText == null) {
        response.setStatus(301); // moved permanent
        response.addHeader("Location", "?repeatText=" + val);
        System.out.println("Write");
    } else {
        if (repeatText != null) {
            response.setContentLength(repeatText.length());
            response.addHeader("pragma", "no-cache");
            response.addIntHeader("expires", BROWSER_CACHE_DAYS);
            response.getWriter().write(repeatText);
            System.out.println("Read and cache!");
        } else {
            response.sendError(304); // use from cache!
            System.out.println("Send use from cache.");
        }
    }
}

脚本:

<input class="username" />
<button>Login</button>

<script>
jQuery.ajax('theservlet?key=username').done(function(v){jQuery('.username').val(v);});
jQuery('button').click(function(){
  jQuery.ajax('theservlet?key=username',{contentType:jQuery('.username').val()})
});
</script>

控制台输出:

Send use from cache.
--- i enter username and press the button ---
Write
Read and cache!
--- now i make a reload ---
Send use from cache.

从浏览器缓存中重新加载后,没有返回我插入的用户名。

为什么浏览器不缓存?

EDIT: Added for explaintaition

最佳答案

重定向 ajax 请求不会将浏览器重定向到新位置,如果重定向了,您将不再拥有您的页面,您只会收到来自 servlet 的响应。

因此,当您刷新页面时,您将再次从头开始请求原始 URL,并且用户名会丢失。

您可以在 javascript 中直接将用户名添加到 URL 中:

jQuery('button').click(function(){
  var username=jQuery('.username').val();
  jQuery.ajax('theservlet?key=username',{contentType:username});
  window.location.hash=username;
});

这会将“#用户名”附加到地址栏中的 URL。然后在页面加载时,如果存在,您可以从请求参数填充输入:

jQuery('.username').val( window.location.hash );

关于java - BHSM-Servlet 不允许浏览器缓存用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29715465/

相关文章:

jQueryUI 对话框位置在 Chrome 和 Safari 中损坏

python - 我是否正确解析了这个 HTTP POST 请求?

java - StoredProcedureItemReader 和 JdbcCursorItemReader 的游标数据保留在 java 堆内存中还是数据库中

java - 从 Java 中的字符串中有效地删除特定字符(一些标点符号)?

Javascript 从单击的按钮写入文本区域

javascript - 如何将纯 JS 代码转换为 jQuery?

wcf - 为 HTTPS 和 HTTP 托管相同服务时为 "A registration already exists for URI"

http - 将输出流量路由到 mitmdump

java - IntelliJ IDEA : ClassNotFoundException if run Debug, 执行/运行确实有效

java - GUI 添加了组件,但显示时显示空白