프로그래밍/Web

[ Spring , flask ] flask 서버에서 spring 서버로 데이터 전송하기

Yanoo 2020. 6. 8. 15:48
728x90
반응형

 

  • test.py
from flask import Flask #간단히 플라스크 서버를 만든다

import urllib.request

app = Flask(__name__)

@app.route("/tospring")
def spring():
    
    return "test"
    
    
if __name__ == '__main__':
    app.run(debug=False,host="127.0.0.1",port=5000)

파이썬 파일은 작성하고 위의 도메인을 들어가보면 test라는 글자가 나옴을 알 수 있다 ( def의 return 값이 뜨게 됨) 이렇게 flask서버를 켜놓고 띄워져있는 test를 스프링 서버로 보낼 것이다.

 

 

 

 

  • Controller.java
	@RequestMapping(value = "/test.do", method = RequestMethod.GET)
	public ModelAndView Test() {
		ModelAndView mav = new ModelAndView();
		
		String url = "http://127.0.0.1:5000/tospring";
		String sb = "";
		try {
			HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
			

			BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));

			String line = null;

			while ((line = br.readLine()) != null) {
				sb = sb + line + "\n";
			}
			System.out.println("========br======" + sb.toString());
			if (sb.toString().contains("ok")) {
				System.out.println("test");
				
			}
			br.close();

			System.out.println("" + sb.toString());
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mav.addObject("test1", sb.toString()); // "test1"는 jsp파일에서 받을때 이름, 
        						//sb.toString은 value값(여기에선 test)
		mav.addObject("fail", false);
		mav.setViewName("test");   // jsp파일 이름
		return mav;

 

 

  • test.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<script type="text/javascript">
	
</script>
<body>

${test1} <!-- 파라미터를 이런식으로 입력 -->


</body>
</html>

 

결과값 : 

(여기서 miri는 프로젝트 명이니 다를 수 있다 프로젝트마다 생략될 수 있음)

728x90
반응형