SpringMVC 解決跨域和亂碼問題

今天再作接口對接的時候,忽然遇到了這個問題:前端

      我在Postman 中測試正常的接口,在前端那邊忽然出現了403跨域的問題,所以我在白度中找了好幾種方法,其中比較簡單有用的,解決了問題是以下方法: java

1; 新建類:web

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.http.HttpServletResponse;

/**
 *@description  TODO 跨域解決類
 *@author  geYang
 **/
public class SimpleCORSFilter implements Filter{

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub
        
    }
    
    /**
     *  請求頭註釋:
     *  0: response.setCharacterEncoding("UTF-8"); 設置響應參數爲UTF-8
     *  1: Access-Control-Allow-Origin 能夠請求的域; *爲容許全部域請求
     *  2: Access-Control-Allow-Methods 請求方式
     *  3: Access-Control-Max-Age  請求數據緩存時間(單位秒)
     *  4: Access-Control-Allow-Credentials 保持跨域 AJAX時的 Cookie
     *  5: Access-Control-Allow-Headers 請求頭:
     *      (1): X-Requested-With 請求頭用於在服務器端判斷request來自AJAX請求仍是傳統請求;
     **/
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        // TODO 解決跨域錯誤
        HttpServletResponse response = (HttpServletResponse) resp;
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "X-Requested-With");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Max-Age", "600");
        chain.doFilter(req, resp);
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
        
    }

    
    
}

2: 在 web.xml 中進行配置:spring

<!-- 
		org.springframework.web.filter.CharacterEncodingFilter
	 -->
	<filter>
		<filter-name>SetCharacterEncoding</filter-name>
		<filter-class>
			com.xt.shop.base.interceptor.SimpleCORSFilter
		</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
        <filter-name>SetCharacterEncoding</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

這樣跨域問題就解決了, 但 Controller 層中接收參數出現了中文亂碼狀況;跨域

解決方法爲: 在攔截器中加入:緩存

        //設置接收編碼爲UTF-8
        request.setCharacterEncoding("UTF-8");
服務器

這句代碼就能夠啦...app

相關文章
相關標籤/搜索