标签:style core post count nbsp add spring app throws
1. 原生支持
Application 启动类添加以下代码:
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import javax.servlet.Filter;
import java.net.InetAddress;
import java.net.UnknownHostException;
@Bean public Filter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); config.addAllowedMethod("*"); config.addExposedHeader("x-auth-token"); config.addExposedHeader("x-total-count"); source.registerCorsConfiguration("/**",config); return new CorsFilter(source); }
2. 自定义 Filter
import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; /** * CorsFilter is 解决跨域问题 * * @author zzt * @date 2019/7/28 11:32:00 */ @Component @WebFilter(urlPatterns = "/**", filterName = "corsFilter") public class CorsFilter implements Filter { @Override public void init(FilterConfig filterConfig) { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse)servletResponse; HttpServletRequest request = (HttpServletRequest)servletRequest; String origin = request.getHeader("Origin"); response.setHeader("Access-Control-Allow-Origin", origin); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Authorization, Accept, Origin, XRequestedWith, Content-Type, LastModified"); response.setHeader("Access-Control-Allow-Credentials", "true"); String method = request.getMethod(); if (method.equalsIgnoreCase("OPTIONS")) { servletResponse.getOutputStream().write("Success".getBytes("utf-8")); } else { filterChain.doFilter(servletRequest, servletResponse); } } @Override public void destroy() { } }
3. 自定义Configuration
略
标签:style core post count nbsp add spring app throws
原文地址:https://www.cnblogs.com/tarencez/p/11711513.html