Servlet开发中出现No 'Access-Control-Allow-Origin' header is present on the requested resource解决办法

xiaoxiao2021-03-01  3

方法一:在servlet中的调用的函数中,对于HttpServletResponse,将其设置为response.setHeader("Access-Control-Allow-Origin", "*")。

方法二:原文

首先新建filter类

package com.itxc.filter; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class CORSFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletResponse httpResponse = (HttpServletResponse) servletResponse; httpResponse.addHeader("Access-Control-Allow-Origin", "*"); filterChain.doFilter(servletRequest, servletResponse); } @Override public void destroy() { } } 12345678910111213141516171819202122232425

然后在web.xml中使用上述filter即可

<filter> <filter-name>CorsFilter</filter-name> <filter-class>com.itxc.filter.CORSFilter</filter-class> </filter> <filter-mapping> <filter-name>CorsFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>亲测有效。
转载请注明原文地址: https://www.6miu.com/read-3650244.html

最新回复(0)