반응형
반응형
public static String httpsGet(String strURL) throws Exception
{
    URL url = null;
    HttpsURLConnection con = null;
    String ret = new String();

    try {
        url = new URL(strURL);
        ignoreSsl();
        con = (HttpsURLConnection)url.openConnection();


        BufferedReader br = null;
        br = new BufferedReader(new InputStreamReader(con.getInputStream()));

        String input = null;

        while ((input = br.readLine()) != null){
            ret += input;
        }

        br.close();
    }
    catch (IOException e) {
        ExceptionUtil.getStackTrace(e);
    } finally {
        if (con != null) {
            con.disconnect();
        }
    }

    return ret;

}

 

 

public static void ignoreSsl() throws Exception{
    HostnameVerifier hv = new HostnameVerifier() {
    public boolean verify(String urlHostName, SSLSession session) 
            return true;
        }
    };
    trustAllHttpsCertificates();
    HttpsURLConnection.setDefaultHostnameVerifier(hv);
}

private static void trustAllHttpsCertificates() throws Exception {
    TrustManager[] trustAllCerts = new TrustManager[1];
    TrustManager tm = new miTM();
    trustAllCerts[0] = tm;
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, null);
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}

static class miTM implements TrustManager,X509TrustManager {
    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }

    public boolean isServerTrusted(X509Certificate[] certs) {
        return true;
    }

    public boolean isClientTrusted(X509Certificate[] certs) {
        return true;
    }

    public void checkServerTrusted(X509Certificate[] certs, String authType)
            throws CertificateException {
        return;
    }

    public void checkClientTrusted(X509Certificate[] certs, String authType)
            throws CertificateException {
        return;
    }
}

 

 

출처 : https://ram2ram2.tistory.com/16

반응형
반응형
package com.lsj.chatting;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

public class testing {

	public static void main(String[] args) {

		Map<String,Object> map = new HashMap<String,Object>();
		List<String> hobbies = new ArrayList<String>();
		hobbies.add("cook");
		hobbies.add("shopping");
		
		map.put("name", "brown");
		map.put("hobbies", hobbies);
		
		System.out.println(map);
		
		JSONObject mapJson = new JSONObject(map);
		System.out.println(mapJson);
		
		// {hobbies=[cook, shopping], name=brown}
		// {"hobbies":["cook","shopping"],"name":"brown"}
		
		JSONArray hobbiesJsonArray = new JSONArray(hobbies);
		System.out.println(hobbiesJsonArray);
		
		// ["cook","shopping"]
		
	}
	
}
반응형
반응형
public static void main(String[] args) {

    String document = "삼성전자 LG전자 화웨이 소니 애플 삼성전자(우) 삼성화재";
    String word = "삼성";

    System.out.println(findIndexes(word, document));

}

public static List<Integer> findIndexes(String word, String document) {

    List<Integer> indexList = new ArrayList<Integer> ();
    int index = document.indexOf(word);

    while(index != -1) {
        indexList.add(index);
        index = document.indexOf(word, index+word.length());
    }

    return indexList;
}

// 출처 : https://needneo.tistory.com/96

 

반응형
반응형
public class LocationDistance {

	public static void main(String[] args) {

		// 마일(Mile) 단위
		double distanceMile = 
			distance(37.504198, 127.047967, 37.501025, 127.037701, "");
		
		// 미터(Meter) 단위
		double distanceMeter = 
			distance(37.49268,126.78442,37.59084,126.78918, "meter");
		
		// 킬로미터(KiloMeter) 단위
		double distanceKiloMeter = 
			distance(37.49268,126.78442,37.59084,126.78918, "kilometer");
		
		System.out.println(distanceMile) ;
		System.out.println(distanceMeter) ;
		System.out.println(distanceKiloMeter) ;
		
	}
	
	
	/**
	 * 두 지점간의 거리 계산
	 * 
	 * @param shoptLat 지점 1 위도
	 * @param shopLngt 지점 1 경도 
	 * @param userLat 지점 2 위도
	 * @param lon2 지점 2 경도
	 * @param unit 거리 표출단위 
	 * @return
	 */
	
	
	private static double distance(double shoptLat, double shopLngt, double userLat, double lon2, String unit) {
		
		double theta = shopLngt - lon2;
		double dist = Math.sin(deg2rad(shoptLat)) * Math.sin(deg2rad(userLat)) 
				+ Math.cos(deg2rad(shoptLat)) * Math.cos(deg2rad(userLat)) * Math.cos(deg2rad(theta));
		
		dist = Math.acos(dist);
		dist = rad2deg(dist);
		dist = dist * 60 * 1.1515;
		
		if (unit == "kilometer") {
			dist = dist * 1.609344;
		} else if(unit == "meter"){
			dist = dist * 1609.344;
		} 

		return (dist);
	}
	

	// This function converts decimal degrees to radians
	private static double deg2rad(double deg) {
		return (deg * Math.PI / 180.0);
	}
	
	// This function converts radians to decimal degrees
	private static double rad2deg(double rad) {
		return (rad * 180 / Math.PI);
	}
}

 

