원문 출처: https://rios.tistory.com/entry/JAVA-hashMap-key%EA%B0%92%EC%9C%BC%EB%A1%9C-value-%EC%B0%BE%EA%B8%B0-value%EB%A1%9C-key%EA%B0%92-%EC%B0%BE%EA%B8%B0

 

잊어버릴까.. 내 블로그에 넣어주자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
 
package java_sort;
 
import java.util.HashMap;
import java.util.Map;
 
public class HashmapGetdata {
 
    public static void main(String[] args) {
        
        Map<String, Object> hashMap = new HashMap();
 
 
        //데이터 넣어줌
        hashMap.put("num"1);
        hashMap.put("name""rios");
        hashMap.put("email""rios0812@naver.com");
        hashMap.put("phone_num""010-1234-1234");
 
 
        // ** value를 통해 key 값얻기 **       
        
        System.out.println(getKey(hashMap,"rios"));
        //rios라는 value 값을 통해서 얻은 key 값 -> name
        System.out.println(getKey(hashMap,"rios0812@naver.com"));
        //rios0812@naver.com 라는 value 값을 통해서 얻은 key 값 -> email
 
 
        // ** key를 통해 value얻기 **
 
        String getName = (String) hashMap.get("name");
        System.out.println(getName);
        //name 이란 key값을 통해서 value 값은 -> rios 
 
        String getPhone = (String) hashMap.get("phone_num");
        System.out.println(getPhone);
        //phone_num 이란 key값을 통해서 value 값은 -> 010-1234-1234
    }
 
 
   // hashmap에 value 로 key 찾기
   public static <K, V> K getKey(Map<K, V> map, V value) {
 
        for (K key : map.keySet()) {
            if (value.equals(map.get(key))) {
                return key;
            }
        }
        return null;
    }
 
 

[JAVA] unchecked or unsafe operations

 

Note : 자바파일이름.java uses unchecked or unsafe operations.

Note : Recompile with -Xlint: unchecked for details.

 

컴파일 에러.

JDK1.5이상에서는 다양한 타입의 객체들을 다루는 메소드나 컬렉션 클래스에 컴파일 시의 타입 체크를 해주는 제네릭(Generic) 메커니즘이 추가되었다. 따라서 제네릭 클래스나 인터페이스를 선언하거나 생성할 때 자료형을 명시해 주지 않으면 나는 에러이다.

단, 컴파일 시 이러한 에러가 나더라도 실행하면 정상적으로 작동이 되므로 크게 신경쓰지 않아도 된다. 

 

더 자세한 에러는 아래를 참고하여 확인하면 된다.

 

javac -Xlint 자바파일이름.java

[JAVA] MultipartParser 파일 저장경로를 파라메터로 받아서 업로드하기

 

저장 경로를 미리 정해두지 않고 파라메터로 받아서 처리하고 싶을때 

MultipartParser를 사용한다.

 

1. 클라이언트 (html)

 - ajax에서 multipart/form-data 로 보낼 것이므로 form에는 굳이 써주지 않아도 된다.

<form method="post" action="">
    <input type="hiddn" id="savePath">
    <input type="file" id="fileUpload">
    <input type="submit" value="Upload">
</form>

2. 클라이언트 (ajax)

