전체 페이지뷰

2014년 1월 12일 일요일

jsonp data with get method

magazien.js

Magazine = function()
{
};

jQuery.extend(Magazine.prototype,
{
_version : '1.0',
_service : '',
_module : '',
_func : '',
_firstCall : '',
_param :
{},
setVersion : function(x)
{
this._version = x;
},
setService : function(x)
{
this._service = x;
},
setModule : function(x)
{
this._module = x;
},
setFunc : function(x)
{
this._func = x;
},
setParam : function(x)
{
this._param = x;
},
setFirstCall : function(x)
{
this._firstCall = x;
},
getVersion : function()
{
return this._version;
},
getService : function()
{
return this._service;
},
getModule : function()
{
return this._module;
},
getFunc : function()
{
return this._func;
},
getParam : function()
{
return this._param;
},
getFirstCall : function()
{
return this._firstCall;
},
fire : function(fn, fnerr)
{
var requestData =
{};

requestData.version = this._version;
requestData.service = this._service;
requestData.module = this._module;
requestData.func = this._func;
requestData.param = this._param;
requestData.firstCall = this._firstCall;

$.ajax({
          type:"GET",
          url:WAS_SERVER_URL + "/service.do",
          data:escape(encodeURIComponent(JSON.stringify(requestData))),
          contentType:'application/json; charset=UTF-8',
          dataType:"JSONP",
          timeout:10000,
          success : function(responseData) {
          if( responseData.status == 'success' ) {
          if ($.isFunction(fn)) {
          fn.apply(fn, [ responseData, requestData.param ]);
          }
          else {
          showAlert($.i18n.prop('common.magazine_0001'));
          }
          }
          else {
          if ($.isFunction(fnerr)) {
          fnerr.apply(fnerr, [ requestData.param, responseData.code, responseData.message ]);
          }
          else {
       //   console.log(JSON.stringify(requestData.param));
          showAlert($.i18n.prop('common.magazine_0002'));
          }
          return;
          }
          },
//           complete : function(data) {
//        
//           },
          error : function(XMLHttpRequest, textStatus, errorThrown) {
          if( errorThrown == 'timeout') {
          if ($.isFunction(fnerr)) {
          fnerr.apply(fnerr, [ requestData.param, '-1', 'timeout' ]);
          }
          else {
          showAlert($.i18n.prop('common.magazine_0003'));
          }
          }
          else {
//           console.log(JSON.stringify(XMLHttpRequest));
//               console.log(JSON.stringify(textStatus));
//               console.log(JSON.stringify(errorThrown));
          }
          }
    });
}
});

------------------------------------------------
controller.java

@RequestMapping(value = "/service.do", method = { RequestMethod.GET, RequestMethod.POST })
public void serviceHandleRequest(HttpServletRequest request, HttpServletResponse response)
{
RequestDTO requestDTO = null;
ResponseDTO responseDTO = null;
String responseData = "";
PrintWriter out = null;

try {
out = response.getWriter();
} catch (IOException e) {
logger.error(e.getMessage());
return;
}
if( out == null ) {
logger.error("Failed to create Response's Writer!!");
return;
}

// Set Response Header
response.addHeader("Access-Control-Allow-Origin", "*");

        if( noCache ) {
       if( request.getProtocol().endsWith("1.1") ) {
        response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
       }
       else if( request.getProtocol().endsWith("1.0") ) {
    response.addHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
       }
        }
     
        requestDTO = getParameterFromRequest(request);
        if( requestDTO == null ) {
responseDTO = makeDefaultResponse(false, -1, "Failed to parse request data");
responseData = new Gson().toJson(responseDTO);
        out.println(responseData);
    out.flush();
    out.close();
return;
}
     
        long lStartTime = System.currentTimeMillis();
logger.info("ServiceController::serviceHandleRequest [" + requestDTO.getModule() + ":" + requestDTO.getFunc() + "] is Started");

        responseDTO = getResult(requestDTO);
        try {
if( !StringUtils.isEmpty(requestDTO.getCallback()) ) {
responseData = String.format("%s(%s);", requestDTO.getCallback(), new Gson().toJson(responseDTO));
}
else {
responseData = new Gson().toJson(responseDTO);
}
        }
        catch(Exception e) {
        logger.debug(e.getMessage());
        responseDTO = makeDefaultResponse(false, -1, "Failed to convert to JSON : Invalid Response Data");
        if( !StringUtils.isEmpty(requestDTO.getCallback()) ) {
responseData = String.format("%s(%s);", requestDTO.getCallback(), new Gson().toJson(responseDTO));
}
else {
responseData = new Gson().toJson(responseDTO);
}
        }
     
        out.println(responseData);
out.flush();
out.close();

logger.info("ServiceController::serviceHandleRequest [" + requestDTO.getModule() + ":" + requestDTO.getFunc() + " / ElapsedTime=" + (System.currentTimeMillis() - lStartTime) + "ms] is ended");

sendLog(requestDTO, responseDTO, request.getRemoteAddr());

logger.debug("ServiceController::serviceHandleRequest [" + requestDTO.getModule() + ":" + requestDTO.getFunc() + " / ElapsedTime=" + (System.currentTimeMillis() - lStartTime) + "ms] is ended(SearchLogSend)");
}


