본문 바로가기
Developer/Javascript & jQuery

[javascript] java필터를 통한 ajax 크로스 도메인 요청 하기

by 순수한소년 2020. 11. 4.
728x90
반응형

 

SimpleCORSFilter.Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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;
 
 
 
public class SimpleCORSFilter implements Filter {
 
 
 
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
 
        HttpServletResponse response = (HttpServletResponse) res;
 
        response.setHeader("Access-Control-Allow-Origin""*");
 
        response.setHeader("Access-Control-Allow-Methods""POST, GET, DELETE, PUT");
 
        response.setHeader("Access-Control-Max-Age""3600");
 
        response.setHeader("Access-Control-Allow-Headers""x-requested-with, origin, content-type, accept");
 
        chain.doFilter(req, res);
 
    }
 
 
 
    public void init(FilterConfig filterConfig) {}
 
 
 
    public void destroy() {}
 
 
 
}
 
 
cs

 

web.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 
    <filter>
 
        <filter-name>SimpleCORSFilter</filter-name>
 
        <filter-class>rest.api.filter.SimpleCORSFilter</filter-class>
 
    </filter>
 
    <filter-mapping>
 
        <filter-name>SimpleCORSFilter</filter-name>
 
        <url-pattern>/*</url-pattern>
 
    </filter-mapping>
 
 
 
cs

 

호출하는 jsp

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
  $.ajax({
 
      url : "http://localhost:8080/api/employees"
 
    , async : true
 
    , type : "POST"
 
    , cache:false
 
    , timeout : 30000 
 
    , data : JSON.parse(JSON.stringify({"id:id, pw:pw"}))
 
    , dataType : "json"
 
    , xhrFields: {
 
            withCredentials: false
 
      }
 
    , beforeSend: function (xhr) {
 
        xhr.setRequestHeader("Accept""application/json");
 
      }
 
    , success : function (data, statusText, xhr) { 
 
        console.log("success status :: " + xhr.status + " || statusText :: " + statusText);
 
      }
 
    , error : function (xhr, statusText, errorThrown) { 
 
        console.log("error status :: " + xhr.status + " || statusText :: " + xhr.responseText + " || errorThrown :: " + errorThrown);
 
      }
 
  });
 
 
cs

 

주의할점

async : true ( false 수행이 안됩니다. )

출처: https://hermeslog.tistory.com/335 [헤르메스 LIFE]

 

[CORS] javascript ajax 크로스 도메인 요청 하기

1. 개발환경 ajax + RESTfule 2. 시나리오. RESTful을 이용해서 서로 다른 domain간에 Json 으로 데이터를 주고 받을 수 있다. 그림 출처 : 시나몬 브레드님의 javascript ajax 크로스 도메인 요청 하기 (CORS..

hermeslog.tistory.com

 

728x90
반응형