  - 주의할 점은 파일의 경로를 먼저 append해주고 그 후에 파일을 append해준다.

//파일업로드 리스트 생성
var fileData = new FormData();
var files = $("#fileUpload").get(0).files;
 
fileData.append("savePath", "EMPLOYEE");
 
if (files.length > 0) {
    for (var i = 0; i < files.length; i++) {
        fileData.append(files[i].name, files[i]);
    }
}
 
$.ajax({
        type: "POST",
        url: hostUrl + "api/File/Upload",
        contentType: false,
        processData: false,
        async: false,
        crossDomain: true,
        data: fileData,
        success: function (data) {
            result = JSON.parse(data);
        },
        error: function (request, status, error) {
            alert("code:" + request.status + "\n" + "error:" + error);
        }
});

 

3. 백엔드(java)

- 파일데이터를 while문을 돌면서 순차적으로 파라메터로 받는다. 앞서 파일객체를 생성할 때 경로를 먼저 넣으라고 한 이유가 여기에 있다. 순차적으로 돌기 때문에 경로를 먼저 받아야 그 경로로 파일을 보낼 수 있는 것이다.

package com.file;
 
import java.io.*;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.oreilly.servlet.multipart.*;
 
public class Upload extends HttpServlet {
 
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        process(req, resp);
        
    }
    //처리내용
    protected void process(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out = resp.getWriter();
        
        // 30Mbyte 제한
        int maxSize  = 1024*1024*30;   
        String fsl = File.separator;
        String root = req.getSession().getServletContext().getRealPath(fsl);
        String rootPath = root + fsl + "Uploads";
        String savePath = "";
        
        MultipartParser mp = new MultipartParser(req, maxSize);
        mp.setEncoding("UTF-8");
 
        Part part;
        while ((part = mp.readNextPart()) != null) {
            String name = part.getName();
 
            //파일이 아닐때
            if (part.isParam()) {
                ParamPart paramPart = (ParamPart) part;
                String value = paramPart.getStringValue();
                //System.out.println("param; name=" + name + ", value=" + value);
                if (name.equals("savePath")) 
                    savePath = value;
                
            }
 
            // 파일일때
            else if (part.isFile()) {
                FilePart filePart = (FilePart) part;
                filePart.setRenamePolicy(new DefaultFileRenamePolicy()); //중복파일

                String fileName = filePart.getFileName();
                if (fileName != null) {
                    File dir = new File(rootPath + fsl + savePath);
                    if (!dir.isDirectory()){     //디렉토리인지 체크 후 없으면 생성
                        dir.mkdir();
                    }
                    //System.out.println(dir);
                    long size = filePart.writeTo(dir);
                }
                else {
                    //form type 이 file 이지만 비어있는 파라메터
                    System.out.println("file; name=" + name + "; EMPTY");
                }
            }
        }    
    }
    
}

개인적으로는 MultipartRequest로 보내는 것보다 이 방법이 더 좋은것 같다.

 

 

< MultipartRequest로 파일 업로드 하기 바로 가기 >

https://kwonyang.tistory.com/8

 

[JAVA] MultipartRequest File Upload

[JAVA] MultipartRequest File Upload 파일업로드를 하기 위해서는 oreilly.jar 를 먼저 다운받는다. 그리고 CLASSPATH 환경변수에 넣어둔다 (예: %CATALINA_HOME%\lib\oreilly.jar) 1. 클라이언트 단(Ajax) 제..

kwonyang.tistory.com

 

[JAVA] MultipartRequest File Upload

 

파일업로드를 하기 위해서는  oreilly.jar 를 먼저 다운받는다.

그리고 CLASSPATH 환경변수에 넣어둔다 (예: %CATALINA_HOME%\lib\oreilly.jar)

 

1. 클라이언트 단(Ajax)

<form method="post" action="/upload_test.do" enctype="multipart/form-data">
    제목: <input type="text" name="title">
    파일: <input type="file" name="upfile">
    <input type="submit" value="Upload">
</form>

2. 백엔드 단(java)

package com.file;
 
import java.io.*;
import java.util.Date;
import java.text.SimpleDateFormat;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
 
public class Upload extends HttpServlet {
 
    /*@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        process(req, resp);
    }*/
 
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        process(req, resp);
        
    }
    //처리내용
    protected void process(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out = resp.getWriter();
        
        String fsl = File.separator;
 
        // 30Mbyte 제한
        int maxSize  = 1024*1024*30;   
        // 웹서버 컨테이너 경로
        String root = req.getSession().getServletContext().getRealPath(fsl);
        // 파일 저장 경로
        String rootPath = root + "Uploads" + fsl;
        // 업로드 파일명
        String uploadFile = "";
        // 실제 저장할 파일명
        String newFileName = "";
 
        int read = 0;
        byte[] buf = new byte[1024];
        FileInputStream fin = null;
        FileOutputStream fout = null;
        long currentTime = System.currentTimeMillis();  
        SimpleDateFormat simDf = new SimpleDateFormat("yyyyMMddHHmmss");  
     
        try{
            MultipartRequest multi = new MultipartRequest(req, rootPath, maxSize, "UTF-8", new DefaultFileRenamePolicy());
                         
            // 전송받은 parameter의 한글깨짐 방지
            String title= multi.getParameter("title");
            title= new String(savePath.getBytes("8859_1"), "UTF-8"); 
            
            // 파일업로드
            uploadFile = multi.getFilesystemName("upfile");
 
            // 실제 저장할 파일명(ex : 20140819151221.zip)
            newFileName = simDf.format(new Date(currentTime)) +"."+ uploadFile.substring(uploadFile.lastIndexOf(".")+1);     
            
            // 업로드된 파일 객체 생성
            File oldFile = new File(rootPath + uploadFile);     
             
            // 실제 저장될 파일 객체 생성
            File newFile = new File(rootPath + newFileName);             
     
            // 파일명 rename
            if(!oldFile.renameTo(newFile)){     
                //rename이 되지 않을경우 강제로 파일을 복사하고 기존파일은 삭제     
                buf = new byte[1024];
                fin = new FileInputStream(oldFile);
                fout = new FileOutputStream(newFile);
                read = 0;
                while((read=fin.read(buf,0,buf.length))!=-1){
                    fout.write(buf, 0, read);
                }
                 
                fin.close();
                fout.close();
                oldFile.delete();
            }   
     
        }catch(Exception e){
            e.printStackTrace();
        }
 
    
    }
    
}

 

