在Java中處理跨域問題通常可以通過在Controller中添加注解來實現(xiàn)。以下是幾種常見的處理跨域問題的方法:
@CrossOrigin(origins = "http://example.com")
@RestController
public class MyController {
@GetMapping("/hello")
public String hello() {
return "Hello!";
}
}
@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ù)具體的需求選擇適合的方式來處理跨域請求。