이번에는 테스트서버용을 구축해보고자 가상머신 중의 하나인 VirtualBox 부터 설치해보도록 하겠습니다.
https://www.virtualbox.org/wiki/Downloads
URL 접속 후 본인의 OS 환경에 맞추어 버추얼박스를 다운로드 받도록 합니다.
저는 Windows OS 환경으로 포스팅 진행하도록 하겠습니다.
다운로드가 완료되었다면 설치를 진행 해보도록 하겠습니다.
[Next] 클릭
[Browse] 파일경로 설정(필수는아님) 후 [Next] 클릭
[Next] 클릭
[Yes] 클릭
[Install] 클릭
VirtualBox 설치진행...
설치완료 [Finish] 클릭
설치가 완료되었다면 이어서 CentOS 6.5 설치를 해보도록 하겠습니다.
※ CentOS 7 은 방화벽 관련하여 조금 더 확인 후 시간이 날때 포스팅을 등록하도록 하겠습니다.
http://www.centos.org/download/mirrors/
해당 미러사이트에 접속 후 다음 순서대로 진행을 하여
CentOS 6.5 Minimal 버전을 다운로드 받도록 합니다.
Ctrl + F 로 "daum" 이라고 검색 후 ftp URL 주소를 클릭합니다.
※ CDNetwork 혹은 Kaist 등 Korea 관련 아무링크나 클릭하셔도 무관합니다.
6.5 버전 클릭
이미지 파일로 설치할 것이므로 isos 디렉토리 클릭
원하는 OS 비트에 따라 다운로드 클릭
※ 본인은 32비트로 설치할 예정이므로 i386을 클릭함
minimal 버전이 2가지가 있는데 324M 용량 파일을 클릭합니다.
그럼 다운로드가 진행일 될겁니다.
다운로드가 완료되었다면 다음 포스팅에는 VirtualBox에 다운로드받은 Cent0S 6.5 설치과정부터
네트워크 할당하여 외부에서 SSH 접속하는 과정까지 진행해보도록 하겠습니다.
by 개발로짜
CentOS wget을 이용하여 Apache 2.4 다운로드 및 서버 실행 (방화벽해제 포함) (1) | 2014.12.10 |
---|---|
CentOS 6.5 - Tomcat7 다운로드 + 서버 실행 및 방화벽 해제 알아보기 (0) | 2014.12.09 |
CentOS에 wget을 이용하여 JDK1.7 RPM 다운로드 후 설치하기 (0) | 2014.12.09 |
putty,파일질라를 이용하여 가상머신(VirtualBox)에 설치된 CentOS 6.5 접속테스트 (2) | 2014.12.09 |
가상머신(Virutalbox)에 CentOS 6.5 설치 및 네트워크 설정한후 ping 테스트 (0) | 2014.12.08 |
이번 포스팅은 Spring MVC 와 HttpClient 라이브러리를 연동하여 API 웹서버 예를 들어보도록 하겠습니다.
HttpClient는 주로 api호출을 하여 서버로부터 받은 데이터(JSON 또는 XML)를
클라이언트(웹 또는 안드로이드)에서 응답받아서 화면에 파싱작업을 진행을 할때 주로 사용합니다.
GET/POST/Multipart(파일처리) 이 3가지에 대하여 알아보도록 하겠습니다.
응답데이터는 JSON 규격으로 클라이언트로 보내는걸로 진행 하겠습니다.
//GET 방식 @RequestMapping(value="/getServer", method=RequestMethod.GET) public @ResponseBody Map<String, Object> getServer(HttpServletRequest request, HttpServletResponse response) { System.out.println("GET Server Response"); Map<String, Object> map = new HashMap<String, Object>(); //클라이언트 페이지로 부터 Httpclient로 받은 parameter값 map.put("param1", request.getParameter("param1")); map.put("param2", request.getParameter("param2")); map.put("flag", "get"); map.put("success", true); return map; } //POST 방식 @RequestMapping(value="/postServer", method=RequestMethod.POST) public @ResponseBody Map<String, Object> postServer(HttpServletRequest request, HttpServletResponse response) { System.out.println("POST Server Response"); Map<String, Object> map = new HashMap<String, Object>(); //클라이언트 페이지로 부터 Httpclient로 받은 parameter값 map.put("param1", request.getParameter("param1")); map.put("param2", request.getParameter("param2")); map.put("flag", "post"); map.put("success", true); return map; } //MultipartFile 방식 @RequestMapping(value="/multipartServer", method=RequestMethod.POST) public @ResponseBody Map<String, Object> multipartServer(Vo vo,HttpServletRequest request) { System.out.println("Multipart Server Response"); Map<String, Object> map = new HashMap<String, Object>(); //클라이언트 페이지로 부터 Httpclient로 받은 parameter값 map.put("txt", request.getParameter("txt")); //클라이언트 페이지로 부터 Httpclient로 받은 multipart parameter값 map.put("filename", vo.getFileupload().getOriginalFilename()); map.put("filesize", vo.getFileupload().getSize()); map.put("flag", "multipart"); map.put("success", true); return map; }
public class Vo { private MultipartFile fileupload; public MultipartFile getFileupload() { return fileupload; } public void setFileupload(MultipartFile fileupload) { this.fileupload = fileupload; } }
다음은 클라이언트 페이지에서 HttpClient를 이용하여
API 서버를 호출하는 라이브러리 추가 및 샘플코드를 다음과 같이 작성해보도록 합니다.
<!-- HttpClient 라이브러리 설정 --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3.6</version> </dependency> <!-- HttpClient - Multipart를 위한 라이브러리 설정 --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.3.6</version> </dependency>
//Get방식 호출을 위한 샘플폼화면 @RequestMapping(value="/getForm") public String getForm(HttpServletRequest request, HttpServletResponse response) { return "getForm"; } //Post방식 호출을 위한 샘플폼화면 @RequestMapping(value="/postForm") public String postForm(HttpServletRequest request, HttpServletResponse response) { return "postForm"; } //Multipart방식 호출을 위한 샘플폼화면 @RequestMapping(value="/multipartForm") public String multipartForm(HttpServletRequest request, HttpServletResponse response) { return "multipartForm"; }
<form action="/getSubmit" method="get"> <input type="text" name="param1" /><br/> <input type="text" name="param2" /><br/> <input type="submit" value="GET전송"/> </form>
<form action="/postSubmit" method="post"> <input type="text" name="param1" /><br/> <input type="text" name="param2" /><br/> <input type="submit" value="POST전송"/> </form>
<form action="/multipartSubmit" method="post" enctype="multipart/form-data"> <input type="file" name="fileupload" /><br/> <input type="text" name="txt" /><br/> <input type="submit" value="POST전송"/> </form>
//Get Submit @RequestMapping(value="/getSubmit") public void getSubmit(HttpServletRequest request) { try { CloseableHttpClient httpclient = HttpClients.createDefault(); //GET 방식으로 parameter를 전달 HttpGet httpGet = new HttpGet("http://localhost:7070/getServer?param1="+request.getParameter("param1")+"¶m2="+request.getParameter("param2")); CloseableHttpResponse response = httpclient.execute(httpGet); try { System.out.println(response.getStatusLine()); //API서버로부터 받은 JSON 문자열 데이터 System.out.println(EntityUtils.toString(response.getEntity())); HttpEntity entity = response.getEntity(); EntityUtils.consume(entity); } finally { response.close(); } } catch (Exception e) { e.printStackTrace(); } }
//Post Submit @RequestMapping(value="/postSubmit") public void postSubmit(HttpServletRequest request) { try { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://localhost:7070/postServer"); //전달하고자 하는 PARAMETER를 List객체에 담는다 List <NameValuePair> nvps = new ArrayList >NameValuePair>(); nvps.add(new BasicNameValuePair("param1", request.getParameter("param1"))); nvps.add(new BasicNameValuePair("param2", request.getParameter("param2"))); //UTF-8은 한글 httpPost.setEntity(new UrlEncodedFormEntity(nvps,"UTF-8")); CloseableHttpResponse response = httpclient.execute(httpPost); try { System.out.println(response.getStatusLine()); //API서버로부터 받은 JSON 문자열 데이터 System.out.println(EntityUtils.toString(response.getEntity())); HttpEntity entity = response.getEntity(); EntityUtils.consume(entity); } finally { response.close(); } } catch (Exception e) { e.printStackTrace(); } }
//파일첨부 MultipartFile Submit @RequestMapping(value="/multipartSubmit") public void multipartSubmit(HttpServletRequest request, Vo vo) { CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost("http://localhost:7070/multipartServer"); File convFile = new File(vo.getFileupload().getOriginalFilename()); vo.getFileupload().transferTo(convFile); FileBody multipart = new FileBody(convFile); //Charset.forName("UTF-8") : 한글깨짐 방지를위함 StringBody txt = new StringBody(request.getParameter("txt"), Charset.forName("UTF-8")); //API 서버에 전달하고자하는 PARAMETER HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("fileupload", multipart).addPart("txt", txt).build(); httppost.setEntity(reqEntity); CloseableHttpResponse response = httpclient.execute(httppost); try { System.out.println(response.getStatusLine()); //API서버로부터 받은 JSON 문자열 데이터 System.out.println(EntityUtils.toString(response.getEntity())); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); } EntityUtils.consume(resEntity); } finally { response.close(); } } catch(Exception e){ e.printStackTrace(); }finally { try { httpclient.close(); } catch (IOException e) {} } }
위와같이 코드를 작성하였다면 각 폼컨트롤러 호출을 하여
실행테스트를 해보도록 하겠습니다.
위와같이 정상적으로 API서버에 PARAMETER 또는 MultipartFile 전송 후
응답값을 받아오는 것을 확인 할 수 있었습니다.
안드로이드 API 서버 구축시 또는 외부 API 서버로부터 API 호출할 경우가 생긴다면
해당 샘플을 응용하여 사용하시면 되겠습니다.
by 개발로짜
Spring3 MVC와 Mybatis를 이용하여 이미지를 blob타입으로 db 저장 및 출력해보기 (13) | 2014.12.21 |
---|---|
Spring3 spring-task를 이용하여 스케줄러 연동 및 동작시켜보기 + DB연동(MySQL기준) (0) | 2014.11.24 |
Spring3 + ibatis(아이바티스) 연동해보고 쿼리결과값 콘솔에 출력해보기 (5) | 2014.11.17 |
Spring3 + Mybatis 여러개 Datasource 연동법(다중 트랜잭션 포함) (0) | 2014.11.16 |
Spring3 + Mybatis연동에 추가로 트랜잭션 설정 하여 실패시 Rollback 처리하기 (2) | 2014.11.14 |
이전 Spring3 + ExtJS 파일업로드 관련하여 포스팅을 한 적이 있습니다.
2014/10/28 - [웹개발강좌/ExtJS] - ExtJS 강좌 - 파일필드를 이용하여 파일업로드하기(html5를 이용한 다중파일 포함)
"Deoki"님께서 질문주신 결과
Spring의 @ResponseBody + Jackson JSON 라이브러리를 이용하여
JSON 파싱한 결과
크롬에서는 정상적으로 JSON 값을 받아왔으나
IE에서는 다운로드가 되는 현상이 발생되었습니다.
이러한 현상이 발생하는 이유는
JacksonMessageConverter의 응답타입이 "application/json" 이어서
IE에서는 정상적으로 동작되지 않는 것이었습니다.
그래서 응답타입을 "text/plain"형태로 설정을 변경을 해주어야 합니다.
크롬에서만 작업하다보니 IE에서 문제가 발생한거라는 것을 몰랐었네요;;
만약 "json-simple" 또는 "json-lib" 와같이 파싱해주는 라이브러리 사용시
response.setContentType을 "text/plain" 으로 설정해주면 문제 없이 IE/크롬 등
모든 브라우저에서 정상작동하는 것이라 신경을 쓰지 않았었는데;;;
상단 포스팅 링크의 코드에 대한 실행결과를 확인해 보도록 하겠습니다.
크롬은 정상적으로 메시지 창이 출력되는 반면,
IE에서는 서버에서 응답받은 결과값이 파일로 다운로드처리가 되었습니다.
그럼 이 부분을 해결하기 위하여
<mvc:annotation-driven />
상단 기존 태그를 다음과 같이 코드 변경을 해주도록 합니다.
<mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes" value="text/plain;charset=UTF-8"/> </bean> </mvc:message-converters> </mvc:annotation-driven>
위와같이 설정을 해주었다면 다시한번 IE에서 동작을 시켜보도록 하겠습니다.
위와같이 정상적으로 업로드된 파일에 대하여
정상적으로 JSON OBJECT를 받아오는 결과를 확인 할 수 있었습니다.
Spring의 @ResponseBody를 이용한 JSON 구현할때
text/plain 을 적용해주기 위해서는 "mvc:annotation-driven" 태그를
위와같이 적용을 해주는 것이 이 포스팅의 핵심내용입니다.
by 개발로짜
ExtJS 강좌 - ExtJS5 MVC 구조를 이용한 간단 그리드 CRUD 알아보기(2) (5) | 2015.01.07 |
---|---|
ExtJS 강좌 - ExtJS5 MVC 구조를 이용한 간단 그리드 CRUD 알아보기(1) (13) | 2014.12.29 |
ExtJS 강좌 - ExtJS5 MVC 구조 잡아보기(View/Controller + Model+Store 추가) (0) | 2014.11.26 |
ExtJS 강좌 - ExtJS5 MVC 구조 잡아보기(View+Controller 연동) (2) | 2014.11.26 |
ExtJS 강좌 - Sencha CMD로 ExtJS 구조 생성하여 연동테스트 해보기 (1) | 2014.11.24 |