336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

안녕하세요.

퍼온글 : https://mkil.tistory.com/273

pom.xml

1
2
3
4
5
<dependency>
          <groupId>commons-fileupload</groupId>
          <artifactId>commons-fileupload</artifactId>
          <version>1.3.2</version>
        </dependency>
cs


servlet-context.xml

1
2
3
4
5
<!-- MultipartResolver -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
      <property name="maxUploadSize" value="100000000"/>
      <property name="maxInMemorySize" value="100000000"/>
    </bean>
cs


home.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$("#fileUpForm").change(function(){
                var form = $("#fileUpForm")[0];
                var data = new FormData(form);
                $.ajax({
                   enctype:"multipart/form-data",
                   method:"POST",
                   url: './fileUp.do',
                   processData: false,   
                   contentType: false,
                   cache: false,
                   data: data,
                   success: function(result){  
                       alert("업로드 성공!!");
                   }
                });
            });
<form name="fileUpForm" id="fileUpForm" enctype="multipart/form-data" method="POST" action="./excelDown.do">
    <input type="file" id="upFile" name="upFile" value="엑셀 업로드" />
</form>
cs


commUtil.java

1
2
3
4
//uuid생성 
    public static String getUuid() { 
        return UUID.randomUUID().toString().replaceAll("-"""); 
    }
cs


FileController.java

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
@RequestMapping(value = "/fileUp.do", method = RequestMethod.POST)
    public void ExcelUp(HttpServletRequest req, HttpServletResponse rep){
        logger.info("@@@@@@@@@@@@@@@FileUp START@@@@@@@@@@@@@@@");
        
        //파일이 저장될 path 설정 
        String path = "D://"
        Map returnObject = new HashMap(); 
        
        try { // MultipartHttpServletRequest 생성 
            MultipartHttpServletRequest mhsr = (MultipartHttpServletRequest) req; 
            Iterator iter = mhsr.getFileNames(); 
            MultipartFile mfile = null
            String fieldName = ""
            List resultList = new ArrayList(); // 디레토리가 없다면 생성 
            File dir = new File(path); 
            
            if (!dir.isDirectory()) { 
                dir.mkdirs(); 
            } 
            
            // 값이 나올때까지
            while (iter.hasNext()) { 
                fieldName = iter.next().toString(); // 내용을 가져와서 
            mfile = mhsr.getFile(fieldName); 
            String origName; 
            origName = new String(mfile.getOriginalFilename().getBytes("8859_1"), "UTF-8"); //한글꺠짐 방지 // 파일명이 없다면 
            
            if ("".equals(origName)) { continue; } // 파일 명 변경(uuid로 암호화) 
            
                String ext = origName.substring(origName.lastIndexOf('.')); // 확장자
                String saveFileName = CommUtil.getUuid() + ext;//getUuid() + ext; // 설정한 path에 파일저장 
                File serverFile = new File(path + File.separator + saveFileName); 
                mfile.transferTo(serverFile); 
                Map file = new HashMap(); 
                file.put("origName", origName); 
                file.put("sfile", serverFile); 
                resultList.add(file); 
                
                //DB에 들어갈만한 건들
                System.out.println("복호화된 파일 이름 : "+serverFile.getName()); //복호화된 파일 이름 
                System.out.println("물리적 저장 경로  : "+serverFile.getAbsolutePath()); //물리적 저장 경로 
                System.out.println("파일 크기 : "+serverFile.length()); //파일 크기 
                System.out.println("원래 파일 명 : "+origName); //원래 파일 명
 
            }
            
            returnObject.put("files", resultList); 
            returnObject.put("params", mhsr.getParameterMap()); 
            
        } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block 
            e.printStackTrace(); 
        }catch (IllegalStateException e) { // TODO Auto-generated catch block 
            e.printStackTrace(); 
        } catch (IOException e) { // TODO Auto-generated catch block 
            e.printStackTrace(); 
        }
        logger.info("@@@@@@@@@@@@@@@FileUp End@@@@@@@@@@@@@@@");
    }
