<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title>4일차</title>

<style>

</style>

<script>

<!-- if  -->

var date = new Date();

var hours = date.getHours();

 

if(hours < 12){

alert('오전입니다');

}

if(hours >= 12){

alert('오후입니다.');

}

<!-- 반복문  -->

var array = ['가', '나', '다', '라'];

array[0] = '윤';

alert(array[0]);

alert(array[1]);

alert(array[2]);

alert(array[3]);

for( var i = 0; i < 4 ; i++){

alert( i + 1 + '번째 출력 : ' + array[i]);

}

<!-- 객체 -->

var product = {

제품명 : '7D 건조 망고',

유형 : '당절임',

성분: '망고, 설탕, 메타중아황산나트륨, 치자황색소',

원산지: '필리핀'

}

for (var i in product){

alert(i+':'+product[i]);

}

<!-- 속성과 메소드 -->

var person = {

name: '홍길동',

eat: function(food){

alert(this.name + '이' + food + '을 먹습니다.');

}

}

person.eat('밥');

</script>

</head>

<body>

</body>

</html>

'Computer > JSP Servlet JavaScript' 카테고리의 다른 글

Eclipse 한글 사용 설정  (0) 2015.01.19
Tomcat 404에러(포트충돌)  (0) 2015.01.16
JSP navigation 마우스오버 Script  (0) 2015.01.14
JSP SQL Injection 방어 기법  (0) 2014.08.21
JSP 버튼이벤트  (0) 2014.08.19

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<script>

$(document).ready(function () {

$('.outer-menu-item').hover(function () {

$(this).find('.inner-menu').show();

}, function () {

$(this).find('.inner-menu').hide();

});

});

</script>

'Computer > JSP Servlet JavaScript' 카테고리의 다른 글

Tomcat 404에러(포트충돌)  (0) 2015.01.16
JavaScript 예제  (0) 2015.01.15
JSP SQL Injection 방어 기법  (0) 2014.08.21
JSP 버튼이벤트  (0) 2014.08.19
JQUERY 화면전환 없이 비동기 업로드  (0) 2014.08.18

SQL Injection 은 사용자가 요상한 문자열을 입력해서 쿼리를 요상하게 바꿔 버려서 아무 아이디로나 로그인이 훅 되버린다던지 하는 쪼금은 싱거운 해킹방법중의 하나라고 나는 알고 있다.


뭐 예를들어 아이디 비번을 입력하고 로그인 할때

아이디로  
admin' OR '1'='1 요런걸 입력하고 로그인을 했을때 admin 으로 싹 로그인 되 버리는 어처구니 없는 일이 발생하는 것이 SQL Injection 처리를 쪽바로 해주지 않았을때 일어나는 참혹한 일이다.


SQL Injection 이 발생하는 전형적인 코드는 다음과 같다.

1
2
3
4
5
6
7
8
9
10
11
12
String userid=request.getParameter("userid");
String password=request.getParameter("password");
 
....
....
 
Statement stmt = conn.createStatement();
ResultSet rs =
   stmt.executeQuery("select count(*) as cnt from member where userid='"+userid+"' and password='"+password+"'");
 
....
....




위 코드처럼 사용자 정보를 받아서 쿼리를 실행하고 실행결과가 1 이면 로그인 시켜주는 코드가 있다.

그런데 사용자가 아디디로 admin' OR '1'='1  을 입력하고 비밀번호로 abcd 를 입력한 후 로그인 시켜주셈~ 이라고 하면 우째될까?

위 코드대로라면  select count(*) from member where userid='amdin' OR '1'='1' and password = 'abcd'   이 쿼리가 실행되 버린다 -_-;;;

무섭다. 만약 사용자 테이블에 userid 가 admin 이라는 레코드가 있다면 admin 으로 로그인 되버리는 것이다. 

이런 어처구니 없는일이 놀랍게도 몇몇 허접한 사이트에서는 더러 통하는데도 있다 . -_-



아무튼 헛소리는 고만하고 본론으로 들어가서 SQL Injection 을 방지하려면 우째해야 될까? 

Statement 대신  PreparedStatement 를 쓰면 된다. 요렇게.

1
2
3
4
5
6
7
8
9
10
11
....
....
 
