spring-boot后端解决跨域问题

代码

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.fastjson.JSONObject;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * Copyright (C), 2019-2019, 北京力盟亚有限公司
 * @Description: 过滤器
 * @Author: qianxi
 * @Date: 2019/10/28 17:47
 * @version:1.0
 */
//@WebFilter(value="/*",filterName = "aaaaaLoggingFilter" )
@Configuration
public class LoggingFilterConfig  implements Filter {
//    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        log.info("接收Object报文:{} \n Exception={} " , o , e );
    }
    @Bean
    public FilterRegistrationBean registrationBean(){
        FilterRegistrationBean filter = new FilterRegistrationBean(new LoggingFilterConfig());
        filter.addUrlPatterns("/*");
        //多个过滤器时执行顺序
        // 最高级别。
        filter.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE);
        return filter;
    }

    private final static Log log = LogFactory.get();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse res,
                         FilterChain chain) throws IOException, ServletException {
        // TODO Auto-generated method stub
        request.setCharacterEncoding("UTF-8");
        res.setCharacterEncoding("UTF-8");

        HttpServletRequest req = (HttpServletRequest)request;
        Map<String, Object> map = new HashMap<String, Object>();

        // Get request URL.
        map.put("URL", req.getRequestURL());
        map.put("Method", req.getMethod());
        map.put("Protocol",req.getProtocol());
        // 获取header信息

        List<Map<String,String>> headerList = new ArrayList<>();
        Map<String,String> headerMaps = new HashMap<String,String>();
        for(Enumeration<String> enu = req.getHeaderNames(); enu.hasMoreElements();){
            String name = enu.nextElement();
            headerMaps.put(name,req.getHeader(name));
        }
        headerList.add(headerMaps);
        map.put("headers", headerList);
        //获取parameters信息

        List<Map<String,String>> parameterList = new ArrayList<>();
        Map<String,String> parameterMaps = new HashMap<String,String>();
        for(Enumeration<String> names = req.getParameterNames();names.hasMoreElements();){
            String name = names.nextElement();
            parameterMaps.put(name, req.getParameter(name));
        }
        parameterList.add(parameterMaps);
        map.put("parameters", parameterList);
        String line = "";
        // 获取请求体信息
//            if (req.getMethod().equalsIgnoreCase("POST")) {
//                int len = req.getContentLength();
//                char[] buf = new char[len];
//                int bufcount = requestWrapper.getReader().read(buf);
//                if (len > 0 && bufcount <= len) {
//                    line = String.copyValueOf(buf).substring(0, bufcount);
//                }
//            } else if (req.getMethod().equalsIgnoreCase("GET")) {
        int idx = req.getRequestURL().indexOf("?");
        if (idx != -1) {
            line = req.getRequestURL().substring(idx + 1);
        } else {
            line = null;
        }
//            }

        if (line != null) {
            map.put("Context", new String[] { line });
        }
        log.info("接收请求报文:\n"+ JSONObject.toJSONString(map));
        HttpServletResponse response = (HttpServletResponse) res;
        // 解决跨域问题。
        response.setHeader("Access-Control-Allow-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");
        chain.doFilter(request, response);
        // 辞书
//      log.info("接收response报文:\n"+ response.getContentType());
    }

    @Override
    public void destroy() {

    }

}

参考资料

  • java后端解决跨域问题

你可能感兴趣的:(计算机基础,#,力盟亚任职,#,spring家族,spring-boot,跨域)