posted by 빛그루터기 2012. 4. 18. 17:06

jsp파일

<form method="post" name="regGoodsform" id="regGoodsform" enctype="multipart/form-data">
    <input type="file" name="name" id="id" size="55" maxlength="255">
</form>

java파일

 private File destinationDir = new File("파일저장될 폴더 위치"); //예) C:/file

 @RequestMapping("/aaa/bbb.do")
 public String insertNoticeInfo(DTO dto, Model model, HttpServletRequest request, HttpServletResponse response) {
   //전달 받은 Request값을 MultipartHttpServletRequest로 바인딩 시킨다.   
   MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
   
   List<TbNoticeImgDTO> listNoticeImg = new ArrayList<TbNoticeImgDTO>();

    //request의 "file"을 찾아 file객체에 세팅한다.
    MultipartFile file = multipartRequest.getFile("name");
    String fileName = file.getOriginalFilename();
    if(fileName != null && !fileName.equals("")) {
        long filesize = file.getSize();
        File destination = File.createTempFile("file", fileName, destinationDir);    
        FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(destination));
    }
}

 

posted by 빛그루터기 2012. 4. 16. 13:42

아직 완성이 된건 아니지만 기본기능(4칙연산등)은 모두 됨

 

import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;

class Exam12_sub extends Frame implements ActionListener {

 // 메뉴
 private MenuBar mb = new MenuBar(); 
 private Menu edit = new Menu("편집"); 
 private MenuItem fcopy = new MenuItem("편집");
 private MenuItem fpase = new MenuItem("편집");
 
 private Menu view = new Menu("편집");
 private CheckboxMenuItem v1 = new CheckboxMenuItem("편집", true);
 private CheckboxMenuItem v2 = new CheckboxMenuItem("편집", false);
 private CheckboxMenuItem v3 = new CheckboxMenuItem("편집");
 
 private Menu help = new Menu("편집");
 private MenuItem h1 = new MenuItem("편집");
 private MenuItem h2 = new MenuItem("편집");
  
 // 텍스트필드
 private TextField tf = new TextField();
  
 // 버튼
 private Button[] bt = new Button[24];
 private Button[] bt01 = new Button[3];
 
 // 버튼이름
 private String[] bt01name = {"Backspace","CE","C"}; 
 private String[] bt02name = {"MC","7","8","9","/","sqrt","MR","4","5","6","*","%","MS","1","2","3","-","1/x","M+","0","+/-",".","+","="};
 
 // 패널
 private Panel p = new Panel();
 private Panel p01 = new Panel();

 //사칙연산클릭확인
 int calnum = 1;
 
 String[] numarray = new String[3];
 
 // 사칙연산클릭확인
 boolean calclick = false;
 
 //String 문자열 패턴
 public String numpattern(String num) throws ParseException {  
  String pattern = "###,###,###,###,###,###.#######";  //패턴문양
  NumberFormat parser = new DecimalFormat(pattern);  //객체생성
  parser.setParseIntegerOnly(false);  //숫자형만 할것인지(true로 할경우 소수점 않나옴)
  parser.setMinimumFractionDigits(0); //소수점 최소자리
  parser.setMaximumFractionDigits(7);  //소수점 최대자리  
  return parser.format(parser.parse(num)); //패턴형식으로 리턴
 }
 
 //Exam12_sub class
 public Exam12_sub (String title) {
  super(title);
  Color bc = new Color(236, 233, 216);
  super.setBackground(bc);
  this.init();
  super.setSize(300,250);
  super.setLocation(100,100);
  super.setResizable(false);
  super.setVisible(true);
 }
 
 //모양만들기
 public void init() {

  //메뉴만들기
  edit.add(fcopy);
  edit.add(fpase);
  mb.add(edit);
  
  view.add(v1);
  view.add(v2);
  view.addSeparator();
  view.add(v3);
  mb.add(view);
  
  help.add(h1);
  help.addSeparator();
  help.add(h2);
  mb.add(help);
  this.setMenuBar(mb);
  
  //상당
  this.setLayout(new BorderLayout(10,10));
  this.tf.setText("0");  
  this.add("North",tf);
  
  Color red = new Color(255, 0, 0);
  
  //중단
  p01.setLayout(new GridLayout(1,3,10,10));
  for(int i=0; i < bt01.length; i++) {
   String btname = bt01name[i];
   bt01[i] = new Button(btname);
   bt01[i].setForeground(red);
   bt01[i].addActionListener(this);
   p01.add(bt01[i]);
  } 
  this.add("Center",p01);
  
  //하단
  p.setLayout(new GridLayout(4,6,10,10));
  for(int i=0; i < bt.length; i++) {
   String btname = bt02name[i];
   bt[i] = new Button(btname);
   if(i%6 == 0) {
    bt[i].setForeground(red);
   }
   bt[i].addActionListener(this);
   p.add(bt[i]);
  }
  this.add("South",p);  
 }