cs




감사합니다.

'SPRING' 카테고리의 다른 글

SPIRNG EXCEL UPLOAD 하기  (1) 2019.04.01
SPRING FILE DOWNLOAD하기  (0) 2019.03.28
Spring Excel down하기  (0) 2019.03.28
SPRING JSTL 이용해서 Spring 값 뿌리기  (0) 2019.03.27
SPRING resources 사용하기  (0) 2019.03.27
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

퍼옴글 : https://jun7222.tistory.com/310


스프링 프레임워크 + tomcat 8.0 + oracle 11g 에서 혼자 로컬로 DB를 사용할 때는 아무 문제가

없다가 여러 인원이 DB서버 하나를 사용하게 될 때 발생했던 오류

close()를 해줘야 하는데 안하는게 쌓이다 보니 결국 오류가 뿜음..


ORA-12519, Error preloading the connection pool, no appropriate service handler found 보인다.



경고: Unexpected exception resolving reference

java.sql.SQLException: Error preloading the connection pool

at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2084)

Caused by: java.sql.SQLException: Listener refused the connection with the following error:

ORA-12519, TNS:no appropriate service handler found

at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:419)

org.apache.tomcat.dbcp.dbcp2.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:38)

... 22 more

Caused by: oracle.net.ns.NetException: Listener refused the connection with the following error:

ORA-12519, TNS:no appropriate service handler found

 

at oracle.net.ns.NSProtocol.connect(NSProtocol.java:386)

at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1054)

at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:308)

... 31 more

경고: Unexpected exception resolving reference

java.sql.SQLException: Error preloading the connection pool

at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2084)

at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getLogWriter(BasicDataSource.java:1587)

Caused by: oracle.net.ns.NetException: Listener refused the connection with the following error:

ORA-12519, TNS:no appropriate service handler found

 

at oracle.net.ns.NSProtocol.connect(NSProtocol.java:386)

at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1054)

at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:308)

... 79 more



오류 해결방법

1. close()를 해준다.


2. SELECT * FROM V$SESSION WHERE OSUSER != 'SYSTEM';  으로 점유하는 것을

확인하여 이상이 있는지 체크





이 글에서 소개할 방법은 3번

3. processes의 할당량을 늘려준다.


select * from v$resource_limit where resource_name = 'processes';

위 내용을 입력하여 현재 사용중인 수가 할당보다 많으면 위 오류를 나온다.


현재 32 최대 36 할당 100 




먼저, cmd를 실행한다.

sqlplus /nolog

SQL> conn /as sysdba


SQL>alter system set processes=200 scope=spfile;

               값은 적당하게~


SQL> shutdown immediate;

SQL> startup;




재시작까지 완료되고 다시 확인을 하면




위처럼 allocation, limit 값이 늘어난 걸 확인할 수 있다.



출처: https://jun7222.tistory.com/310 [leverage 블로그]

'DATABASE > ORACLE' 카테고리의 다른 글

ORACLE PROCEDURE 쿼리 COMMIT 또는 ROLLBACK  (0) 2017.02.16
ORACLE FOR LOOP구문  (0) 2017.02.16
ORACLE WHILE문과 LOOP문  (0) 2017.02.16
ORACLE 프로시저 IF문과 EXCEPTION처리방법  (0) 2017.02.16
ORACLE PLSQL  (0) 2017.02.12
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

안녕하세요

이번엔 DB에 있는 값을 EXCEL DOWN에 대해 써보겠습니다.


pom.xml

1
2
3
4
5
<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>
cs


HomeController.java가 있는 패키지에 ExcelController.java를 생성해 주세요.

ExcelController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Controller
public class ExcelController {
 
    private static final Logger logger = LoggerFactory.getLogger(ExcelController.class);
    
    //Service 연동
    @Resource(name = "homeService")
    private HomeService homeService;
    
