在 Java 中可以通过设置 HTTP 响应头来确保 JavaScript 文件不被浏览器缓存。以下是具体的方法:
一、使用 Servlet 设置响应头
如果你的 Java 应用使用 Servlet 技术,可以在处理 JavaScript 请求的 Servlet 中设置响应头:
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; public class JavaScriptServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置响应内容类型为 JavaScript response.setContentType("application/javascript"); // 设置响应头,禁止缓存 response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); response.setHeader("Pragma", "no-cache"); // 输出 JavaScript 内容 PrintWriter out = response.getWriter(); out.println("console.log('This JavaScript is not cached.');"); } }
二、在 Spring Boot 中设置响应头
如果使用 Spring Boot,可以通过配置拦截器来设置响应头:
import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Date; public class NoCacheInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); response.setHeader("Pragma", "no-cache"); return true; } }
然后在配置类中注册拦截器:
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new NoCacheInterceptor()); } }
通过以上方法,无论使用传统的 Servlet 还是 Spring Boot 框架,都可以确保 JavaScript 文件不被浏览器缓存,每次请求都能获取到最新的 JavaScript 内容。