 //각 버튼 이벤트
 public void actionPerformed(ActionEvent e) {
  // TODO Auto-generated method stub
  String id = e.getActionCommand();
  int hashcode = id.hashCode();
  System.out.println("hashcode===>>>"+id.hashCode());
  
  //1~9까지
  if(hashcode >= 48 && hashcode <= 57 || hashcode == 46) {
   if(!this.calclick) {
    if(tf.getText().equals("0") || this.numarray[0] == null) {
     this.tf.setText(id);
    } else {
     this.tf.setText(tf.getText()+""+id);
    }    
   } else {
    this.tf.setText(id);
   }
   if(this.calnum == 1) {    
    numarray[0] =  this.tf.getText();
   } else if(this.calnum == 2) {
    numarray[2] = this.tf.getText();
   }
   this.calclick = false;

  //C, CE
  } else if(hashcode == 67 || hashcode == 2146 ) {
   this.tf.setText("0");
   
   //CE인경우 바로앞취소
   if(hashcode == 2146 ) {
    this.numarray[2] = null;
   
   //C인경우 초기화
   } else {
    this.numarray = new String[3];
    this.calnum = 1;
   }
  //backspace
  } else if(hashcode == -937491361) {
   if(!tf.getText().equals("0")) {
    if(this.tf.getText().length() == 1 ){
     this.tf.setText("0");
    } else {
     this.tf.setText(this.tf.getText().substring(0,this.tf.getText().length()-1));
    }
   }
  
  //사칙연산
  } else if(hashcode == 43 || hashcode == 47 || hashcode == 42 || hashcode == 45) {   
   
   //연산method
   cal(hashcode, e);   
   
   if(id.hashCode() == 43) {
    this.numarray[1] = "+";
   } else  if(id.hashCode() == 47) {
    this.numarray[1] = "/";
   } else  if(id.hashCode() == 42) {
    this.numarray[1] = "*";
   } else  if(id.hashCode() == 45) {
    this.numarray[1] = "-";
   }
   if(this.calnum == 1) this.calnum = 1+1;
   this.calclick = true;
  
  // "="
  } else if(hashcode == 61) {   
   cal(hashcode, e);
   this.calclick = false;
  
  // "+/-"  
  } else if (hashcode == 42825) {   
   try {
    if(this.calnum == 1) {
     if(this.numarray[0] == null || this.numarray[0].equals("0")) {
      this.numarray[0] = "0";    
      this.tf.setText("0");
     } else {
      this.numarray[0] = String.valueOf(Double.parseDouble(this.numarray[0])*-1);     
      this.tf.setText(numpattern(this.numarray[0]));
     }
    } else {
     if(this.numarray[2] == null || this.numarray[2].equals("0")) {
      this.numarray[2] = "0";
      this.tf.setText("0");      
     } else {
      this.numarray[2] = String.valueOf(Double.parseDouble(this.numarray[2])*-1);
      this.tf.setText(numpattern(this.numarray[2]));
     }
    }
   } catch (ParseException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
   }
  }
 }
 
 //연산만 따로 빼놓음
 public void cal(int num, ActionEvent e) {
  try {
   Double num01 = 0.0;
   if(this.numarray[0] != null && this.numarray[1] != null && this.numarray[2] != null) {   
    if(this.numarray[1].equals("+")) {
     num01 = Double.parseDouble(this.numarray[0])+Double.parseDouble(this.numarray[2]);
    } else if(this.numarray[1].equals("/")) {
     num01 = Double.parseDouble(this.numarray[0])/Double.parseDouble(this.numarray[2]);
    } else if(this.numarray[1].equals("*")) {
     num01 = Double.parseDouble(this.numarray[0])*Double.parseDouble(this.numarray[2]);
    } else if(this.numarray[1].equals("-")) {
     num01 = Double.parseDouble(this.numarray[0])-Double.parseDouble(this.numarray[2]);
    }
    numarray[0] = String.valueOf(num01);   
    this.tf.setText(numpattern(String.valueOf(num01)));
    
    if(num == 61) {
     this.calnum = 1;
     this.numarray = new String[3];
    }
   } else if(num == 61 && this.numarray[0] != null && this.numarray[2] == null)  {
    num01 = Double.parseDouble(this.numarray[0]);
    this.tf.setText(numpattern(String.valueOf(num01)));
    this.calnum = 1;
    this.numarray = new String[3];
   }
  } catch (ParseException e1) {
   e1.printStackTrace();
  }
 }
}