    @RequestMapping(value = "/excelDown.do", method = RequestMethod.POST)
    public void ExcelDown(HttpServletResponse response){
        logger.info("@@@@@@@@@@@@@@@ExcelDown START@@@@@@@@@@@@@@@");
        
        homeService.getExcelDown(response);
        
        logger.info("@@@@@@@@@@@@@@@ExcelDown END@@@@@@@@@@@@@@@");
        
    }
}
cs


HomeService.java

1
public void getExcelDown(HttpServletResponse response);
cs


HomeServiceImpl.java

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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
@Override
    public void getExcelDown(HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<?> list = homeMapper.testDbList(map);
        
        try{
            //Excel Down 시작
            Workbook workbook = new HSSFWorkbook();
            //시트생성
            Sheet sheet = workbook.createSheet("게시판");
            
            //행, 열, 열번호
            Row row = null;
            Cell cell = null;
            int rowNo = 0;
            
            // 테이블 헤더용 스타일
            CellStyle headStyle = workbook.createCellStyle();
    
            // 가는 경계선을 가집니다.
            headStyle.setBorderTop(BorderStyle.THIN);
            headStyle.setBorderBottom(BorderStyle.THIN);
            headStyle.setBorderLeft(BorderStyle.THIN);
            headStyle.setBorderRight(BorderStyle.THIN);
    
            // 배경색은 노란색입니다.
            headStyle.setFillForegroundColor(HSSFColorPredefined.YELLOW.getIndex());
            headStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
    
            // 데이터는 가운데 정렬합니다.
            headStyle.setAlignment(HorizontalAlignment.CENTER);
    
            // 데이터용 경계 스타일 테두리만 지정
            CellStyle bodyStyle = workbook.createCellStyle();
            bodyStyle.setBorderTop(BorderStyle.THIN);
            bodyStyle.setBorderBottom(BorderStyle.THIN);
            bodyStyle.setBorderLeft(BorderStyle.THIN);
            bodyStyle.setBorderRight(BorderStyle.THIN);
    
            // 헤더 생성
            row = sheet.createRow(rowNo++);
    
            cell = row.createCell(0);
            cell.setCellStyle(headStyle);
            cell.setCellValue("번호");
    
            cell = row.createCell(1);
            cell.setCellStyle(headStyle);
            cell.setCellValue("이름");
    
            cell = row.createCell(2);
            cell.setCellStyle(headStyle);
            cell.setCellValue("제목");
    
            // 데이터 부분 생성
            for(Object map1 : list) {
                Map<String, Object> mapValue = (Map<String, Object>) map1;
                
                logger.info("DB DATA : "+mapValue.toString());
                
                row = sheet.createRow(rowNo++);
                cell = row.createCell(0);
                cell.setCellStyle(bodyStyle);
                cell.setCellValue(""+mapValue.get("IDCOL"));
                cell = row.createCell(1);
                cell.setCellStyle(bodyStyle);
                cell.setCellValue(""+mapValue.get("NAMECOL"));
                cell = row.createCell(2);
                cell.setCellStyle(bodyStyle);
                cell.setCellValue(""+mapValue.get("VALUECOL"));
            }
    
            // 컨텐츠 타입과 파일명 지정
            response.setContentType("ms-vnd/excel");
            response.setHeader("Content-Disposition""attachment;filename=test.xls");
 
            // 엑셀 출력
            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }
cs


마지막으로

home.jsp

1
2
3
<form name="excelForm" id="excelForm" method="POST" action="./excelDown.do">
    <input type="submit" id="excelDown" value="EXCEL 다운"/>
</form>
cs

 

후에 실행해보면 ExcelFile을 Down 받아서 보여줍니다.


감사합니다.

'SPRING' 카테고리의 다른 글

SPRING FILE DOWNLOAD하기  (0) 2019.03.28
Spring FileUpload 하기  (0) 2019.03.28
SPRING JSTL 이용해서 Spring 값 뿌리기  (0) 2019.03.27
SPRING resources 사용하기  (0) 2019.03.27
Ambiguous mapping found 에러 해결방법  (0) 2019.03.27
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

안녕하세요.



뿌려줄 데이터입니다.


HomeController.java

결과를 이부분에 저장했습니다.

1
model.addAttribute("dbList", list);
cs


home.jsp

저장한 것을 list라는 변수에 담아 처리했습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    <!-- 결과값 출력 -->
<table border="1">
    <tr>
        <td>번호</td>
        <td>작성자</td>
        <td>기타</td>
    </tr>
    <c:forEach var="list" items="${dbList }">
        <tr>
            <td>${list.IDCOL }</td>
            <td>${list.NAMECOL }</td>
            <td>${list.VALUECOL }</td>
        </tr>
    </c:forEach>
</table>
cs


감사합니다.

'SPRING' 카테고리의 다른 글

Spring FileUpload 하기  (0) 2019.03.28
Spring Excel down하기  (0) 2019.03.28
SPRING resources 사용하기  (0) 2019.03.27
Ambiguous mapping found 에러 해결방법  (0) 2019.03.27
log4j 로그 패턴들  (0) 2019.03.26
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

안녕하세요.

이번엔 spring에서 resource 사용설정을 써볼꼐요


servlet-context.xml

1
<mvc:resources location="/resources/" mapping="/resources/**" />
cs



home.jsp

1
2
3
4
5
6
7
<script src="/spring/resources/js/jquery-3.3.1.min.js"></script>
    <script>
        $(document).ready(function(){
            alert("start!");
        });
    </script>
 
cs



감사합니다.

'SPRING' 카테고리의 다른 글

Spring Excel down하기  (0) 2019.03.28
SPRING JSTL 이용해서 Spring 값 뿌리기  (0) 2019.03.27
Ambiguous mapping found 에러 해결방법  (0) 2019.03.27
log4j 로그 패턴들  (0) 2019.03.26
spring DB 로그 추가하기  (0) 2019.03.26
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

 

해당 에러시에는 spring URL및 RequestMethod가 똑같아서 나오는 에러이므로 변경하면 해결가능합니다.

 

'SPRING' 카테고리의 다른 글

SPRING JSTL 이용해서 Spring 값 뿌리기  (0) 2019.03.27
SPRING resources 사용하기  (0) 2019.03.27
log4j 로그 패턴들  (0) 2019.03.26
spring DB 로그 추가하기  (0) 2019.03.26
spring MVC DB 연결하기  (0) 2019.03.26
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.
출처 : http://mrjh.com/wiki/content.php?no=101

###############################################

# FaTAL : 가장 크리티컬한 에러가 일어 났을 때 사용합니다.
# ERROR : 일반 에러가 일어 났을 때 사용합니다.
# WARN : 에러는 아니지만 주의할 필요가 있을 때 사용합니다.
# INFO : 일반 정보를 나타낼 때 사용합니다.
# DEbUG : 일반 정보를 상세히 나타낼 때 사용합니다.

################################################



######################################################################
#%p  debug, info, warn, error, fatal 등의 priority 가 출력된다.  
#%m  로그내용이 출력됩니다
#%d  로깅 이벤트가 발생한 시간을 기록합니다.
#  포맷은 %d{HH:mm:ss, SSS}, %d{yyyy MMM dd HH:mm:ss, SSS}같은 형태로 사용하며 SimpleDateFormat에 따른 포맷팅을 하면 된다
#%t  로그이벤트가 발생된 쓰레드의 이름을 출력합니다.  
#%%  % 표시를 출력하기 위해 사용한다.  
#%n  플랫폼 종속적인 개행문자가 출력된다. \r\n 또는 \n 일것이다.  
#%c  카테고리를 표시합니다
#  예) 카테고리가 a.b.c 처럼 되어있다면 %c{2}는 b.c가 출력됩니다.
#%C  클래스명을 포시합니다.
#  예)클래스구조가 org.apache.xyz.SomeClass 처럼 되어있다면 %C{2}는 xyz.SomeClass 가 출력됩니다
#%F  로깅이 발생한 프로그램 파일명을 나타냅니다.
#%l  로깅이 발생한 caller의 정보를 나타냅니다
#%L  로깅이 발생한 caller의 라인수를 나타냅니다
#%M  로깅이 발생한 method 이름을 나타냅니다.
#%r  어플리케이션 시작 이후 부터 로깅이 발생한 시점의 시간(milliseconds)
#%x  로깅이 발생한 thread와 관련된 NDC(nested diagnostic context)를 출력합니다.
#%X  로깅이 발생한 thread와 관련된 MDC(mapped diagnostic context)를 출력합니다.

#######################################################################



#최상위 카테고리에 INFO로 레벨 설정 및 appender로 stdout, rolling을 정의
log4j.rootLogger=DEBUG, stdout, rolling

#stdout 어펜더는 콘솔에 뿌리겠다는 정의
log4j.appender.stdout=org.apache.log4j.ConsoleAppender

#stdout 어펜더는 patternlayout을 사용하겠다는 정의
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

#페턴은 다음과 같이 포맷팅 하겠다는 것을 정의
log4j.appender.stdout.layout.ConversionPattern=[%d{yyyy\ub144 MM\uc6d4 dd\uc77c HH:mm(ss)}] _%-5p_ [%t] %-17c{2} (%13F:%L) %3x -->\ub0b4\uc6a9 : %m%n



#역시나 rolling 어펜더는 파일로 처리한다라고 정의
log4j.appender.rolling=org.apache.log4j.DailyRollingFileAppender

#로그 파일 이름은 output.log
log4j.appender.rolling.File=output.log

#true면 톰캣을 내렸다 올려도 파일이 리셋되지 않습니다.
log4j.appender.rolling.Append=true

#파일 최대 사이즈는 500KB로 설정
log4j.appender.rolling.DatePattern='.'yyyy-MM-dd

#역시나 rolling 어펜더는 패턴 레이아웃을 사용하겠다고 정의
log4j.appender.rolling.layout=org.apache.log4j.PatternLayout

#rolling 어펜더는 패턴 레이아웃 포맷
log4j.appender.rolling.layout.ConversionPattern=[%d{yyyy\ub144 MM\uc6d4 dd\uc77c HH:mm(ss)}] _%-5p_ [%t] %-17c{2} (%13F:%L) %3x -->\ub0b4\uc6a9 : %m%n

 

'SPRING' 카테고리의 다른 글

SPRING resources 사용하기  (0) 2019.03.27
Ambiguous mapping found 에러 해결방법  (0) 2019.03.27
spring DB 로그 추가하기  (0) 2019.03.26
spring MVC DB 연결하기  (0) 2019.03.26
Eclipse 마켓(STS, spring Tool : STS) 설치하기  (0) 2015.05.28
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

안녕하세요.

spring DB 로그 추가에 대해 써보겠습니다.

DB를 불러오고난 뒤 부터 시작하겠습니다.

이전글을 참조해주세요. (spring MVC DB 연결하기)

 

pom.xml depandences 태그 안에 추가

1
2
3
4
5
<dependency> 
            <groupId>org.lazyluke</groupId> 
            <artifactId>log4jdbc-remix</artifactId> 
            <version>0.2.7</version> 
        </dependency>
cs

 

log4j.xml 추가

1
2
3
4
5
6
7
<logger name="jdbc.sqlonly">
        <level value="info" />
    </logger>
    
    <logger name="jdbc.resultsettable">
        <level value="info" />
    </logger>
cs

 

root-context.xml 수정 및 추가

1
2
3
4
5
6
7
8
9
10
 <!-- db Log추가 -->
 <bean id="dataSource" class="net.sf.log4jdbc.Log4jdbcProxyDataSource"> 
     <constructor-arg ref="dataSourceSpied" /> 
     <property name="logFormatter"> 
         <bean class="net.sf.log4jdbc.tools.Log4JdbcCustomFormatter"> 
             <property name="loggingType" value="MULTI_LINE" /> 
             <property name="sqlPrefix" value="SQL : "/> 
         </bean> 
     </property> 
 </bean> 
cs

수정

기존에 있는 dataSource를 dataSourceSpied로 변경

 

다시 호출해보면 결과가 이렇게 나옵니다.

 

 

 

 

감사합니다.

 

'SPRING' 카테고리의 다른 글

SPRING resources 사용하기  (0) 2019.03.27
Ambiguous mapping found 에러 해결방법  (0) 2019.03.27
log4j 로그 패턴들  (0) 2019.03.26
spring MVC DB 연결하기  (0) 2019.03.26
Eclipse 마켓(STS, spring Tool : STS) 설치하기  (0) 2015.05.28
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

안녕하세요.

spring mvc db 연결에 대해 설명하겠습니다.

해당 설명은 eclispe의 spring Project생성을 기반으로 하였음을 알려드립니다.

후에 기본 패키지 입력 후 finish

ex) com.java.spring

 

