Java 解决跨域问题

Java 解决跨域问题

跨域问题基础认知

跨域定义

跨域(Cross-Origin)是指浏览器基于 同源策略 的安全限制,当网页向不同协议、域名或端口的服务器发起资源请求时,视为跨域请求,浏览器会拦截该请求的响应。

同源策略核心要求

同源需满足 协议、域名、端口 三者完全一致,例如:

  • 允许:http://localhost:8080/indexhttp://localhost:8080/api/user(三者一致)
  • 禁止:http://localhost:8080/indexhttps://localhost:8080/api/user(协议不同)
  • 禁止:http://localhost:8080/indexhttp://127.0.0.2:8080/api/user(域名不同)
  • 禁止:http://localhost:8080/indexhttp://localhost:8081/api/user(端口不同)

同源策略目的

核心是防止恶意脚本窃取敏感数据,保障 Web 应用的安全性。

Java 后端跨域解决方案(CORS 方式)

通过在服务器端设置跨域响应头,允许浏览器接收跨域请求,是最主流的跨域解决方案。

基础跨域配置(Servlet 示例)

doGetdoPost 方法中添加响应头:

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // 允许所有域名跨域访问(生产环境建议指定具体域名,如 "https://example.com")
    resp.setHeader("Access-Control-Allow-Origin", "*");
    // 允许的 HTTP 请求方法
    resp.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
    // 允许的请求头(如 Content-Type)
    resp.setHeader("Access-Control-Allow-Headers", "Content-Type");
    // 跨域配置缓存时间(3600 秒内无需重复校验)
    resp.setHeader("Access-Control-Max-Age", "3600");
    // 允许携带 Cookie
    response.setHeader("Access-Control-Allow-Credentials", "true"); 
    // 业务逻辑代码...
}

处理预检请求(OPTIONS 方法)

当发送 POST(非表单格式)、PUT、DELETE 等请求时,浏览器会先发送 OPTIONS 预检请求,需重写 doOptions 方法处理:

@Override
public void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // 与 doGet 中跨域配置一致
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Credentials", "true");
}
posted @ 2025-12-04 13:44  Jing61  阅读(3)  评论(0)    收藏  举报