서블릿에서 HTTP Request Body 읽기

 

HTTP Request로 넘어온 값들 중 일부는

getParameter()나 getParameterValues()로 읽을 수 없는 경우가 있다. 

 

POST 메서드를 사용하면서 CONTENT-TYPE이 "application/json" 형식일 때 발생하는데, 

이를 RequestBody post data라고 하며 이러한 값은 

Request.getInputStream() 혹은 Request.getReader()를 통해 직접 읽어와야 한다고 한다.

 

아래 ajax에서 전송한 값은 RequestBody post data이다. 

<script type="text/javascript">
  $(document).ready(function() {
    $.ajax({
      type: "post",
      url: "<%=request.getContextPath()%>/ajaxtest.action?id=1",
      data: '[{"name1":"value1", "name2":"value2"}, {"name1":"value3", "name2":"value4"}]',
      dataType: "json",
      contentType: 'application/json; charset=utf-8',
      success: function(data) {
        ob = data;
      },
      error: function(jqXHR, textStatus, errorThrown) {
        console.log(jqXHR);
        console.log(textStatus);
        console.log(errorThrown);
      }
    });
  });
</script>

 

Servlet 에서 아래처럼 작성하여 읽을 수 있다.

package com.test;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class Dispatcher extends HttpServlet {
    private static final long serialVersionUID = 1L;
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        process(req, resp);
    }
 
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        process(req, resp);
    }
 
    protected void process(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println(getBody(req));
    }
    
    public static String getBody(HttpServletRequest request) throws IOException {
 
        String body = null;
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
 
        try {
            InputStream inputStream = request.getInputStream();
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                char[] charBuffer = new char[128];
                int bytesRead = -1;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            }
        } catch (IOException ex) {
            throw ex;
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException ex) {
                    throw ex;
                }
            }
        }
 
        body = stringBuilder.toString();
        return body;
    }
}

<결과: Console>

[{"name1":"value1", "name2":"value2"}, {"name1":"value3", "name2":"value4"}] 

 

 

 

 

MYSQL에서

DATEDIFF, TIMEDIFF 를 이용해 날짜 및 시간을 계산해보기로 합니다.

 

 

1. 날짜차이 계산하기 : DATEDIFF(expr1, expr2)

SELECT DATEDIFF('2016-04-20','2016-04-01') AS DiffDate

 > 결과값: 19

 

2. 시간차이 계산하기 : TIMESTAMPDIFF(시간표현단위, 시작체크시간, 종료체크시간)

SELECT TIMESTAMPDIFF(minute, '2016-04-20 01:01', '2016-12-31 23:59') AS time_diff;

 > 결과값: 368578(분)

 

* 시간표현단위: second, minute, hour, day, week, month, quarter, year

 

그런데 위와 같이 하면 문자열을 바로 계산하는 것으로 최대 1분까지 차이가 날 수 있다. 

따라서 아래와 같이 DATE 포멧으로 변경 후에 적용하면 더욱 더 정확하다.

 

3. 문자형에서 날짜형으로 데이터 전환 : DATE_FORMAT

SELECT TIMESTAMPDIFF(minute, 
      date_format('2016-04-20 01:01', '%Y-%m-%d %H:%i'), 
      date_format('2016-12-31 23:59', '%Y-%m-%d %H:%i')) AS time_diff;

 

 


네이버에서 티스토리로 글 이동 중입니다.

코딩 관련 글은 특히나 구글에서 유입이 많이 되서 고민 끝에 티스토리로 정착하게 되었습니다.

그동안 조회가 높았던 글부터 하나씩 편집해서 이 곳에 가지고 오도록 할께요~

 

같이 예쁘게 코딩하는 개발자가 되어보아요~ ㅎㅎ

혹시나 추가로 의견이 있으신 분은 댓글 언제든지 환영합니다.

 

 

+ Recent posts