在Java中处理跨域问题通常可以通过在Controller中添加注解来实现。以下是几种常见的处理跨域问题的方法:
- 使用@CrossOrigin注解:可以在Controller类或方法上使用@CrossOrigin注解来允许特定的域名或URL进行跨域访问。示例代码如下:
@CrossOrigin(origins = "http://example.com") @RestController public class MyController { @GetMapping("/hello") public String hello() { return "Hello!"; } }
- 配置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() {} }
以上是两种处理跨域问题的常见方法,可以根据具体的需求选择适合的方式来处理跨域请求。