public class Exam12 {
 public static void main(String[] args) {
  Exam12_sub eb = new Exam12_sub("계산기");
 }
}

posted by 빛그루터기 2012. 4. 16. 13:41

public String numpattern(String num) throws ParseException {  
    String pattern = "###,###,###,###,###,###.#######";  //패턴문양
    NumberFormat parser = new DecimalFormat(pattern);  //객체생성
    parser.setParseIntegerOnly(false);  //숫자형만 할것인지(true로 할경우 소수점 않나옴)
    parser.setMinimumFractionDigits(0); //소수점 최소자리
    parser.setMaximumFractionDigits(7);  //소수점 최대자리  
    return parser.format(parser.parse(num)); //패턴형식으로 리턴
 }

'프로그램 > java' 카테고리의 다른 글

java로 만든 계산기소스(미완성)  (0) 2012.04.16
posted by 빛그루터기 2012. 3. 28. 13:25

<!DOCTYPE html>
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.17.custom.min.js"></script>
<script type="text/javascript">
    $(function(){

        $("input").val("1111");   //모든 input테그에 value값을 ddddd로 넣어준다.
        $("input").css("border","3px solid red"); //모든 input테그에 css값을 적용한다.
        $("input").attr("disabled",true);  //모든 input테그를 disabled상태로 만든다.


        $("input[id ='man']").val("4444");  // input테그 중 아이디가 man인것만 해당 값을 넣어준다.
        $("input[id ='man']").css("border","3px solid red"); // input테그 중 아이디가 man인것만  골라서 css를 적용한다.
        $("input[id ='man']").attr("disabled",true); // input테그 중 아이디가 man인것만 골라서 disabled상태로 만든다.


        $("input[id^='man']").val("2222");  // input테그 중 아이디가 man으로 시작되는 것 만 골라서 해당 값을 넣어준다.
        $("input[id^='man']").css("border","3px solid red"); // input테그 중 아이디가 man으로 시작되는 것 만 골라서 css를 적용한다.
        $("input[id^='man']").attr("disabled",true); // input테그 중 아이디가 man으로 시작되는 것 만 골라서 disabled상태로 만든다.


        $("input[id$='man']").val("3333");  // input테그 중 아이디가 man으로 끝나는 것 만 골라서 해당 값을 넣어준다.
        $("input[id$='man']").css("border","3px solid red"); // input테그 중 아이디가 man으로 끝나는 것 만 골라서 css를 적용한다.
        $("input[id$='man']").attr("disabled",true); // input테그 중 아이디가 man으로 끝나는 것 만 골라서 disabled상태로 만든다.


        $("input[id!='man']").val("4444");  // input테그 중 아이디가 man이 아닌것만 해당 값을 넣어준다.
        $("input[id!='man']").css("border","3px solid red"); // input테그 중 아이디가 man이 아닌것만  골라서 css를 적용한다.
        $("input[id!='man']").attr("disabled",true); // input테그 중 아이디가 man이 아닌것만 골라서 disabled상태로 만든다.

     });
</script>

<title>Insert title here</title>
</head>
<body>
  <input id="manffffff" />
  <input id="letterman" />
  <input id="newmilk" /> 
<br>
* jquery에서 id를 name으로 바꾸면 input테그의 name으로 동일한 효과를 볼 수 있다.
</body> 

posted by 빛그루터기 2012. 3. 28. 13:25

예정 ibatis에서 사용하던 <isEmpty></isEmpty>나 <isNull></isNull> 등을 비교구문은 mybatis에서 사용할 수 없다

그럼 mybatis에서는 어떤 비교구문을 사용할까?

 

가장 기초는 <if test="비교구문">쿼리</if>이다

 

기본적으로 사용하는 비교연산자 ==, !=, >, < 등을 사용하여 비교할 수 있다

<if test='변수명=="A"'>쿼리</if>

<if test="변수명 !='A'">쿼리</if> ...

 

그 다음 in 연산자를 사용할 수 있다.

<if test="변수명 in {'A','B','C'}"></if>

 

choose : 자바의 switch 구문과 유사

기본구성