private ResponseDTO getResult(RequestDTO request) {
ResponseDTO response = null;
int errorCode = -1;
String errorMessage = "";

logger.debug("beans(" + request.getModule() + ") construct type=" + ctx.getAutowireCapableBeanFactory().isPrototype(request.getModule()));

Method method = null;
try {
CommonService impl = (CommonService)ctx.getBean(request.getModule());
method = impl.getClass().getDeclaredMethod(request.getFunc(), RequestDTO.class);
response = (ResponseDTO)method.invoke(impl, new Object[] { request });
} catch (SecurityException e) {
logger.error(e.getMessage());
errorMessage = "Invalid Method : SecurityException";
} catch (NoSuchMethodException e) {
logger.error(e.getMessage());
errorMessage = "Invalid Method : NoSuchMethodException";
} catch (IllegalArgumentException e) {
logger.error(e.getMessage());
errorMessage = "Failed to invoke Method : IllegalArgumentException";
} catch (IllegalAccessException e) {
logger.error(e.getMessage());
errorMessage = "Failed to invoke Method : IllegalAccessException";
} catch (InvocationTargetException e) {
logger.error(e.getMessage());
errorMessage = "Failed to invoke Method : InvocationTargetException";
} catch (NullPointerException e) {
logger.error(e.getMessage());
errorMessage = "Failed to run Method : NullPointerException";
} catch (Exception e) {
logger.error(e.getMessage());
errorMessage = "Failed to run Method : Exception";
}

if( response == null ) {
response = makeDefaultResponse(false, errorCode, errorMessage);
}
return response;
}


@SuppressWarnings("unchecked")
private RequestDTO getParameterFromRequest(HttpServletRequest request)
{
RequestDTO dto = null;
String callback = "";
Set<String> keySet = request.getParameterMap().keySet();
for (String oneKey : keySet) {
try {
oneKey = URLDecoder.decode(oneKey, "UTF-8");
} catch (UnsupportedEncodingException e) {
logger.error(e.getMessage());
return null;
}

logger.debug("param = " + oneKey);

if( oneKey.startsWith("{") && oneKey.contains("service") ) {
try {
dto = new Gson().fromJson(oneKey, RequestDTO.class);
} catch (JsonSyntaxException e) {
logger.error(e.getMessage());
return null;
}
}
else if( oneKey.equalsIgnoreCase("callback") ) {
Object values = request.getParameterMap().get("callback");
if (values instanceof String[]) {
callback = ((String[])values)[0];
}
}
}
if( dto != null ) {
dto.setCallback(callback);
}

return dto;
}
--------------------------------
requestDTO.java

public class RequestDTO {
private String version = StringUtils.EMPTY;

private String service = StringUtils.EMPTY;
private String module = StringUtils.EMPTY;
private String func = StringUtils.EMPTY;
private String callback = StringUtils.EMPTY;
private boolean firstCall = true;

private Parameter param = null;

public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
public String getModule() {
return module;
}
public void setModule(String module) {
this.module = module;
}
public String getFunc() {
return func;
}
public void setFunc(String func) {
this.func = func;
}
public String getCallback() {
return callback;
}
public void setCallback(String callback) {
this.callback = callback;
}
public boolean isFirstCall() {
return firstCall;
}
public void setFirstCall(boolean firstCall) {
this.firstCall = firstCall;
}
public Parameter getParam() {
return param;
}
public void setParam(Parameter param) {
this.param = param;
}
}
-------------------------
servelt.xml
<beans:bean id="SearchService" class="common.service.impl.SearchServiceImpl" scope="prototype" lazy-init="false" />

----------------------------

$.post(contextPath + '/authenticate/checkSession.ajax').done(function()
{
$.post(WAMS_SERVER_IP, JSON.stringify(param), 'json').done(function(result)
{
if ($.isFunction(fn))
{
fn.apply(fn, [ result ]);
}
else
{
showAlert($.i18n.prop('common.magazine_0001'));
}
}).fail(function(jqXHR, textStatus, errorThrown)
{
showAlert($.i18n.prop('fail'));
}).always(function()
{

});
}).fail(function(jqXHR, textStatus, errorThrown)
{

if (jqXHR.status == '901')
{
sessionTimeOutForInter();
}
}).always(function()
{

});

-----------------------------


function callExport(limit)
{
// 유효성 체크
var result = validCheck($('#searchKeyword').val(), "keyword");

if (result == false)
{
return;
}

var param = new Magazine();

param.setVersion('1.0');
param.setService('DICTIONARY');
param.setModule('SIMILAR');
param.setFunc('SELECT_LIST');

param.setOpt(
{
search :
{
keyword : $('#searchKeyword').val(),
date : {},
sort :
{
column : $('#sort_column').val(),
order : $('#sort_order').val()
},
dependency : {},
page :
{
offset : 1,
count : limit
}
}
});

param.fire(processExport);
}

댓글 없음:

댓글 쓰기