티스토리 뷰

JAVA

API Server Test 01 | postman 사용

wldnjd2 2022. 6. 3. 15:54

 

아직은 서버끼리 통신하는거 아님

데이터가 컨트롤러에 들어가는것부터 확인한다.

(위의 노란색 부분 진행하는거당)

 

 

프로젝트 초기셋팅

 

0. 전자정부프레임워크 Example 프로젝트를 생성한다.

https://jays-lab.tistory.com/6

 

[전자정부 프레임워크] eGovframework 웹 어플리케이션 개발_03 전자정부 프레임워크 이용하여 프로

지금까지 전자정부 프레임워크 eGovframework의 구조와 적용 규칙을 알아봤다면 이제부터는 실제로 전자정부 프레임워크( eGovframework )를 사용하여 프로젝트를 진행하려고 한다. 모든 프로그래밍이

jays-lab.tistory.com

 

 

1. web.xml 수정
welcom-file-list를 index.jsp로 수정

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>



2. index.jsp 파일 수정
아래와 같이 수정한다.

<jsp:forward page="/main.do"/>

 


3. pom.xml 
아래를 추가해준다.

<!-- JSON 관련 dependency추가 -->
<dependency>
  <groupId>org.codehaus.jackson</groupId>
  <artifactId>jackson-mapper-asl</artifactId>
  <version>1.9.2</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
  <artifactId>json-simple</artifactId>
  <version>1.1.1</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.10.1</version>
</dependency>

 


4. main.jsp 생성
WEB-INF - jsp - egovframework - example 안에 main.jsp파일을 생성
main.jsp 파일에 버튼을 생성해줄거임

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<div> hello</div>

 

 

5. Context root 설정
프로젝트 우클릭 -> Web Project Settings -> Context root: api_server 

 


6. 프로젝트 Servers 생성
Tomcat8.5v server 생성하고 더블클릭하면 Overview 창이 나옴
-> Ports 부분에 HTTP/1.1 부분을 8082라고 수정하였음

 


7. MainController.java 생성

package apiTest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MainController {
      @RequestMapping(value = "main.do")
      public String main(){
           return "main";
      }
}

 


8. 아래 링크 접속시 화면 표출 됨
http://localhost:8082/api_server/

 

 

 


파일 생성

 

1. HttpUrlConnectionPost.java 생성

package apiTest;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUrlConnectionPost {

	/**
	 * 매개변수를 String으로 받는 통신 메소드
	 * @param strJson
	 * @param strUrl
	 * @exception Exception
	 */
	public String httpURLConnection(String strJson, String strUrl){
		
		try {
			
			URL url = new URL(strUrl);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			// 서버에 연결되는 Timeout 시간 설정
			con.setConnectTimeout(5000); 
			// InputStream 읽어 오는 Timeout 시간 설정
			con.setReadTimeout(5000); 
			
			// json으로 message를 전달하고자 할 때 
			con.setRequestMethod("POST");
			con.setRequestProperty("Content-Type", "application/json");
			con.setDoInput(true);
			// POST 데이터를 OutputStream으로 넘겨 주겠다는 설정
			con.setDoOutput(true);  
			
			// json을 보내기 위해서 생성된 OutputStreamWriter
			OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
			
			// json 형식의 message 전달 
			wr.write(strJson); 
			wr.flush();
			
			
			if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
				
				// response값을 담기 위한 클래스
				StringBuilder sb = new StringBuilder();
				BufferedReader br = new BufferedReader(
										new InputStreamReader(con.getInputStream(), "utf-8"));
				
				String line;
				while ((line = br.readLine()) != null) {
					sb.append(line).append("\n");
				}
				br.close();
				System.out.println("" + sb.toString());
				
				return sb.toString();
				
			} else {
				System.out.println(con.getResponseMessage());
			}
			
		} catch (Exception e) {
			
			e.printStackTrace();
			
		}
		
		return null;
		
	}

}

 

 

2. ParamStringController.java

- @ResponseBody

서버에서 데이터를 주고받을때 데이터 형식이 json일때 사용하는것이다.

클라이언트에서 서버로 필요한 데이터를 요청하기 위해 JSON 데이터를 서버로 보내면,

서버에서는 RequestBody 어노테이션을 사용해서 HTTP 요청 본문에 담긴 값들을 자바객체로 변환시켜, 객체에 저장한다.

 

 

 

- json을 전송하게 되면 json데이터가 string으로 변환되서 json형태를 잃게 된다.

이를 해결하기 위해서 JSON.parse()메소드를 사용한다.

위의 메소드는 string 객체를 json객체로 변환시켜준다

 

아래는 디버그 모드로 확인한 데이터 모습이다. string의 형태로 바뀌었다.

package apiTest;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ParamStringController {
	/**
	 * 데이터 send
	 * @param strJson
	 * @exception Exception
	 */
	@RequestMapping(value = "/sendReqStr.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
	public @ResponseBody String sendReqStr(@RequestBody String strJson) throws Exception{
		
		HttpUrlConnectionPost connection = new HttpUrlConnectionPost();
		
        	//다른 서버의 url mapping
		String url = "http://xxx.xxx.xx.xxx:8082/data/receiveReqStr.do";		
		
		return connection.httpURLConnection(strJson, url);
	}
	
	/**
	 * 데이터 receive
	 * @param strJson
	 * @exception Exception
	 */
	@RequestMapping(value = "/receiveReqStr.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
	public @ResponseBody String receiveReqStr(@RequestBody String strJson) throws Exception{
		
		JSONParser parser = new JSONParser();
		JSONObject json = (JSONObject) parser.parse(strJson);
		
		System.out.println("=============== 받은 데이터 =================");
		System.out.println(json);
		
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("reusult1", "ok!!");
		
		return jsonObject.toString();
		
	}
}

 

 

 

 


ERROR

 

dispatcher-servlet.xml

egovFrameWork를 이용해서 example을 사용시 경로를 못잡는 경우가 있음

이때 dispatcher-servlet.xml 파일을 수정해야한다.

이거 수정안해줘서 계속 No mapping found for HTTP request with URI 에러났었는데, 아래가 에러 원인이였음 ㄷㄷ

 

아래 코드는 기본 패키지를 설정하는건데,

egovframework -> apiTest(패키지명)로 아래와 같이 바꿔주면 된다.

<context:component-scan base-package="apiTest">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
</context:component-scan>

 

 

- 패키지 구조

 

 


Postman 이용해서 json 데이터 보내주기

 

 

 

SUCCESS

 

console창에서 데이터 들어온거 확인//^0^

 

 

 

 

 

 

 


Ref.

재석씨 희선씨 감사합니당

 

https://cheershennah.tistory.com/179

 

[Spring] @RequestBody / @ResponseBody 어노테이션 이란?

스프링에서 비동기 처리를 하는 경우 @RequestBody , @ResponseBody를 사용한다. 비동기 처리를 위해 이 어노테이션들은 어떻게 작동할까? 클라이언트와 서버의 비동기 통신  클라이언트에서 서버로 통

cheershennah.tistory.com

 

 

 

 

댓글