2017년 9월 14일 목요일

JSONP 및 Script console.log Tip


console.log 찍을 시 Object 상세 찍는법
console.log("object: %O", data); 

JSNOP  : http://kingbbode.tistory.com/26 여기에 제일 잘 정리되어있음
            크로스도메인 해결하는데 Spring security에서 막혀 있어 filter + jsonp 로 해결함
            http://www.codejs.co.kr/jquery-jsonp/
            http://dev.epiloum.net/1311



JSONP is a method for sending JSON data without worrying about cross-domain issues.
JSONP does not use the XMLHttpRequest object.

JSONP uses the <script> tag instead.

실행시 주의사항
1. web.xml 에 filter 설정해서 해당 url 크로스도메인 허용해줌
2. java 값 리턴시 callback 함수로 감싸주어야함
3. script에서 호출하고 받을때 callback 함수 이름이 동일해야함


XML 부분 
web.xml
<filter>
   <filter-name>cors</filter-name>
   <filter-class>com.test.api.common.util.CORSFilter</filter-class>
</filter>
<filter-mapping>
   <filter-name>cors</filter-name>
   <url-pattern>/test/*</url-pattern>

</filter-mapping>

Filter java 부분
public class CORSFilter implements Filter{

@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub

}

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {

        HttpServletResponse response = (HttpServletResponse) res;

        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");
        
        response.setHeader("Access-Control-Allow-Origin", "*");
        chain.doFilter(req, response);
}
}

JAVA 부분
@RequestMapping(value="/test.do", method = {RequestMethod.GET, RequestMethod.POST})
public void testApi(HttpServletRequest request, HttpServletResponse response) throws Exception{

try {
response.setContentType("text/html;charset=UTF-8"); //PrintWriter 한글깨짐해결

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
TestDetail testDetail = (TestDetail ) authentication.getPrincipal();
String userId    = testDetail .getMember().getId();
String userName  = testDetail .getMember().getUserName();

String callBack = request.getParameter("callback");  //jsonp callback 함수명

JSONObject obj=new JSONObject();

obj.put("userId", userId);
obj.put("userName", userName);

PrintWriter out = response.getWriter();
out.write(callBack + "("+obj.toString()+")");
out.flush();
out.close();
}
catch (Exception e){
logger.error("Exception : " + e.getMessage(), e);
}

}
Script 부분 

function apiCheck(){
 var aPI = "http://test/testApi.do?callback=?";  //callback 이게 컬백함수 이름임
 $.getJSON( testAPI, 
function( data ) {
console.log("data : " + data);
console.log("object: %O", data)
 });
}

댓글 없음:

댓글 쓰기