출처 : https://m.blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=akdlakdrn&logNo=221717580886 

반응형
반응형

 

 

📝 Controller

package com.lsj.spring_study;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;

import javax.servlet.http.HttpServletResponse;

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;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;

/**
 * Handles requests for the application home page.
 */
@Controller
public class PdfController {
	
	/**
	 * @why : 자바로 pdf 파일 생성
	 */
	@RequestMapping(value = "pdf", method = RequestMethod.PUT)
	public void makePdfFile() throws DocumentException, IOException {
		

		String filePath = "C://test.pdf";
		String contents = "자바로 pdf 파일 생성";
		
	    Document document = new Document();
	    PdfWriter.getInstance(document, new FileOutputStream(filePath));

	    document.open();
	    
	    /** 표 그리기 **/ 
//	     PdfPTable table = new PdfPTable(4); 
//	     for(int i = 0; i < 16; i++){
//	      	table.addCell("cellNumber:" + i); 
//	    }

	    /** 글자 넣기 (WEB-INF/classes/font에 폰트를 넣어주세요 (참고 : 한글이 안 나오는 글씨체도 있음) **/ 
	    // C:\Windows\Fonts\휴먼매직체 보통(HMKMMAG.TFF 파일 사용)
	    BaseFont bfKorean = BaseFont.createFont("font/HMKMMAG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); 
	    
	    Font FontKorean = new Font(bfKorean, 10, Font.NORMAL);
	    document.add(new Paragraph(contents, FontKorean));
	    document.close();
		
	}
	
	/**
	 * @why : pdf 파일 다운로드
	 */
    @RequestMapping(value = "/download/pdf", method = RequestMethod.GET)
    public void downloadPdf(HttpServletResponse response) throws IOException {
    	
    	FileInputStream fis = null;
    	BufferedOutputStream bos = null;
    	
    	String pdfFileName = "C:/test.pdf";
    	
    	try {

    		/** Pdf Open **/
	    	File pdfFile = new File(pdfFileName);
	    	fis = new FileInputStream(pdfFile);

	    	/** Header 설정 (Download) **/
	    	response.addHeader("Content-Disposition", "attachment; filename=" + pdfFile.getName() + ".pdf");
	    	
	    	/** Pdf 내용을 Read [버퍼에 담기] **/
	    	int size = fis.available(); 
	    	byte[] buf = new byte[size]; 
	    	int readCount = fis.read(buf);
	    	
	    	/** 버퍼에 담은 내용 웹에 출력 **/
	    	response.flushBuffer();

	    	bos = new BufferedOutputStream(response.getOutputStream());
	    	bos.write(buf, 0, readCount);
	    	bos.flush();
	
    	} catch(Exception e) {

    		e.printStackTrace();

    	} finally {

	    	if (fis != null) fis.close();
	    	if (bos != null) bos.close();

    	}
    }


	/**
	 * @why : pdf 파일 웹에 띄우기
	 */
    @RequestMapping(value = "pdf", method = RequestMethod.GET)
    public void readPdf(HttpServletResponse response) throws IOException {
    	
    	FileInputStream fis = null;
    	BufferedOutputStream bos = null;
    	
    	String pdfFileName = "C:/test.pdf";
    	
    	try {

    		/** Pdf Open **/
	    	File pdfFile = new File(pdfFileName);
	    	fis = new FileInputStream(pdfFile);

	    	/** Content Type 설정 **/
	    	response.setContentType("application/pdf");

	    	/** Pdf 내용을 Read [버퍼에 담기] **/
	    	int size = fis.available(); 
	    	byte[] buf = new byte[size]; 
	    	int readCount = fis.read(buf);
	    	
	    	/** 버퍼에 담은 내용 웹에 출력 **/
	    	response.flushBuffer();

	    	bos = new BufferedOutputStream(response.getOutputStream());
	    	bos.write(buf, 0, readCount);
	    	bos.flush();
	
    	} catch(Exception e) {

    		e.printStackTrace();

    	} finally {

	    	if (fis != null) fis.close();
	    	if (bos != null) bos.close();

    	}
    }
    
    
	/**
	 * @why : pdf 파일 웹에 띄우기
	 */
    @RequestMapping(value = "board", method = RequestMethod.GET)
    public String pdf() {
    	
    	return "board";
    }
}

 

 

📝 Maven

<!-- make pdf lib -->
<dependencies>
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itextpdf</artifactId>
        <version>5.4.2</version>
    </dependency>
    <dependency>
        <groupId>com.itextpdf.tool</groupId>
        <artifactId>xmlworker</artifactId>
        <version>5.5.7</version>
</dependency>

 

📝 View

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

<body>
<h1> 웹화면에 PDF 출력해보기 </h1>
<embed src="/pdf" type="application/pdf" width=1500px height=1500px/>
</body>
</html>

 

 

📝 출력 화면

 

🔗 참고 및 출처

https://blog.naver.com/onandme/220529022550

https://lee-mandu.tistory.com/87

반응형
반응형
    File file = new File("D:\\contents.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));

    String line = null;

    while (true) {
        if ((line = br.readLine()) != null) content += line + "\n";
        else break;
    }

    br.close();

파일 읽기

 

OutputStream output = new FileOutputStream("D://filePathList.txt");
byte[] contentByte = allPath.getBytes();
output.write(contentByte);

output.close();

파일 쓰기

 

 

반응형
반응형

pom.xml

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.4</version>
</dependency>

 

servlet-context.xml

<beans:bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <beans:property name="maxUploadSize" value="5242880000" />
    <beans:property name="maxInMemorySize"
        value="100000000" />
</beans:bean>

 

multipart.java

@RequestMapping(value = "/upload.do", method = RequestMethod.POST)
public void upload(HttpServletRequest request, HttpServletResponse response) 
        throws IllegalStateException, IOException {

    MultipartFile multipartFile = null;

    String originalFileName = null; // 원본 파일 명
    String originalFileExtension = null; // 파일 확장자
    String storedFileName = null; // 저장될 파일 명


    // 파일을 받는 페이지 필요
    MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;

    // 반복자로 파일 이름을 담는다.
    Iterator<String> iterator = multipartHttpServletRequest.getFileNames();

    String uploadPath = "D:\\"; // 예) "D:\\

    // resource/egovframework/spring/context-properties.xml 에 파일업로드 경로 설정
    File file = new File(uploadPath);

    while (iterator.hasNext()) {
        multipartFile = multipartHttpServletRequest.getFile(iterator.next());

        if (multipartFile.isEmpty() == false) {

            originalFileName = multipartFile.getOriginalFilename();
            originalFileName = new String(originalFileName.getBytes("ISO-8859-1"), "UTF-8"); // 한글 깨짐 때문에 씀
            originalFileExtension = originalFileName.substring(originalFileName.lastIndexOf(".")); // .jpg
            storedFileName = UUID.randomUUID().toString() + originalFileExtension;

            file = new File(uploadPath + storedFileName);
            multipartFile.transferTo(file);

            System.out.println("originalFileName : " + originalFileName);
            System.out.println("storedFileName : " + storedFileName);
            System.out.println("type : " + multipartFile.getName());
            System.out.println("filename : " + multipartFile.getOriginalFilename());
            System.out.println("size : " + multipartFile.getSize());

        }
    }
}

 

multipart.js

$(function() {
	$("#sending").on("click", function() {
		sendImage();
	})
});

function sendImage(){

	var fileId = document.getElementById("file_input");
	var file = fileId.files[0];
	
	var formdata = new FormData();
	
	// formdata에 보낼 이미지 정보 담기 (키:값)
	formdata.append("file", file);
	console.log(formdata);

	
	$.ajax({
		type: "POST",
		url: "upload.do",
		data: formdata,
		processData: false, // 데이터를 컨텐트 타입에 맞게 변환 여부 (false 필수)
		contentType: false, // 요청 컨텐트 타입 (false 필수)
		success: function(data) {
			alert("파일이 전송 되었습니다.");
		},
		error: function(data) {
			alert("파일 전송에 실패했습니다.");
		}
	});
	
}

 

multipart.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
	<title>Home</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

<h1>
	Hello world!  
</h1>

	<input type='file' id='file_input'>
	<button id='sending'> 보내기 </button>
<P>  The time on the server is ${serverTime}. </P>
</body>
</html>

 

반응형
반응형
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.4.0</version>
</dependency>

<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.4.0</version>
</dependency>
@RequestMapping(value = "/qr.do", method = RequestMethod.GET)
public @ResponseBody void client(HttpServletRequest request, HttpServletResponse response, 
	HttpSession session) throws IllegalStateException, IOException, WriterException {

    /** 문제 내기 **/
    int randomCode = (int) (Math.random() * 100) + 1;
    String randomCodeStr = String.valueOf(randomCode);

    String strData = new String(randomCodeStr.getBytes("UTF8"), "ISO-8859-1");

    /** qr 생성 **/
    QRCodeWriter qrCodeWriter = new QRCodeWriter();
    BitMatrix bitMatrix = qrCodeWriter.encode(strData, BarcodeFormat.QR_CODE, 512, 512); // 200,200은 width,
                                                                                            // height
    MatrixToImageConfig matrixToImageConfig = new MatrixToImageConfig(0xFF2e4e96, 0xFFFFFFFF);
    BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix, matrixToImageConfig);

    /** 생성 qr을 화면에 노출 **/
    response.setContentType("image/png");
    OutputStream out = response.getOutputStream();

    ImageIO.write(bufferedImage, "png", out);

}
반응형
반응형

 

public String getRandomImage(HttpSession session) {

	filePath = "image\\rock_paper_scissor\\rock.JPG";
	URL resource = getClass().getClassLoader().getResource(filePath);
	filePath = resource.getFile();
    
	return filePath;
}

자바에서 파일 경로 불러올 때 경로는 webapp안에 있는 resources가 아닙니다.

 

 

<img src="/resources/image/captcha/rock_paper_scissor/scissor.JPG"/>

JSP 파일 경로를 불러올 때 경로는 webapp 안에 있는 resources입니다.

 

 

반응형