- 전체보기 

SHOW PROCEDURE STATUS

 

- 특정 DB내 프로시저만 보기

SHOW PROCEDURE STATUS WHERE db = DB이름

JDBCAppender를 상속한 커스텀클래스 없이 진행하려 했으나...

로그에 포함된 특수문자 (')로 인하여 에러가 발생하였다...ㅠㅠ

 

여러가지 시도한 후 아직까지 에러가 나타나지 않은 방법을 기록해두기로 한다...

 

 

1. DB Table 작성 (Mysql)

 CREATE TABLE `tbl_log` (

     `regdate` timestamp NOT NULL,

     `level` varchar(100) NOT NULL,

     `logger` varchar(100) NOT NULL,

     `message` varchar(5000) DEFAULT NULL

 )

 

 

2. log4j.xml 수정

 

 - log4j.xml 상단

 <appender name="db" class="mini.home.jdbc.CustomJDBCAppender" />

   <param name="driver" value="com.mysql.jdbc.Driver" />

   <param name="URL" value="jdbc:mysql://DB주소" />

   <param name="user" value="DB아이디" />

   <param name="password" value="DB암호" />

   <param name="sql" value="insert into tbl_log values(now(), '%p', '%C', '%m')" />

 </appender>

 - log4j.xml 하단

 <root>

   <priority value="warn" />

   <appender-ref ref="console" />

   <appender-ref ref="db" />

 </root>

 

 

3. CustomJDBCAppender 작성 (https://bryan7.tistory.com/406)

 import org.apache.log4j.LogManager; 
 import org.apache.log4j.spi.LoggingEvent;

 import org.apache.log4j.jdbc.JDBCAppender;


 public class CustomJDBCAppender extends JDBCAppender { 

    @Override 

    protected String getLogStatement(LoggingEvent event) { 

        Object eventMsgObj = event.getMessage(); 
        String eventMessage = ""; 

        if( eventMsgObj != null && eventMsgObj.toString() != null ) { 
        // DB에 입력하기 위해서는 (') 를 ('')로 치환해야지 에러없이 제대로 입력된다. 
            eventMessage = eventMsgObj.toString().replaceAll("'", "''").replaceAll("(?<!\r)\n", "\r\n"); 
        } 
        if (null != event.getThrowableInformation() ) { 
        // DB에 저장할 때는 "\r\n" 이 아닌 "\n"만 "\r\n"으로 바꾼다. 
        // 부정형 후방탐색 정규표현식 이용 => replaceAll("(?<!\r)\n", "\r\n") 

            Throwable throwable = event.getThrowableInformation().getThrowable(); 
            String message = ""; 
            if( throwable != null ) { 
                message = throwable.getMessage(); 
                if( message != null ) { 
                    message = message.replaceAll("'", "''").replaceAll("(?<!\r)\n", "\r\n");
                } 
            } 

            Exception exception = new Exception(message, throwable); 
            exception.setStackTrace(throwable.getStackTrace()); 
            LoggingEvent clone = new LoggingEvent(event.fqnOfCategoryClass, 

                            LogManager.getLogger(event.getLoggerName()), event.getLevel(), eventMessage, exception); 

            return getLayout().format(clone); 

       

        } else { 
            LoggingEvent clone = new LoggingEvent(event.fqnOfCategoryClass, LogManager.getLogger(

                                                              event.getLoggerName()), event.getLevel(), eventMessage, null); 
            return getLayout().format(clone); 
        } 
    } 
 }

 

 

 

 

참조 블로그

1. https://arincblossom.wordpress.com/2018/04/05/log4j%EB%A1%9C-%EC%84%9C%EB%B2%84-%EB%A1%9C%EA%B7%B8%EB%A5%BC-db%EC%97%90-%EB%82%A8%EA%B8%B0%EA%B8%B0/

2. https://bryan7.tistory.com/406 

3. https://handcoding.tistory.com/135 

4. https://itmore.tistory.com/entry/%EC%8A%A4%ED%94%84%EB%A7%81-Log4j-%EB%8B%A4%EB%A3%A8%EA%B8%B0 

5. https://www.tutorialspoint.com/log4j/log4j_logging_database.htm

 

 

** 잘못된 내용이 있으면 일러주시면 감사하겠습니다.

written by 미니아빠

 

자주 사용하는 margin과 padding 옵션이지만, 순서가 헷갈린다.....ㅠㅠ

 

margin : (top-bottom), (left-right)

margin : (top), (left-right), (bottom)

margin : (top), (left), (bottom), (right)

 

** padding도 동일하다

 

written by 미니아빠

1. web.xml


- 웹 어플리케이션을 위한 배치기술서 (Deployment Descriptor)


- 주요 역할

1. WAS(ex. Tomcat)에 필요한 정보 전달

2. Spring Container 생성 (ContextLoaderListener, DispatcherServlet)

3. Encoding 설정


- ContextLoaderListener : WebApplicationContext를 생성한다. (root 컨텍스트 - 공통 beans 설정)

> contextConfigLocation 파라미터의 xml 설정파일들을 로드한다. (ex. root_context.xml)


- DispatcherServlet :  WebApplicationContext를 생성한다. (root 컨텍스트의 자식 context)

> 태그 내의 contextConfigLocation 파라미터의 xml 설정파일들을 로드한다. (ex. servlet_context.xml)




2. root_context.xml


- Controller가 공유하는 Beans 설정


- ex. hikariCP 등~




3. servlet_context.xml


- Servlet 내 Beans 설정


- HandlerMapping, ViewResolver 등 




4. pom.xml


- 프로젝트 내 라이브러리 관리




참조 및 출처 :

https://gmlwjd9405.github.io/2018/10/29/web-application-structure.html

https://doublesprogramming.tistory.com/84

https://jeong-pro.tistory.com/96



** 잘못된 내용이 있으면 일러주시면 감사하겠습니다.

written by 미니아빠

'미니아빠의 웹개발 > Spring MVC' 카테고리의 다른 글

Spring Log4j 로그 DB에 저장하기  (0) 2019.04.08

벌써 연말정산의 시즌이 돌아왔네요.

(연말정산 신고기간2019년 3월 11일까지 입니다. 참고 하시길.....)


어제 친구님께서 홈택스에서 배우자와 자녀를 등록하는 법을 모르겠다며 도움을 청하더군요.


국세청이 바쁜 기간이다보니, 전화도 안 받는다 하더군요....허허....


간단한 일이지만, 처음 접하시는 분들은 어려움이 있으실 것이라 생각이듭니다.


그래서!! 여기 간단하게 미성년자녀와 배우자의 자료를 합산하는 방법을 정리해서 올려보기로 했습니다.



1. 국세청 홈택스에 접속합니다. (https://www.hometax.go.kr)






2. 성명과 주민등록번호를 입력하고, 공인인증서로 로그인합니다.






3. 유의사항 안내를 필독하시고, [닫기] 버튼을 누릅니다.






4. 소득, 세액공제 자료 조회하는 화면이 나왔습니다.

   화면 오른쪽 윗 부분에 [제공동의현황] 버튼을 누릅니다.







5. 작년 소득에 관한 것이므로, 귀속년도는 2018년을 선택한 후 [조회하기]를 눌러봅니다.

   아래 리스트에 나타는 것이 없다면 함께 처리되는 사람이 없는 것입니다.

   미성년자녀를 등록하기 위해서는 [미성년자녀신청] 을,

   배우자 또는 기타 가족을 등록하기 위해서는 [자료제공동의신청]

   클릭하시면 됩니다.






6. 미성년 자녀자료 조회신청 팝업이 나왔습니다.

   자녀의 주민등록번호를 입력하시고 신청하면 됩니다.






7. 자녀의 자료제공이 신청이 되면, 나(조회자)에게 자료를 제공하는 자 (현재) 목록에 자녀의 정보가 나타납니다.

   [간소화 자료조회] 버튼을 누릅니다.







8. 간소화 자료조회에서 의료비를 클릭하니, 자녀의 병원비 지출 내역이 나타납니다. 성공!






(추가) 배우자의 경우 [제공동의현황] 화면에서, [자료제공동의신청] 버튼을 누릅니다. (위 5번)

필요한 정보를 입력하시고, 배우자의 공인인증서를 이용해서 신청하시면 되겠습니다.




끝~



written by 미니아빠




MySQL 내 date(), date_sub(), date_format() 함수를 활용한 Timestamp 날짜 비교




1. 특정 날짜의 레코드 조회


특정 날짜(ex, 2019-01-30)에 해당하는 레코드를 가져오기 위해...


>> select * from TABLE_NAME where DATE(TIMESTAMP_COLUMN) = DATE('2019-01-30');


위와 같이 사용할 수 있다.


오늘 날짜로 비교하기 위해서 '2019-01-30' 대신 NOW()를 사용할 수도 있다.





2. 지난 일주일 간의 레코드 조회


>> select * from TABLE_NAME where DATE(TIMESTAMP_COLUMN) >= DATE_SUB(NOW(), INTERVAL 7 DAY);


DATE_SUB() 함수를 활용하여 사용할 수 있다.


다른 기간의 자료를 조회하기 위해서 7 대신 필요한 만큼의 날짜수를 입력하면 된다.





3. 이번 달에 등록된 레코드 조회


>> select * from TABLE_NAME where DATE(TIMESTAMP_COLUMN) >= DATE_FORMAT(NOW(), '%Y-%m-01');


DATE_FORMAT() 함수를 활용하여 사용할 수 있다.





4. 이번 년도에 등록된 레코드 조회


>> select * from TABLE_NAME where DATE(TIMESTAMP_COLUMN) >= DATE_FORMAT(NOW(), '%Y-01-01');


3번 항목과 크게 다르지 않다. 포맷 형식의 월에 대한 부분만 수정하면 된다.





5. 참조자료 (https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html)




▷ DATE(expr)

Extracts the date part of the date or datetime expression expr.

mysql> SELECT DATE('2003-12-31 01:02:03'); -> '2003-12-31'




▷ NOW([fsp])

Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS format, depending on whether the function is used in a string or numeric context. The value is expressed in the current time zone.

If the fsp argument is given to specify a fractional seconds precision from 0 to 6, the return value includes a fractional seconds part of that many digits.

mysql> SELECT NOW();
        -> '2007-12-15 23:50:26'
mysql> SELECT NOW() + 0;
        -> 20071215235026.000000

NOW() returns a constant time that indicates the time at which the statement began to execute. (Within a stored function or trigger, NOW() returns the time at which the function or triggering statement began to execute.) This differs from the behavior for SYSDATE(), which returns the exact time at which it executes.

mysql> SELECT NOW(), SLEEP(2), NOW();
+---------------------+----------+---------------------+
| NOW()               | SLEEP(2) | NOW()               |
+---------------------+----------+---------------------+
| 2006-04-12 13:47:36 |        0 | 2006-04-12 13:47:36 |
+---------------------+----------+---------------------+

mysql> SELECT SYSDATE(), SLEEP(2), SYSDATE();
+---------------------+----------+---------------------+
| SYSDATE()           | SLEEP(2) | SYSDATE()           |
+---------------------+----------+---------------------+
| 2006-04-12 13:47:44 |        0 | 2006-04-12 13:47:46 |
+---------------------+----------+---------------------+

In addition, the SET TIMESTAMP statement affects the value returned by NOW() but not by SYSDATE(). This means that timestamp settings in the binary log have no effect on invocations of SYSDATE(). Setting the timestamp to a nonzero value causes each subsequent invocation of NOW() to return that value. Setting the timestamp to zero cancels this effect so that NOW() once again returns the current date and time.

See the description for SYSDATE() for additional information about the differences between the two functions.




▷ DATE_ADD(date,INTERVAL expr unit), DATE_SUB(date,INTERVAL expr unit)

These functions perform date arithmetic. The date argument specifies the starting date or datetime value. expr is an expression specifying the interval value to be added or subtracted from the starting date. expr is evaluated as a string; it may start with a - for negative intervals. unit is a keyword indicating the units in which the expression should be interpreted.

For more information about temporal interval syntax, including a full list of unit specifiers, the expected form of the expr argument for each unit value, and rules for operand interpretation in temporal arithmetic, see Temporal Intervals.

The return value depends on the arguments:

  • DATE if the date argument is a DATE value and your calculations involve only YEARMONTH, and DAY parts (that is, no time parts).

  • DATETIME if the first argument is a DATETIME (or TIMESTAMP) value, or if the first argument is a DATE and the unit value uses HOURSMINUTES, orSECONDS.

  • String otherwise.

To ensure that the result is DATETIME, you can use CAST() to convert the first argument to DATETIME.

mysql> SELECT DATE_ADD('2018-05-01',INTERVAL 1 DAY); -> '2018-05-02' mysql> SELECT DATE_SUB('2018-05-01',INTERVAL 1 YEAR); -> '2017-05-01' mysql> SELECT DATE_ADD('2020-12-31 23:59:59', -> INTERVAL 1 SECOND); -> '2021-01-01 00:00:00' mysql> SELECT DATE_ADD('2018-12-31 23:59:59', -> INTERVAL 1 DAY); -> '2019-01-01 23:59:59' mysql> SELECT DATE_ADD('2100-12-31 23:59:59', -> INTERVAL '1:1' MINUTE_SECOND); -> '2101-01-01 00:01:00' mysql> SELECT DATE_SUB('2025-01-01 00:00:00', -> INTERVAL '1 1:1:1' DAY_SECOND); -> '2024-12-30 22:58:59' mysql> SELECT DATE_ADD('1900-01-01 00:00:00', -> INTERVAL '-1 10' DAY_HOUR); -> '1899-12-30 14:00:00' mysql> SELECT DATE_SUB('1998-01-02', INTERVAL 31 DAY); -> '1997-12-02' mysql> SELECT DATE_ADD('1992-12-31 23:59:59.000002', -> INTERVAL '1.999999' SECOND_MICROSECOND); -> '1993-01-01 00:00:01.000001'




▷ DATE_FORMAT(date,format)

Formats the date value according to the format string.

The following specifiers may be used in the format string. The % character is required before format specifier characters.

SpecifierDescription
%aAbbreviated weekday name (Sun..Sat)
%bAbbreviated month name (Jan..Dec)
%cMonth, numeric (0..12)
%DDay of the month with English suffix (0th1st2nd3rd, …)
%dDay of the month, numeric (00..31)
%eDay of the month, numeric (0..31)
%fMicroseconds (000000..999999)
%HHour (00..23)
%hHour (01..12)
%IHour (01..12)
%iMinutes, numeric (00..59)
%jDay of year (001..366)
%kHour (0..23)
%lHour (1..12)
%MMonth name (January..December)
%mMonth, numeric (00..12)
%pAM or PM
%rTime, 12-hour (hh:mm:ss followed by AM or PM)
%SSeconds (00..59)
%sSeconds (00..59)
%TTime, 24-hour (hh:mm:ss)
%UWeek (00..53), where Sunday is the first day of the week; WEEK() mode 0
%uWeek (00..53), where Monday is the first day of the week; WEEK() mode 1
%VWeek (01..53), where Sunday is the first day of the week; WEEK() mode 2; used with %X
%vWeek (01..53), where Monday is the first day of the week; WEEK() mode 3; used with %x
%WWeekday name (Sunday..Saturday)
%wDay of the week (0=Sunday..6=Saturday)
%XYear for the week where Sunday is the first day of the week, numeric, four digits; used with %V
%xYear for the week, where Monday is the first day of the week, numeric, four digits; used with %v
%YYear, numeric, four digits
%yYear, numeric (two digits)
%%A literal % character
%xx, for any x not listed above

Ranges for the month and day specifiers begin with zero due to the fact that MySQL permits the storing of incomplete dates such as '2014-00-00'.

The language used for day and month names and abbreviations is controlled by the value of the lc_time_names system variable (Section 10.15, “MySQL Server Locale Support”).

For the %U%u%V, and %v specifiers, see the description of the WEEK() function for information about the mode values. The mode affects how week numbering occurs.

DATE_FORMAT() returns a string with a character set and collation given by character_set_connection and collation_connection so that it can return month and weekday names containing non-ASCII characters.

mysql> SELECT DATE_FORMAT('2009-10-04 22:23:00', '%W %M %Y'); -> 'Sunday October 2009' mysql> SELECT DATE_FORMAT('2007-10-04 22:23:00', '%H:%i:%s'); -> '22:23:00' mysql> SELECT DATE_FORMAT('1900-10-04 22:23:00', -> '%D %y %a %d %m %b %j'); -> '4th 00 Thu 04 10 Oct 277' mysql> SELECT DATE_FORMAT('1997-10-04 22:23:00', -> '%H %k %I %r %T %S %w'); -> '22 22 10 10:23:00 PM 22:23:00 00 6' mysql> SELECT DATE_FORMAT('1999-01-01', '%X %V'); -> '1998 52' mysql> SELECT DATE_FORMAT('2006-06-00', '%d'); -> '00'



written by 미니아빠

게시판의 글 내용을 <textarea>태그로 작성 중 줄 바꿈이 적용되지 않아 replace() 메소드를 활용하기로 했다.




w3schools.com 에 따르면....



JavaScript String replace() Method


Definition and Usage

The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.

Note: If you are replacing a value (and not a regular expression), only the first instance of the value will be replaced. To replace all occurrences of a specified value, use the global (g) modifier (see "More Examples" below).

Read more about regular expressions in our RegExp Tutorial and our RegExp Object Reference.

This method does not change the original string.


Syntax

string.replace(searchvalue, newvalue)


Parameter Values

ParameterDescription
searchvalueRequired. The value, or regular expression, that will be replaced by the new value
newvalue

Required. The value to replace the search value with




replace() 메소드는 문자열의 특정 값이나 정규식을 찾아 원하는 문자열로 변경해준다~라는 의미인 듯 하다.

노트에 따르면 변경하고자 하는 문자열의 첫번째 검색에 한하여 원하는 문자열로 변경해준다고 한다. 여기까지는 기존에 알던 사실.


그러나 추가적으로!! global (g) modifier를 사용하면 모든 검색에 대해 원하는 문자열로 변경해준다고 한다!!



코드에 적용해보았다.



<form role='writeForm' action='/write' method='post>

<textarea name='contents'></textarea>                // <textarea>로 문자열을 입력받는다


<button type='submit'>등록</button>

</form>


<script>

$(document).ready(fucntion(e){


var writeForm = $("form[role='writeForm']");


$("button[type='submit']").on("click", fucntion(e){    // 등록 button 클릭시 이벤트 발생


e.preventDefault();


var orginalStr    = $("textarea[name='contents']").val();            // 기존 <textarea>에 입력된 문자열

var newStr        = originalStr.replace(/(\r\n|\n)/g, '<br/>');    // 줄바꿈을 <br/>태그로 변경한 새로운 문자열


$("textarea[name='contents']").val(newStr);        // 수정된 문자열을 <textarea>에 입력


writeForm.submit();                                      // submit

});

});

</script>




부족한 부분은 피드백 부탁드립니다.

감사합니다.



인용자료 :

w3schools.com : https://www.w3schools.com/jsref/jsref_replace.asp





written by 미니아빠

아기와 함께 외식을 하는 것은 쉽지 않다.

특히 아기가 아직 앉지 못하는 경우에는 레스토랑에서 제공하는 아기 의자도 소용이 없다.


아기는 특히 부모가 식사를 하건, 안하건 자신만의 스케줄에 따라 살기 때문에 외식 장소를 고를 때 고려해야 할 몇 가지가 있다.


1. 유모차와 함께 들어갈 수 있거나, 그것이 어렵다면 아이가 누울 수 있어야 한다.

2. 너무 시끄럽거나, 밝으면 곤란하다.

3. 너무 덥거나 추워도 곤란하다.

4. 연기가 자욱한 곳은 곤란하다.


한마디로 표현하자면, 아이가 잘 수 있는 환경이 되어야 한다는 것이다.



우리 미니를 양육하면서(물론, 미니엄마가 대부분을 합니다....허허...), 외식이란 걸... 몇 번 해보지도 못했지만, 그래도 이곳에서는 정말 편하게 식사했던 기억 밖에 없는 것 같다.





안산 25시 광장에 위치한 포메인 안산점이다.




천장의 조명(빨간색 동그라미)이 있기는 하지만 대체로 어두운 분위기이다.

조명을 피할 수 있는 자리가 하나 있다. (화살표)




개별 의자가 아닌 통(?)의자이기 때문에 아이를 눕히기도 좋다.




세상 모르고 자는 우리 미니




잘 자는 미니 덕분에 오늘 호강했다. 





written by 미니아빠


+ Recent posts