1. 程式人生 > >springboot-shiro-ajax 跨域問題參考方案

springboot-shiro-ajax 跨域問題參考方案

1.配置
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.cors.CorsConfiguration;
import 
org.springframework.web.cors.UrlBasedCorsConfigurationSource; @Configuration public class MyConfig { private CorsConfiguration buildConfig() { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin("*"); corsConfiguration.addAllowedHeader("*"
); corsConfiguration.addAllowedMethod("*"); return corsConfiguration; } @Bean public MyCrosFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", buildConfig()); // 4 return new
MyCrosFilter(source); } @Bean @Order(Ordered.HIGHEST_PRECEDENCE) public FilterRegistrationBean crosFilterRegistrationBean(){ /* log.info("-----註冊跨域過濾器-------"); */ FilterRegistrationBean frb = new FilterRegistrationBean(); frb.setOrder(Ordered.HIGHEST_PRECEDENCE); frb.setFilter(corsFilter()); frb.addUrlPatterns("/*"); frb.setName("crosFilter"); return frb; } }
2.過濾器
import org.springframework.util.Assert;
import org.springframework.web.cors.*;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyCrosFilter extends OncePerRequestFilter {

    private final CorsConfigurationSource configSource;
    private CorsProcessor processor = new DefaultCorsProcessor();

/**
     * Constructor accepting a {@link CorsConfigurationSource} used by the filter
     * to find the {@link CorsConfiguration} to use for each incoming request.
     * @see UrlBasedCorsConfigurationSource
     */
public MyCrosFilter(CorsConfigurationSource configSource) {
        Assert.notNull(configSource, "CorsConfigurationSource must not be null");
        this.configSource = configSource;
    }


/**
     * Configure a custom {@link CorsProcessor} to use to apply the matched
     * {@link CorsConfiguration} for a request.
     * <p>By default {@link DefaultCorsProcessor} is used.
     */
public void setCorsProcessor(CorsProcessor processor) {
        Assert.notNull(processor, "CorsProcessor must not be null");
        this.processor = processor;
    }

    @Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        if (CorsUtils.isCorsRequest(request)) {
//System.out.println("ORGIN----"+request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token,XX-Token,XX-Device-Type,sessionID");
            CorsConfiguration corsConfiguration = this.configSource.getCorsConfiguration(request);
            if (corsConfiguration != null) {
                boolean isValid = this.processor.processRequest(corsConfiguration, request, response);
                if (!isValid || CorsUtils.isPreFlightRequest(request)) {
                    return;
                }
            }
        }
        filterChain.doFilter(request, response);
    }

}
3.跨域輸出
 /**
     * (跨域)輸出JSON
     */
protected void writeJson(Result result) {
        PrintWriter out = null;
        try {
            HttpServletResponse response=getResponse();
            HttpServletRequest request=getRequest();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            response.setHeader("Access-Control-Allow-Credentials","true"); //是否支援cookie跨域
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
            response.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token,XX-Token,XX-Device-Type,sessionID");
//            JSONObject jsonObject = new JSONObject();
try {
                out = response.getWriter();
                JSON json = (JSON) JSONObject.toJSON(result);
/*
                Map<String,Object> map=new HashMap<>();
                map.put("data",result);
                JSON json = (JSON) JSONObject.toJSON(map);
*/
out.write(String.valueOf(json));
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
4.前端
$.ajax({
url:url,
//加上這句話
xhrFields: {
           withCredentials: true
       },
       crossDomain: true,
 
success:function(result){
alert("test");
},
error:function(){
}
});