반응형

[JSTL] 한자리 숫자 앞에 0붙이기, addZero

<c:forEach var="c" items="${contents.content}" varStatus="status">
    <fmt:formatNumber var="no" minIntegerDigits="2" value="${status.count}" type="number"/>
     ${no}
</c:forEach>
반응형
반응형

[JAVA] HttpURLConnection로 REST API 호출하기 

public void post(String strUrl, String jsonMessage){
		try {
			URL url = new URL(strUrl);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			con.setConnectTimeout(5000); //서버에 연결되는 Timeout 시간 설정
			con.setReadTimeout(5000); // InputStream 읽어 오는 Timeout 시간 설정
			con.addRequestProperty("x-api-key", RestTestCommon.API_KEY); //key값 설정

			con.setRequestMethod("POST");

            //json으로 message를 전달하고자 할 때 
			con.setRequestProperty("Content-Type", "application/json");
			con.setDoInput(true);  // InputStream으로 응답 헤더와 메시지를 읽어들이겠다는 옵션
			con.setDoOutput(true); //POST 데이터를 OutputStream으로 넘겨 주겠다는 설정 
			con.setUseCaches(false);
			con.setDefaultUseCaches(false);

			OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
			wr.write(jsonMessage); //json 형식의 message 전달 
			wr.flush();

			StringBuilder sb = new StringBuilder();
			if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
				//Stream을 처리해줘야 하는 귀찮음이 있음.
				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());
			} else {
				System.out.println(con.getResponseMessage());
			}
		} catch (Exception e){
			System.err.println(e.toString());
		}
}

 

// 요청할 파라미터의 정보를 입력한다.
String body = "id=asdf&pass=asdf";

// URL클래스의 생성자로 주소를 넘겨준다.
URL u = new URL( 주소 );

// 해당 주소의 페이지로 접속을 하고, 단일 HTTP 접속을 하기위해 캐스트한다.
HttpURLConnection  huc = (HttpURLConnection) u.openConnection();

// POST방식으로 요청한다.( 기본값은 GET )
huc.setRequestMethod("POST");

//InputStream으로 응답 헤더와 메시지를 읽어들이겠다는 옵션을 정의한다.
   huc.setDoInput(true);

// OutputStream으로 POST 데이터를 넘겨주겠다는 옵션을 정의한다.
   huc.setDoOutput(true);

// 요청 헤더를 정의한다.( 원래 Content-Length값을 넘겨주어야하는데 넘겨주지 않아도 되는것이 이상하다. )
   huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

// 새로운 OutputStream에 요청할 OutputStream을 넣는다.
   OutputStream os = huc.getOutputStream();

// 그리고 write메소드로 메시지로 작성된 파라미터정보를 바이트단위로 "EUC-KR"로 인코딩해서 요청한다.

// 여기서 중요한 점은 "UTF-8"로 해도 되는데 한글일 경우는 "EUC-KR"로 인코딩해야만 한글이 제대로 전달된다.
   os.write( body.getBytes("euc-kr") );

// 그리고 스트림의 버퍼를 비워준다.
   os.flush();

// 스트림을 닫는다.
os.close();

// 응답받은 메시지의 길이만큼 버퍼를 생성하여 읽어들이고, "EUC-KR"로 디코딩해서 읽어들인다.
BufferedReader br = new BufferedReader( new OutputStreamReader( huc.getInputStream(), "EUC-KR" ), huc.getContentLength() );

String buf;

// 표준출력으로 한 라인씩 출력
while( ( buf = br.readLine() ) != null ) {
    System.out.println( buf );
}

// 스트림을 닫는다.
br.close();

 

반응형
반응형

[JSTL core] [c:forEach] varStatus를 활용한 변수

forEach문은 아래와 같이 활용한다.

<c:foreach items="${리스트가 받아올 배열이름}"
           var="for문 내부에서 사용할 변수"
           varStatus="상태용 변수">

	// 반복해서 표시할 내용 혹은 반복할 구문

</c:foreach>

이 때, 상태용 변수를 status라고 지정했다면 아래와 같이 활용할 수 있다.

 