PreparedStatement stmt = conn.prepareStatement("select count(*) from member where userid=? and password=?");
stmt.setString(1, userid);
stmt.setString(2, password);
 
ResultSet rs = stmt.executeQuery();
 
....
....




PreparedStatement 만 쓰면 해결된다고 해서 또 요렇게는 쓰지 말길 -.-;

1
2
PreparedStatement stmt =
   conn.prepareStatement("select count(*) from member where userid='" + userid + "'" and password='" + password + "'");




※ 하이버네이트는 한번도 안써봐서 잘 모르겠는데 mybatis 나 ibatis 같은 경우는 무난하게 #{xxxx} 요런것만 썼다면 SQL Injection 이 방지된다. 

그런데 WHERE 절에 ${xxxx} 이렇게 있다면 다시 한번 생각해 보기 바란다. 

${xxxx} 이거는 문자열 더하는것과 똑같기 때문에 위험하다. ${xxxx} 요런건 ORDER BY 절 같은데만 사용하자.

'Computer > JSP Servlet JavaScript' 카테고리의 다른 글

JavaScript 예제  (0) 2015.01.15
JSP navigation 마우스오버 Script  (0) 2015.01.14
JSP 버튼이벤트  (0) 2014.08.19
JQUERY 화면전환 없이 비동기 업로드  (0) 2014.08.18
JSP Modal 사용하기  (0) 2014.08.14

<div class="row row-form">

<div class="col-md-12">

<a

onclick="mqigoWritePage('mainQnA.do?nowpage=1&start_row=1&finish_row=10');"

class="btn btn-success pull-right">목록으로</a> <a

onclick="delqnaPage('mainQnaDelete.do?qna_id=${qna.qna_id}');"

class="btn btn-success pull-right">질문삭제</a>

</div>

</div>


<!-- 코멘트삭제 -->


<script type="text/javascript">

function delCommentPage(updateurl) {

$.ajax({

url : updateurl,

success : function(resultData) {

qloadtabpage('mainQnAInner.do?qna_id=${qna.qna_id}');

}

});


}

</script>


<!-- 질문삭제 -->


<script type="text/javascript">

function delqnaPage(updateurl) {

$.ajax({

url : updateurl,

success : function(resultData) {

qloadtabpage('mainQnA.do?nowpage=1&start_row=1&finish_row=10');

}

});


}

</script>




<script type="text/javascript">

function qloadtabpage(loadingurl) {

$.ajax({

url : loadingurl,

type : 'get',//'post',

timeout : 1000,

traditional : true,

async : false,

error : function() {

alert('네트워크가 불안정합니다.');

},

success : function(resultData) {

$("#mainqnainnerview").html(resultData);

}

});

}

</script>

'Computer > JSP Servlet JavaScript' 카테고리의 다른 글

JSP navigation 마우스오버 Script  (0) 2015.01.14
JSP SQL Injection 방어 기법  (0) 2014.08.21
JQUERY 화면전환 없이 비동기 업로드  (0) 2014.08.18
JSP Modal 사용하기  (0) 2014.08.14
JSP c:choose  (0) 2014.08.14

출처 : http://blog.naver.com/sh_park0107/130175661601


* 화면전환 없이 비동기 업로드 *


1. 파일 업로드 폼

/fileUpload.jsp

 

1
2
3
4

<form name="serverInfoForm" id="serverInfoForm" method="post" action="/serverInfoUpload.do" enctype = "multipart/form-data">

        <input type="file" name="agentInstallFile" id="agentInstallFile"> 

        <input type="submit"  class="btn" value="전송">
</form>

 

  • form 의 id 를 지정해준다.
  • action 을 지정해준다. 파일을 보내는 컨트롤러
  • enctype을 반드시 multipart/form-data로 지정해준다.

 

2jquery.form.js 플러그인 사용하기

 

  • http://malsup.com/jquery/form/#download 에서 jquery.form.js 혹은 jquery.form.min.js 다운을 받아 js폴더에 넣어준다.
  •  <script src="js/jquery.form.js"></script> ㅎㅔ더(<HEAD></HEAD>에 삽입해준다

 

 

3. 파일업로드 jquery 소스 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$('#serverInfoForm').ajaxForm({
        
        dataType : 'text', 
        beforeSerialize: function(){
             // form을 직렬화하기전 엘레먼트의 속성을 수정할 수도 있다.            
        },
        beforeSubmit : function() {
        //action에 걸어주었던 링크로 가기전에 실행 ex)로딩중 표시를 넣을수도 있다.
        },

        success : function(data) {
             //컨트롤러 실행 후 성공시 넘어옴
            alert("등록완료 ! ");            
        }

    });

http://malsup.com/jquery/form/ 참고 ! (API)

 

 

  • form id를 넣어준다. $("#serverInfoForm")
  • beforeSerialize 는 form 을 직렬화 하기전에 실행되는 함수이다.
  • beforeSubmit 는 form 이 submit 되기전에 실행되는 함수

 

4. 파일업로드 컨트롤러 

MultipartHttpServletRequest 를 사용하기위 엮인글의 1번과, 3번 설정 필요!!

역인글 :  http://blog.naver.com/sh_park0107/130175605306


/serverInfoUpload.do

 Colored By Color Scripter

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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
@RequestMapping("/serverInfoUpload.do")
    public ModelAndView mybatistest(HttpServletRequest request) throws IOException{

        ModelAndView mav = new ModelAndView();
        
        MultipartHttpServletRequest multi = (MultipartHttpServletRequest) request;
        MultipartFile file = multi.getFile("agentInstallFile");//jsp 페이지에서 input type="file"의 파라미터명
                
         String path="";
         UUID randomeUUID = UUID.randomUUID();//중복 파일명 방지
                  
         if(file!=null){
        
          System.out.println("파라미터명" + file.getName());
          System.out.println("파일크기" + file.getSize());
          System.out.println("파일 존재" + file.isEmpty());
          System.out.println("오리지날 파일 이름" + file.getOriginalFilename());
        
          
          path = "d:/upload/";
          InputStream inputStream = null;
          OutputStream outputStream = null;
          
          String organizedfilePath="";
          
          try {
              
 
              if (file.getSize() > 0) {
                  inputStream = file.getInputStream();
                  File realUploadDir = new File(path);
                  
                  if (!realUploadDir.exists()) {//업로드하려는 path에 폴더가 없을경우
                      realUploadDir.mkdirs();//폴더생성.
                  }
                  
                  
                  organizedfilePath = path + randomeUUID + "_" + file.getOriginalFilename();
                  System.out.println(organizedfilePath);//파일이 저장된경로 + 파일 명
                  
                  outputStream = new FileOutputStream(organizedfilePath);
 
                  int readByte = 0;
                  byte[] buffer = new byte[8192];
 
                  while ((readByte = inputStream.read(buffer, 0, 8120)) != -1) {
                      outputStream.write(buffer, 0, readByte); //파일 생성 ! 
                      
                  }
            
                  
              }
              
          } catch (Exception e) {
              // TODO: handle exception
              e.printStackTrace();
 
          } finally {
 
              outputStream.close();
              inputStream.close();
          }
          
      
                 
         }    
          mav.setViewName("fileUpload");
        return mav;
                
    }

 


'Computer > JSP Servlet JavaScript' 카테고리의 다른 글

JSP SQL Injection 방어 기법  (0) 2014.08.21
JSP 버튼이벤트  (0) 2014.08.19
JSP Modal 사용하기  (0) 2014.08.14
JSP c:choose  (0) 2014.08.14
JSP select onchange  (0) 2014.08.14

<c:set var="rec" value="resources/"></c:set>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta charset="utf-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>My Lectures</title>




</head>

<body>


<a href="databoardInsert.do" data-toggle="modal" data-target="#dataModal" class="btn btn-success pull-right">글쓰기</a>

    <!-- Modal -->

<div class="modal fade" id="dataModal" tabindex="-1" role="dialog" aria-labelledby="dataModalLabel" aria-hidden="true" >

  <div class="modal-dialog modal-sm">

    <div class="modal-content" >

      <div class="modal-header">

        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>

        <h4 class="modal-title" id="dataModalLabel">Modal title</h4>

      </div>

      <div class="modal-body" >

        ....

      </div>

      <div class="modal-footer">

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

        <button type="button" class="btn btn-primary">Save changes</button>

      </div>

    </div>

  </div>

</div> 



</body>

</html>



form


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

pageEncoding="UTF-8"%>

<div class="modal-header">

<button type="button" class="close" data-dismiss="modal">

<span aria-hidden="true">&times;</span><span class="sr-only">Close</span>

</button>

<h4 class="modal-title" id="loginModalLabel">자료 올리기</h4>

</div>

<div class="modal-body" >


<form action="databoardInsert.do" method="post">

<div class="row row-form">


<label for="title" class="col-sm-2">  제목</label>

<div class="col-sm-10">

<input type="text" class="form-control" id="title"

placeholder="제목을 입력하세요">

</div>

</div>

<div class="row row-form">

<label for="filedirectory" class="col-sm-2">파일 첨부</label>

<div class="col-sm-10">

<input type="text" class="form-control" id="filedirectory"

placeholder="파일 경로">

</div>

</div>

<div class="row row-form">

<label for="content" class="col-sm-2">내용</label>

<div class="col-sm-10">

<textarea class="form-control" id="content" rows="7"></textarea>

</div>

</div>

<div class="row row-form">

<label for="content" class="col-sm-2">파일선택</label>

<div class="col-sm-10">

<input type="file" id="attachment1" name="attachment1"

placeholder="사진첨부1" class="input-large" required>

</div>

</div>

<div class="row row-form">

<div class="col-sm-12">

<button type="submit" class="btn btn-lg btn-primary pull-right">등록</button>

</div>

</div>




</form>

</div>



'Computer > JSP Servlet JavaScript' 카테고리의 다른 글

JSP SQL Injection 방어 기법  (0) 2014.08.21
JSP 버튼이벤트  (0) 2014.08.19
JQUERY 화면전환 없이 비동기 업로드  (0) 2014.08.18
JSP c:choose  (0) 2014.08.14
JSP select onchange  (0) 2014.08.14

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>


<c:choose>

<c:when test="${b.att_checks==0 }">결석</c:when>

<c:when test="${b.att_checks==1 }">출석</c:when>

<c:when test="${b.att_checks==2 }">지각</c:when>

<c:when test="${b.att_checks==3 }">조퇴</c:when>

</c:choose>

'Computer > JSP Servlet JavaScript' 카테고리의 다른 글

JSP SQL Injection 방어 기법  (0) 2014.08.21
JSP 버튼이벤트  (0) 2014.08.19
JQUERY 화면전환 없이 비동기 업로드  (0) 2014.08.18
JSP Modal 사용하기  (0) 2014.08.14
JSP select onchange  (0) 2014.08.14

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>




<c:set var="abc" value=""></c:set>

<c:set var="att" value=""></c:set>

<c:set var="lat" value=""></c:set>

<c:set var="ear" value=""></c:set>

<c:if test="${b.att_checks ==0}">

<c:set var="abc" value="selected"></c:set>

 </c:if>

<c:if test="${b.att_checks ==1}">

<c:set var="att" value="selected"></c:set>

</c:if>

<c:if test="${b.att_checks ==2}">

<c:set var="lat" value="selected"></c:set>

</c:if>

<c:if test="${b.att_checks ==3}">

<c:set var="ear" value="selected"></c:set>

</c:if>

<form>

<select class="form-control" id="chk_att" onchange="location = this.options[this.selectedIndex].value;">

<option id="1" value="attendanceUpdate.do?user_id=${a.user_id }&att_date=${b.att_date}&att_checks=1"                                                  

${att }>출석</option>

<option id="0" value="attendanceUpdate.do?user_id=${a.user_id }&att_date=${b.att_date}&att_checks=0"

          ${abc }>결석</option>

      <option id="2" value="attendanceUpdate.do?user_id=${a.user_id }&att_date=${b.att_date}&att_checks=2"

${lat }>지각</option>

<option id="3" value="attendanceUpdate.do?user_id=${a.user_id }&att_date=${b.att_date}&att_checks=3"

${ear }>조퇴</option>

</select>

</form>

'Computer > JSP Servlet JavaScript' 카테고리의 다른 글

JSP SQL Injection 방어 기법  (0) 2014.08.21
JSP 버튼이벤트  (0) 2014.08.19
JQUERY 화면전환 없이 비동기 업로드  (0) 2014.08.18
JSP Modal 사용하기  (0) 2014.08.14
JSP c:choose  (0) 2014.08.14

+ Recent posts