프로젝트 생성 후 선택되어있는 부분을 클릭하여 F2눌르고 controller, mapper, service패키지를 추가입력하여 하단 생성

 

 

HomeController.java

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
    
    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
    
    //Service 연동
    @Resource(name = "homeService")
    private HomeService homeService;
    
    /**
     * Simply selects the home view to render by returning its name.
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(Locale locale, Model model) {
        logger.info("Welcome home! The client locale is {}.", locale);
        
        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
        
        String formattedDate = dateFormat.format(date);
        
        model.addAttribute("serverTime", formattedDate );
        
        //추가한 코드 Service 연동
        Map<String, Object> map = new HashMap<String, Object>();
        List<?> list = homeService.getBagicDB(map);
        
        model.addAttribute("dbList", list);
        
        return "home";
    }
    
cs

 

 

HomeService.java  

1
2
3
4
5
6
7
8
9
10
11
package com.java.spring.service;
 
import java.util.List;
import java.util.Map;
 
public interface HomeService {
    
    public List<?> getBagicDB(Map<String, Object> map);
    
}
 
cs

 

HomeServiceImpl.java

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
package com.java.spring.service;
 
import java.util.List;
import java.util.Map;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import com.java.spring.controller.HomeController;
import com.java.spring.mapper.HomeMapper;
 
@Service("homeService")
public class HomeServiceImpl implements HomeService {
 
    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
    
    //HomeMapper 자동연결
    @Autowired
    private HomeMapper homeMapper;
    
    @Override
    public List<?> getBagicDB(Map<String, Object> map) {
        List<?> list = homeMapper.testDbList(map);
        //db 결과를 로그로 출력
        for(int position = 0; position < list.size(); position++){
            logger.info("position : "+list.get(position));
        }
        
        return list;
    }
 
}
cs

 

HomeMapper.java

1
2
3
4
5
6
7
8
9
10
11
package com.java.spring.mapper;
 
import java.util.List;
import java.util.Map;
 
public interface HomeMapper {
 
    public List<?> testDbList(Map<String, Object> map);
}
 
 
cs

testMapper.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="UTF-8"?>
 
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.java.spring.mapper.HomeMapper">
 
<!-- select 추출된 컬럼값들을 저장할 resultType을 지정함 -->
    <select id="testDbList" resultType="java.util.Map">
        SELECT *
        FROM testTable
    </select>
</mapper>
cs

 

home.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"  %>
<%@ page session="false" contentType="text/html; charset=UTF-8" %>
<!--  결과값 호환 -->
<html>
<head>
    <title>Home</title>
</head>
<body>
<h1>
    Hello world!  
</h1>
 
<P>  The time on the server is ${serverTime}. </P>
 
<!-- 결과값 출력 -->
${dbList }
 
</body>
</html>
 
cs

 

설정

root-context.xml

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
71
72
73
74
75
76
77
78
79
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
 
<!-- db oracle 연결
    destory-method : 소멸자
    drverClassName : 해당 DB 드라이버
    url : DB연결정보
    username : 접속ID
    password : 접속PW
    initialSize : 초기연결수
    maxActive :최대연결수
    maxIdle : Idle 상태 소유한 최대연결수
    minIdle : Idle 상태 소유한 최소연결수
    maxWait : 커넥션이 존재하지 않을 때, 커넥션을 얻기까지 대기하는 최대 대기시간
    removeAbandoned : 유효하지 않는 커넥션의 제거 여부
    removeAbandonedTimeout : 유효하지 않은 커넥션의 삭제시의 타임아웃
    validationQuery : 연결 정상확인
    
    @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
    목록에 엇는 사용값
    testOnBorrow : 풀에서 커넥션을 가져올시 커넥션의 유효성 검사(TRUE || FALSE)
    testOnReturn : 풀에 커넥션을 리턴할 때 커넥션의 유효성 검사(TRUE || FALSE)
    testWhileIdle : Idle상태에 커넥션의 유효성 검사(TRUE || FALSE)
    timeBetweenEvictionRunsMillis : 설정된 주기를 통해 Evict(유효하지 않는 커넥션/정의된 시간이 만료된 커넥션을 풀에서 제거) 쓰레드를 수행
    minEvictableIdleTimeMiilis : Evict 쓰레드를 수행시, 만료여부를 체크할 시간을 정의
    numTestsPerEvictionRun : Evict 쓰레드를 수행시 수행할 커넥션의 갯수
    logAbandoned : 유효하지 않는 커넥션을 생성한 코드 위치 로그생성 여부(TRUE || FALSE)
    
    defaultAutoCommit : 생성된 커넥션의 기본 auto commit 여부(TRUE || FALSE)
    defaultReadOnly : 생성된 커넥션의 기본 read-only 여부(TRUE || FALSE)
    defaultTransactionIsolation : 생성된 커넥션의 기본 트랜잭션 격리 수준
    defaultCatalog : 생성된 커넥션의 기본 카탈로그
    connectionInitSqls : SQL statements의 컬렉션으로 물리적 커넥션의 최기화에 사용. 설정된 커넥션 생성. DEFAULT : NULL?
    poolPreparedStatements : Prepared Statements 사용 여부(TRUE || FALSE)
    maxOpenPreparedStatements : Prepared Statements 최대 Open 갯수
    accessToUnderlyingConnectionAllowed : 물리적 연결 여부 (TRUE || FALSE)?
    minIdle : Idle상태에 풀이 소유한 최소 커넥션 갯수
-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
          p:driverClassName="oracle.jdbc.driver.OracleDriver"
          p:url="jdbc:oracle:thin:@localhost:1521:orcl" 
          p:username="ID" 
          p:password="PW"
          p:initialSize="2"
          p:maxActive="30"
          p:maxIdle="10"
          p:minIdle="3"
          p:maxWait="30000"
          p:removeAbandoned="true"
          p:removeAbandonedTimeout="30"
          p:validationQuery="SELECT 1 FROM DUAL" />
 
 
 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="configLocation" value="/WEB-INF/spring/mybatis-config.xml" />    <!-- mybatis 설정 -->
  <!--<property name="typeAliasesPackage" value="com.test.web" /> -->
  <property name="mapperLocations" value="classpath*:mapper/*Mapper.xml" />        <!-- mapper 경로 -->
  <!-- <property name="mapperLocations" value="classpath*:mapper/*Mapper.xml" /> -->
 </bean>
 
 <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
  <constructor-arg ref="sqlSessionFactory" />
 </bean>
 
 <!-- dao 스캔 -->
 <bean class"org.mybatis.spring.mapper.MapperScannerConfigurer">
  <property name="basePackage" value="com.java.spring.mapper" />                <!-- mapper interface pakage -->
 </bean>
</beans>
 
cs

 

mybatis-config.xml

1
2
3
4
5
6
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0/EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
 
<configuration>
    
</configuration>     
cs

 

servlet-context.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
 
    <!-- 추후에 따로 글을 추가할 예정입니다. -->
    <context:annotation-config/>
    <context:component-scan base-package="com.java.spring"/>
    
    <mvc:annotation-driven />
    
    
    <!-- prefix : 앞에 나오는 경로 생략 // suffix : 위에 나오는 확장자 생략 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix"><value>/WEB-INF/views/</value></property>
        <property name="suffix"><value>.jsp</value></property>
    </bean>
            
</beans>
cs

 

pom.xml

properties태그 아래에 추가(db 저장소)

1
2
3
4
5
6
<repositories> 
       <repository>
           <id>mesir-repo</id>
           <url>https://code.lds.org/nexus/content/groups/main-repo</url>
       </repository>
    </repositories>
cs

 

depandences 태그 안에 추가

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
<!-- ORACLE -->
        <dependency>
               <groupId>com.oracle</groupId>
                <artifactId>ojdbc6</artifactId>
                <version>11.2.0.3</version>
        </dependency>
        
        <dependency> 
            <groupId>org.mybatis</groupId> 
            <artifactId>mybatis</artifactId> 
            <version>3.2.2</version> 
        </dependency> 
        
        <dependency> 
            <groupId>org.mybatis</groupId> 
            <artifactId>mybatis-spring</artifactId> 
            <version>1.2.0</version> 
        </dependency> 
        
        <dependency> 
            <groupId>org.springframework</groupId> 
            <artifactId>spring-jdbc</artifactId> 
            <version>${org.springframework-version}</version> 
        </dependency> 
        
        <dependency> 
            <groupId>commons-dbcp</groupId> 
            <artifactId>commons-dbcp</artifactId> 
            <version>1.4</version> 
        </dependency>
cs

 

 

결과 1. HomeServiceImpl.java 에서 결과 로그

 

결과 2. home.jsp에서 결과

일단 DB의 결과를 표시하는 것만 했습니다.

jstl이나 dbㄹ그 추가등은 뒷글에 나올예정입니다.

 

감사합니다.

'SPRING' 카테고리의 다른 글

SPRING resources 사용하기  (0) 2019.03.27
Ambiguous mapping found 에러 해결방법  (0) 2019.03.27
log4j 로그 패턴들  (0) 2019.03.26
spring DB 로그 추가하기  (0) 2019.03.26
Eclipse 마켓(STS, spring Tool : STS) 설치하기  (0) 2015.05.28
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.


hostname : 호스트의 이름을 가져옵니다.


cd : 파일로 이동합니다다

ex) cd folderName (folderName으로 이동합니다. )

ex) cd .. 현재 경로의 상위로 이동합니다.

또한 응용(?)도 가능합니다 

ex) cd ../f (현재폴더의 상위의 f폴더로 이동합니다.)


cat 파일명 : 파일명을 보여줍니다.


vi 파일명 : vi형태로 파일을 봅니다. 리눅스의 메모장으로 생각하시면됩니다.


tail -f 파일명 : 해당 파일을 봅니다 (cat과 다른점이라면 파일이 변경된것을 실시간으로 볼 수 있습니다.)


mv 파일명1 파일명2 : 파일명1을 파일명 2로 바꾸어줍니다.


cp 파일명1 파일명2 : 파일명1을 파일명2로 복사해줍니다.


rm 파일명1 : 파일명1을 삭제합니다.


mkdir : 디렉토리를 삭제합니다.


pwd : 현재 경로를 보여줍니다.


alias lsA '명령어' : lsA이란 키워드로 명령어를 추가해줍니다.

ex) alias lsA 'ls -l'


who : 현재 로그인한 사용자명을 보여줍니다. 

'Linux' 카테고리의 다른 글

Linux Centos 인터넷 연결  (0) 2019.04.06
Linux Centos 설치하기  (0) 2019.04.06
Linux Centos 다운로드  (0) 2019.04.06
리눅스에서 톰켓 재시작 및 로그보기  (0) 2017.02.12

+ Recent posts