${status.current} 현재 for문의 해당하는 번호

${status.index} 0부터의 순서

${status.count} 1부터의 순서

${status.first} 첫 번째인지 여부

${status.last} 마지막인지 여부

${status.begin} for문의 시작 번호

${status.end} for문의 끝 번호

${status.step} for문의 증가값

<c:foreach items="${list}" var="list" varStatus="status">
	<c:out value="${status.index}" /> / <c:out value="${status.end}" />
</c:foreach>
반응형
반응형

Hide the navigation bar - Android

https://developer.android.com/training/system-ui/navigation#behind

 

Hide the navigation bar  |  Android Developers

This lesson describes how to hide the navigation bar, which was introduced in Android 4.0 (API level 14). Even though this lesson focuses on hiding the navigation bar, you should design your app to hide the status bar at the same time, as described in Hidi

developer.android.com

This lesson describes how to hide the navigation bar, which was introduced in Android 4.0 (API level 14).

Even though this lesson focuses on hiding the navigation bar, you should design your app to hide the status bar at the same time, as described in Hiding the Status Bar. Hiding the navigation and status bars (while still keeping them readily accessible) lets the content use the entire display space, thereby providing a more immersive user experience.

You can hide the navigation bar using the SYSTEM_UI_FLAG_HIDE_NAVIGATION flag. This snippet hides both the navigation bar and the status bar:

View decorView = getWindow().getDecorView();
// Hide both the navigation bar and the status bar.
// SYSTEM_UI_FLAG_FULLSCREEN is only available on Android 4.1 and higher, but as
// a general rule, you should design your app to hide the status bar whenever you
// hide the navigation bar.
int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
              | View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
반응형
반응형

jsp 현재 날짜, 일주일전 날짜, 한달 전 날짜 구하기.

currentCalendar.add 부분에 -값이 아닌 +값을 대입하면 현재 이후의 날짜를 구할 수 있지요.

 

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="java.text.DecimalFormat" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.util.Calendar" %>

<%
    DecimalFormat df = new DecimalFormat("00");
    Calendar currentCalendar = Calendar.getInstance();

  //현재 날짜 구하기
    String strYear   = Integer.toString(currentCalendar.get(Calendar.YEAR));
    String strMonth  = df.format(currentCalendar.get(Calendar.MONTH) + 1);
    String strDay   = df.format(currentCalendar.get(Calendar.DATE));
    String strDate = strYear + strMonth + strDay;

  //일주일 전 날짜 구하기
    currentCalendar.add(currentCalendar.DATE, -7);
    String strYear7   = Integer.toString(currentCalendar.get(Calendar.YEAR));
    String strMonth7  = df.format(currentCalendar.get(Calendar.MONTH) + 1);
    String strDay7   = df.format(currentCalendar.get(Calendar.DATE));
    String strDate7 = strYear7 + strMonth7 + strDay7;

  //한달 전 날짜 구하기
    currentCalendar.add(currentCalendar.DATE, -24);
    String strYear31   = Integer.toString(currentCalendar.get(Calendar.YEAR));
    String strMonth31  = df.format(currentCalendar.get(Calendar.MONTH) + 1);
    String strDay31   = df.format(currentCalendar.get(Calendar.DATE));
    String strDate31 = strYear31 + strMonth31 + strDay31;
%>

<!-- 현재날짜 -->
<c:set var="nowdate" value='<%=strDate%>' />
<!-- 일주일전 -->
<c:set var="nowdate7" value='<%=strDate7%>' />
<!-- 한달전 -->
<c:set var="nowdate31" value='<%=strDate31%>' /> 
반응형
반응형

Java XML parse Library (=XPath)

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
 
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
 
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
 