<choose>

    <when test ="조건문">쿼리</when>

    <when test ="조건문">쿼리</when>

    <otherwise>쿼리</otherwise>  //java의 if구문에서 esle와 같은 역활

</choose>

 

그외에도 foreach등 여러가지가 있다. 

'프로그램 > mybatis(ibatis)' 카테고리의 다른 글

mybatis에서 procedure 호출하기  (0) 2012.03.28
selectKey 값 DAOImpl에서 가져오기  (0) 2012.03.28
posted by 빛그루터기 2012. 3. 28. 13:24

<insert id="insertTable" parameterType="HashMap" statementType="CALLABLE">
  { CALL procedure명 (#{a}, #{b}, #{c}, #{d}) } 
 </insert>

 

여기서 중요한 부분은 procedure를 호출 할때  statementType="CALLABLE" 를 추가해야 된다는것과

{와 CALL사이에는 한칸의 공간만 허용한다하는 것이다. 즉, { 과 CALL사이가 두칸이상 떨어졌거나

줄바꿈이 되어 있다면 procedure는 호출되지 않는다.

'프로그램 > mybatis(ibatis)' 카테고리의 다른 글

mybatis 조건 태그모음  (0) 2012.03.28
selectKey 값 DAOImpl에서 가져오기  (0) 2012.03.28
posted by 빛그루터기 2012. 3. 28. 13:24

mybatis에서 insert를 할 경우 저장 후 최종 시퀀스 값을 selectKey로 해서 넘겨주는데

이 넘겨준 값을 Spring에서 DAOImpl에서 어떻게 받느냐하면

 

mybatis에서  selectKey로 값을 넘겨 줍니다.

이때 keyProperty로 해당 값의 변수를 지정해 준다 (DTO에 해당 변수명 있어야됨)

 

<insert id="insertBoard" parameterType="newboard">
    INSERT INTO FAQ (
        B_NO, REF, STEP, B_LEVEL, NAME, SUBJ, NEWCONTENTS, HIT, REGIDATE,

        CONTENT, NOTICEYN
    ) VALUES (

        SEQ_FAQBNO.NEXTVAL, #{ref}, '0', '0', #{name}, #{subj}, #{newcontents}, '0', sysdate,

        #{newcontents}, 'N'
    )
    <selectKey resultType="int" keyProperty="b_no" order="AFTER">
        SELECT MAX(B_NO)  AS B_NO FROM FAQ

    </selectKey>
</insert>

 

 

DAOImpl 소스

다른 소스를 보면

int b_no = (int)getSqlSession().insert("newboard.insertBoard", newBoardDTO);

이렇게 되어 있는데 이렇게 하면 무조건 1로 반환되더군요;

 

아래 소스처럼 insert구분은 따로 selectKey값 받아오는것 따로입니다.

selectKey값이  해당 모델(DTO파일)의 keyProperty값과 같은 변수를 찾아 담아서 보내줍니다.

그럼 그 값을 해당 모델에서 꺼내오면 되는군요;

 

 @Override
 public int insertBoard(NewBoardDTO newBoardDTO) throws Exception {
     getSqlSession().insert("newboard.insertBoard", newBoardDTO);
     int b_no = newBoardDTO.getB_no();
     return b_no;
 } 

'프로그램 > mybatis(ibatis)' 카테고리의 다른 글

mybatis 조건 태그모음  (0) 2012.03.28
mybatis에서 procedure 호출하기  (0) 2012.03.28
posted by 빛그루터기 2012. 3. 28. 13:23

<%@ page language="java" contentType="text/html; charset=euc-kr" %>
<html>
<head>
<title>키보드 방향키로 로우셀렉트하기</title>
<meta http-equiv="Content-Type" content="text/html; charset=euc-kr">
<script language="javascript">

//현재 선택된 행 번호를 hidden에 넣어준다.
function setvalue(i) {
 var obj = document.getElementById('num');
    obj.value = i;
 return false;
}

//행선택시 이벤트
function rValue(i) {
 alert("선택행이벤트"+i);
}

//방향키로 행이동시 선택된 행번호를 가지는 변수
var y=0;

//방향기 행이동 이벤트
function teclaPulsada() {
 //행(리스트) 전체 숫자에서 하나를 뺀다 (0부터 시작하게 때문에)
 var listnum = 5;
 switch (event.keyCode) {
  case 40:
   document.getElementById('tabla').rows[y].bgColor='#FFFFFF';
   if (y==listnum){y=0;} else {y++;}
   document.getElementById('tabla').rows[y].bgColor='#CC66FF';
   setvalue(y);
  break
  case 38:
   document.getElementById('tabla').rows[y].bgColor='#FFFFFF';
   if (y==0){y=listnum;} else {y--;}
   document.getElementById('tabla').rows[y].bgColor='#CC66FF';
   setvalue(y);
  break
 }
}
   
//처음 로딩시 첫번째 행 자동선택되도록 하는 이벤트
function cambiarFondo() {
    document.getElementById('tabla').rows[y].bgColor='#CC66FF';
}
</script>

</head>
<body onkeyup="teclaPulsada();" onload="cambiarFondo();" >
<form name="Accountinfo02" method="post" style="ime-mode:active;">
<!-- 현재 선택된 행번호 -->
<input type="hidden" id="num" name="num" value="0" readonly>
<table width="470" height="260" border="0" cellspacing="0" cellpadding="0" align="center">
 <tr>
  <td align='left' class="msg">&nbsp;※ 선택하세요.</td>
 </tr> 
 <tr>
  <td valign="top">
   <table width="100%" align="center" class="tblst">    
    <tr align="center" valign="middle">
     <th width="40">순번</th>
     <th width="100">아이디</th>
     <th width="330">이름</th>
    </tr>
   </table> 
   <table width="100%" align="center" class="tblst" id="tabla">
    <tr onClick="rValue(0);" style="cursor:hand">
     <td width="40" align="center">1</td>
     <td width="100" align="center">1111111</td>
     <td width="316" align="center">1111111</td>
    </tr>
    <tr onClick="rValue(1);" style="cursor:hand">
     <td width="40" align="center">2</td>
     <td width="100" align="center">2222222</td>
     <td width="316" align="center">22222222</td>
    </tr>
    <tr onClick="rValue(2);" style="cursor:hand">
     <td width="40" align="center">3</td>
     <td width="100" align="center">3333333</td>
     <td width="316" align="center">3333333</td>
    </tr>
    <tr onClick="rValue(3);" style="cursor:hand">
     <td width="40" align="center">4</td>
     <td width="100" align="center">4444444</td>
     <td width="316" align="center">4444444</td>
    </tr>
    <tr onClick="rValue(4);" style="cursor:hand">
     <td width="40" align="center">5</td>
     <td width="100" align="center">5555555</td>
     <td width="316" align="center">5555555</td>
    </tr>
    <tr onClick="rValue(5);" style="cursor:hand">
     <td width="40" align="center">6</td>
     <td width="100" align="center">6666666</td>
     <td width="316" align="center">6666666</td>
    </tr>
   </table>
  </td>
 </tr>
</table>
</form>
</body>
</html> 

posted by 빛그루터기 2012. 3. 28. 13:20

web.zip


답글형계시판 일단 소스 압축해서 먼저 올림 

환경은 기존에 예제 올렸던 환경과 같습니다.

 

eclipse 인디고

톰켓 7.0.22

spring 3.1.0

mabatis3.0.5

ckediter

 

관련 라이브러니는 첨부파일에 같이 있습니다 

'프로그램 > spring' 카테고리의 다른 글

Spring3 초간단 파일업로드  (0) 2012.04.18
ORA-01000: 최대 열기 커서 수를 초과  (0) 2012.03.28
posted by 빛그루터기 2012. 3. 28. 13:07

spring 과 ibatis에서 insert구분을 여러개  돌릴 경우 batch를 이용하는데 있다

ORA-01000: 최대 열기 커서 수를 초과 에러가 떠서 보니 insert 구문이 300개가 넘어버려서

에러나 나네요

그래서 구글신에게 물어본 결과 아래와 같이 하면 잘 돌아갑니다.

 

참조

http://stackoverflow.com/questions/2921840/ibatis-startbatch-only-works-with-sqlmapclients-own-start-and-commit-transact

 

 

public void insertEmpSalmst(final List<SalAllSalaryModel> salpaylist) throws DataAccessException {
  super.execute(new SqlMapClientCallback() {

public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException {
    try {     
     int count = 0, total = 0;
     executor.startBatch();
     for (SalAllSalaryModel model : salpaylist) {
       executor.insert("ibatis 쿼리", model);
      }      
      count++;
      if (count % DB_BATCH_SIZE== 0)  { 
            total += executor.executeBatch();
            executor.startBatch();        
      }
     }

 total += executor.executeBatch();
    } catch (RuntimeException e) {
     e.printStackTrace();
    }
    return null;   

  }
  });
 }