在Java中处理跨域问题通常可以通过在Controller中添加注解来实现。以下是几种常见的处理跨域问题的方法:
@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() {}
}
以上是两种处理跨域问题的常见方法,可以根据具体的需求选择适合的方式来处理跨域请求。