通过工具远程访问rest会出现
已阻止跨源请求:同源策略禁止读取位于 http://XXXXX:1200/gyly/busData 的远程资源。(原因:CORS 请求失败)。
修改方法
添加Filter
import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.filter.OncePerRequestFilter; public class CorsFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { response.addHeader("Access-Control-Allow-Origin", "*"); response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); response.addHeader("Access-Control-Allow-Headers", "origin, content-type, accept, x-requested-with, sid, mycustom, smuser"); filterChain.doFilter(request, response); } }
修改web.xml
<filter> <filter-name>CorsFilter</filter-name> <filter-class>com.interfaceservice.filter.CorsFilter</filter-class> </filter> <filter-mapping> <filter-name>CorsFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-29 21:20:09