溫馨提示×

java controller 怎樣處理跨域問題

小樊
214
2024-06-15 14:00:34
欄目: 編程語言

在Java中處理跨域問題通常可以通過在Controller中添加注解來實現(xiàn)。以下是幾種常見的處理跨域問題的方法:

  1. 使用@CrossOrigin注解:可以在Controller類或方法上使用@CrossOrigin注解來允許特定的域名或URL進行跨域訪問。示例代碼如下:
@CrossOrigin(origins = "http://example.com")
@RestController
public class MyController {

    @GetMapping("/hello")
    public String hello() {
        return "Hello!";
    }
}
  1. 配置CorsFilter:也可以通過配置一個CorsFilter來處理跨域請求??梢蕴砑右粋€CorsFilter類來配置允許跨域訪問的域名和方法。示例代碼如下:
@Component
public class CorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");

        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, res);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) {}

    @Override
    public void destroy() {}
}

以上是兩種處理跨域問題的常見方法,可以根據(jù)具體的需求選擇適合的方式來處理跨域請求。

0