public class OpenApi {
    public static void main(String[] args) {
        BufferedReader br = null;
        //DocumentBuilderFactory 생성
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder;
        Document doc = null;
        try {
            //OpenApi호출
            String urlstr = "http://openapi.airkorea.or.kr/"
                    + "openapi/services/rest/ArpltnInforInqireSvc/getMsrstnAcctoRltmMesureDnsty"
                    + "?stationName=수내동&dataTerm=month&pageNo=1&numOfRows=10&ServiceKey=서비스키&ver=1.3";
            URL url = new URL(urlstr);
            HttpURLConnection urlconnection = (HttpURLConnection) url.openConnection();
            
            //응답 읽기
            br = new BufferedReader(new InputStreamReader(urlconnection.getInputStream(), "UTF-8"));
            String result = "";
            String line;
            while ((line = br.readLine()) != null) {
                result = result + line.trim();// result = URL로 XML을 읽은 값
            }
            
            // xml 파싱하기
            InputSource is = new InputSource(new StringReader(result));
            builder = factory.newDocumentBuilder();
            doc = builder.parse(is);
            XPathFactory xpathFactory = XPathFactory.newInstance();
            XPath xpath = xpathFactory.newXPath();
            // XPathExpression expr = xpath.compile("/response/body/items/item");
            XPathExpression expr = xpath.compile("//items/item");
            NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            for (int i = 0; i < nodeList.getLength(); i++) {
                NodeList child = nodeList.item(i).getChildNodes();
                for (int j = 0; j < child.getLength(); j++) {
                    Node node = child.item(j);
                    System.out.println("현재 노드 이름 : " + node.getNodeName());
                    System.out.println("현재 노드 타입 : " + node.getNodeType());
                    System.out.println("현재 노드 값 : " + node.getTextContent());
                    System.out.println("현재 노드 네임스페이스 : " + node.getPrefix());
                    System.out.println("현재 노드의 다음 노드 : " + node.getNextSibling());
                    System.out.println("");
                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

 

1. XML이 제공되는 URL로 접속해서 데이터를 받아온다.

2. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance()로 factory를 생성한다.

3. DocumentBuilder builder = factory.newDocumentBuilder();로 builder를 생성한다.

4. InputSource is = new InputSource(new StringReader( 1.에서 받은 xml문자열 )); 로 InputSource를 생성한다.

  - XML파일에서 받는거면 InputSource is = new InputSource(new FileReader( File객체 ));로 생성한다.

5. Document doc = builder.parse(is); 로 XML을 파싱한다.

6. XPath xpath = XPathFactory.newInstance().newXPath(); 로 XPath 객체를 생성하고

7. XpathExpression expr = xpath.complie( 선택하는 문법 ); 으로 가져올 element를 선택한다.

8. 해당 노드(Element)에 접근해서 필요한 데이터를 추출한다.

 

대략적으로 위와 같은 과정으로 XML데이터 파싱이 이루어진다.

 DocumentBuilderFactory로부터 builder를 만들어내고 InputSource에 XML을 넣어서 document를 만드는 것까지는 일반적이다.

여기서 XML을 파싱해서 새롭게 만들어진 DOM객체를 접근하는데에 XPath가 쓰인다.

중점적으로 봐야할 부분은 역시 XPath의 문법이다. XPath는 노드에 접근하는데에 표현식(XPathExpression)이 사용된다.

다른 블로그에서 Xpath 표현식 문법(?)에 대해 잘 정리한 곳이 많으므로 여기서는 자주 쓰이고 중요한 부분만 정리한다.


 

 XPathExpression

표현식까지 익혀야 한다고 번거로운 라이브러리라고 판단할 수도 있겠지만 한 번 익혀두거나 나중에 찾아보면서 사용해도 훌륭한 것 같은 라이브러리니 간단하게 배운다.

item : <item>요소를 모두 선택함
/item : "/" 루트 노드의 자식 노드중에서 <item>엘리먼트를 선택함 (앞에 "/"가 들어가면 절대 경로)
item/jeongpro : <item>엘리먼트의 자식 노드중에서 <jeongpro>엘리먼트를 선택 (상대 경로)
// : 현재 노드의 위치와 상관없이 지정된 노드부터 탐색
//item : 위치와 상관없이 엘리먼트 이름이 <item>인 모든 엘리먼트
item/@id : 모든 <item>엘리먼트의 id속성 노드를 모두 선택함
item[k] : <item>엘리먼트 중에서 k번 째 <item>엘리먼트
item[@attr = val] : attr이라는 속성이 val값을 가지는 모든 <item>엘리먼트

 

이런 표현식들이 있으니 잘 사용하면된다. 위의 예제에서는 //items/item 이라는 표현식을 적었으므로 "위치와 상관없이 <items>라는 노드들 중에서 자식 노드가 <item>인 노드(element)들을 NodeList로 받았다.

결과적으로 파싱을 마친 후 노드에서 원하는 데이터를 정확하게 추출하는 것이 중요하다.

node.getNodeName() 으로 "element 이름"을 받았고

node.getTextContent() 로 "값"을 받았다. (* 참고로 getNodeValue()가 있는데 혼란을 겪지 않길 바란다.)

또한 node.getPrefix() 로 "네임스페이스 값"을 받을 수도 있고

node.getNextSibling으로 "다음 노드"를 선택할 수도 있다.

속성은 node.getAttributes().item(0) 이런식으로 받을 수 있다.

끝으로 문자열에서 xml 파싱하는 소스도 첨부한다.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
 
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
 
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
 
public class OpenApi {
    public static void main(String[] args) {
        //DocumentBuilderFactory 생성
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder;
        Document doc = null;
        try {
            // xml 파싱하기
            String result = "<response xmlns:s='http://www.example.net/'><items><item><s:best>hello</s:best></item></items></response>";
            InputSource is = new InputSource(new StringReader(result));
            builder = factory.newDocumentBuilder();
            doc = builder.parse(is);
            XPathFactory xpathFactory = XPathFactory.newInstance();
            XPath xpath = xpathFactory.newXPath();
            // XPathExpression expr = xpath.compile("/response/body/items/item");
            XPathExpression expr = xpath.compile("//items/item");
            NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            for (int i = 0; i < nodeList.getLength(); i++) {
                NodeList child = nodeList.item(i).getChildNodes();
                for (int j = 0; j < child.getLength(); j++) {
                    Node node = child.item(j);
                    System.out.println("현재 노드 이름 : " + node.getNodeName());
                    System.out.println("현재 노드 이름 : " + node.getLocalName());
                    System.out.println("현재 노드 타입 : " + node.getNodeType());
                    System.out.println("현재 노드 값 : " + node.getTextContent());
                    System.out.println("현재 노드 네임스페이스 : " + node.getPrefix());
                    System.out.println("현재 노드의 다음 노드 : " + node.getAttributes().item(0));
                    System.out.println("");
                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
 

 https://jeong-pro.tistory.com/144

 

자바 XML 파싱 라이브러리, XPath를 사용한 예제와 정확하게 element를 선택하는 방법을 알아보자

Java XML parse Library (=XPath) XPath : 자바에서 내장 패키지(javax.xml.xpath)로 제공하는 라이브러리로 XML형식의 웹문서, 파일, 문자열을 파싱하는데 사용한다. 요즘 누가 XML쓰나? JSON이랑 비교했을 때 태..

jeong-pro.tistory.com

 

반응형
반응형

JAVA, JSP - QR Code 만들기 소스 - ZXing ("Zebra Crossing") barcode scanning library for Java, Android

https://github.com/zxing/zxing

 

zxing/zxing

ZXing ("Zebra Crossing") barcode scanning library for Java, Android - zxing/zxing

github.com

java  android   barcode   barcode-scanner   zxing   qr-code   datamatrix   upc  

반응형
반응형

Calendar 클래스 (달력 출력)

Calendar 클래스도 Date 클래스처럼 날짜와 시간에 관한 정보를 표현할 때 사용한다. Date 클래스에서 deprecate된 메소드나 생성자들 중 같은 기능의 메소드가 Calendar 클래스에서 제공된다.
Calendar 클래스는 추상 클래스이므로 객체를 직접 생성할 수는 없지만, getInstance() 메소드를 이용하여 시스템의 날짜와 시간 정보를 표현할 수 있다.

Calendar.DAY_OF_YEAR
Calendar.DAY_OF_MONTH
Calendar.DAY_OF_WEEK

 

반응형

+ Recent posts