Java – bhsm servlet does not allow the browser to cache user names

I have a requirement that the value should not be cached in the server, and the browser should not be cached as a cookie on the domain and session

So I chose to permanently redirect to value

Servlet:

@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.");
        }
    }
}

script:

<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>

Console output:

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

The user name I inserted is not returned after realload from browsercache

Why don't browsers cache?

Solution

Redirecting an Ajax request does not redirect the browser to the new location, if so, you will no longer have the page, you only need a response from the servlet

Therefore, when you refresh the page, you will request the original URL again from scratch and the user name will be lost

You can add the user name to the URL directly in javascript:

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

This appends "#username" to the URL in the address bar Then, when the page loads, you can populate the input of the request parameters (if any):

jQuery('.username').val( window.location.hash );
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>