웹개발하면서 DB의 사용은 필연적이기 때문에 java.sql.PreparedStatement의 사용은 필연적이다. Statement도 있기는 하지만 PreparedStatement는 한번 사용한 SQL문이저장되기 때문에 반복해서 사용할 경우 성능이 좋기 때문에 일반적으로는 PreparedStatement를 사용한다.



StringBuffer sql = new StringBuffer(" INSERT INTO poll (col1, col2 ) VALUES (?, ?) ");


psmt = conn.prepareStatement(sql.toString());

psmt.setString(1, "test");

psmt.setString(2, "test");

psmt.executeUpdate();




일반적으로 위와 같이 사용하는데 저렇게 사용해서 결과값 받아서 결과값 리턴해주고 끝인데 상황에 따라서는 쿼리를 반복적으로 사용해야할 때가 있다. 보통은 저게 DAO에 들어있기 때문에 메서드를 여러번 실행해도 되겠지만 그렇게 하면 Connection도 끝었다 다시하기 때문에 별로 효율적이지 못하다.



StringBuffer sql = new StringBuffer(" INSERT INTO poll (col1, col2 ) VALUES (?, ?) ");


for(int i = 0; i<5; i++) {

    psmt = conn.prepareStatement(sql.toString());

    psmt.setString(1, "test");

    psmt.setString(2, "test");

    psmt.executeUpdate();

}




하지만 여러번 반복해서 쿼리를 실행하기 위해서 위처럼 사용하면 안된다. 보기에는 크게 문제가 없고 일반적인 객체의 경우는 저렇게 재할당해서 사용해도 되기는 하지만 PreparedStatement는 다르다. 저렇게한 다음에 psmt.close();를 실행하면 아래쪽 맨 마지막psmt만 닫히고 앞의 psmt들은 닫히지 않는다. 정확히 말하면  앞에서 할당한 psmt는 결코 닫을수 없는 형태가 되어버린다.



StringBuffer sql = new StringBuffer(" INSERT INTO poll (col1, col2 ) VALUES (?, ?) ");

psmt = conn.prepareStatement(sql.toString());


for(int i = 0; i<5; i++) {

    psmt.setString(1, "test");

    psmt.setString(2, "test");

    psmt.executeUpdate();

    psmt.clearParameters();

}




이걸 위처럼 사용하고 있다. PreparedStatement의 객체를 새로할당하는게 아니라파라미터를 할당하고 실행한 다음에 psmt.clearParameters();로 파라미터를 클리어해버린다. 루프돌면서 다시 할당하고 이렇게 돌리면 PreparedStatement객체를 여러번 사용할 수 있다. 



StringBuffer sql = new StringBuffer(" INSERT INTO poll (col1, col2 ) VALUES (?, ?) ");

psmt = conn.prepareStatement(sql.toString());


for(int i = 0; i<5; i++) {

    psmt.setString(1, "test");

    psmt.setString(2, "test");

    psmt.addBatch();

    psmt.clearParameters();

}

psmt.executeBatch();




이걸 좀 더 세련(?)되게 하면 위와같이 사용할 수 있다. JDBC의 배치기능을 사용한 것이다. PreparedStatement의 배치기능은 다수의 쿼리를 한꺼번에 실행하기 위한 기능이다. 여러번에 나누어서 실행하지않고 배치기능을 이용해서 한번에 송신해서 실행함으로써 퍼포먼스를 높일 수 있다.

addBatch()는 쿼리와 파라미터 셋을 배치에 추가하고 이렇게 추가된 배치를 executeBatch()를 통해서 한꺼번에 실행한다. 정확한 테스트까지는 못해봤지만 이렇게 사용하는 배치 메모리의 크기 제한이 있기 때문에 너무 많은 배치를 추가할 경우에는 out of memory가 발생할 수 있기 때문에 많은 addBatch()를 실행해야 할 경우에는 중간중간 executeBatch()를 실행해 주어야 한다.



출처 : https://blog.outsider.ne.kr/266

'Server Enterprise > JDBC & DBCP' 카테고리의 다른 글

[Oracle] JDBC Connection  (0) 2013.07.17
Oracle DBCP Connection pool - Eclipse 환경  (0) 2013.02.07
DBCP 에서 JNDI 설정 방법  (0) 2012.07.20
public class StringFinder {
    public static void main(String[] args) {

        String txt1 = "가나다라" ;
        String txt2 = "해당 내용은 테스트 입니다" ;
        String txt3 = "가격은 29,000원 입니다" ;

        // contains를 이용한 방법(true, false 반환)
        if(txt1.contains("나다"))
            System.out.println("문자열 있음!");
        else
            System.out.println("문자열 없음!");
         
         
        // indexOf를 이용한 방법
        if(txt2.indexOf("테스트") > -1)
            System.out.println("문자열 있음!");
        else
            System.out.println("문자열 없음!");
         
         
        // matches를 이용한 방법
        if(txt2.matches(".*테스트.*"))
            System.out.println("문자열 있음!");
        else
            System.out.println("문자열 없음!");
         
         
        // matches를 이용하여 정규 표현식으로 문자열에 숫자가 있는지 확인
        if(txt3.matches(".*[0-9].*"))
            System.out.println("숫자 있음!");
        else
            System.out.println("숫자 없음!");
    }
}

contains문자열에 검색하고자 하는 문자가 있는지 확인 : 포함 - true / 미포함 - false
indexOf 문자열에서 검색하는 문자의 위치를 반환 : 포함 - 문자 위치 / 미포함 - ( -1 )
matches 정규식을 이용하여 문자열을 검색한다, 특정 문자열을 검색할때 사용하기 보다는 한글, 숫자 등과 같이 해당 형태의 텍스트가 존재하는지 확인할때 사용하면 좋다 : 포함 - true / 미포함 - false



출처 : http://fruitdev.tistory.com/72


'Server Enterprise > Java' 카테고리의 다른 글

[Java] Design Pattern  (0) 2016.07.07
[Book] 알고리즘 관련 서적 for java  (0) 2016.07.05
[random] java.security.SecureRandom  (0) 2016.01.12
[Request] 호스트 설정 jsp  (0) 2016.01.12
URL Encoding 특수문자 코드  (0) 2015.07.22



SecureRandom random = new SecureRandom ();

//랜던 문자 길이

int numLength = 16;

String randomStr = "";


for (int i = 0; i < numLength; i++) {

//0 ~ 9 랜덤 숫자 생성

//randomStr += ran.nextInt(10);

randomStr += random.nextInt(10);

System.out.println("randomStr "+ i + " :: " + randomStr);

}




아래 출처 : https://jonghwasu.wordpress.com/2013/02/15/%EA%B0%95%EB%A0%A5%ED%95%9C-%EB%82%9C%EC%88%98%EB%A5%BC-%EC%83%9D%EC%84%B1-%ED%95%9C%EB%8B%A4/



  • 강력한 난수를 생성한다.
    • 의사 난수 생성기는 좋은 통계적 성질을 가진 일련의 수 배열을 생성하는 결정성 수학 알고리즘을 사용
    • 그러나 숫자 배열이 진정한 난수성을 갖지는 않는다.
    • 의사 난수 생성기는 일반적으로 초깃값(seed value)으로 시작한다.
    • 알고리즘은 이 초깃값을 사용해 난수를 생성하고 새로운 초깃 값을 만들고, 다시 이 초깃 값을 사용해 그 다음 난 수 값을 만든다.
  • 자바 API는 java.util.Random 클래스로 의사 난수 생성기를 구현한다.
    • 의사 난수 생성기는 이식 할 수 있고 반복될 수 있다.
    • 따라서 동일한 초깃값을 사용해 생성한 두개의 java.util.Random 객체는 모든 자바 구현에서 동일한 숫자 배열을 생성하게 된다.
    • 어플리케이션을 초기화 하거나 시스템이 재 시동된 후에 초깃값이 재 사용되곤 한다.
    • 또는 시스템 클럭에서 가져온 현재 시간에서 유도하여 초깃 값으로 사용하기도 한다.
  • 부적합 코드예
    • 이 클래스는 모든 주어진 초깃 값에 대해 동일한 숫자 배열을 생성한다. 따라서 앞으로 나올 숫자를 예상 할 수 있다.
    1
    2
    3
    4
    5
    6
    Random rand1 = new Random(123L);
     
    /* [0,20] 범위에 있는 또다른 정수현 난수를 생성한다. */
    int n = rand1.nextInt(21);
    System.out.println("Random1 =================================================");
    System.out.println(n);
  • 적합 코드 예
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    /* java.security.SecureRandom 클래스를 사용해 고품질의 난수를 만들어낸다. */
    SecureRandom rand3 = null;
    try {
        rand3 = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
     
    System.out.println("SecureRandom============================================");
    n = rand3.nextInt(21);
    System.out.println(n);
  • 적합 코드 예
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    /* Random의 기본 생성자를 이용하면 생성자를 호출 할 때 마다 다른 값을 초기 값으로 가져올 수 있다. */
    Random rand2 = new Random();
    System.out.println("Random2 =================================================");
    for(int i = 0; i < 20; i++) {
        /* 난수 생성기의 초깃값을 다시 설정 */
        rand2 = new Random();
        n = rand1.nextInt(21);
        System.out.println(n);
    }

String svrHost = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();

print) svrHost    ::    http://localhost:8080


if (svrHost.matches("(?i).*127.0.0.1:8080.*")){ // (?i).*내용.* ==> 대소문자 구분없이

// local logic

} else if (svrHost.matches("(?i).*10.185.130.23:6010.*")) {

// dev logic

else if (svrHost.matches("(?i).*http://www.domain.co.kr.*") || svrHost.matches("(?i).*http://domain.co.kr.*")) {

// http prd logic

} else if (svrHost.matches("(?i).*https://www.domain.co.kr.*") || svrHost.matches("(?i).*https://domain.co.kr.*")) {

// https prd logic

} else { }



ServletRequest와 HttpServletRequest의 구분

 

 ServletRequest는 기본적인 클라이언트 요청에 관한 모든 정보를 가지고 있습니다. 그리고 이 인터페이스는 다시 HttpServletRequest로 확장하여 HTTP프로토콜상에서 할 수 있는 일들이 포함되어져 있습니다. 이 HttpServletRequest는 서블릿의 service의 매개변수의 하나로 서블릿 프로그래머가 클라이언트의 요청에 관한 작업들을 핸들할 수 있도록 하는 중요한 역할을 담당하고 있습니다. ServletRequest인터페이스의 구조를 살펴보면 다음과 같은 부분으로 나눌 수 있습니다.

 

ServletRequest의 구조

n        클라이언트 자체에 대한 정보추출

n        클라이언트가 전송한 정보 추출

 

 이러한 구조에 따라서 ServletRequest의 메서드를 분류해 보면 다음과 같습니다.

 

ServletRequest의 멤버메서드

클라이언트 자체에 대한 정보추출

Object getAttribute(String name): 주어진 이름을 갖는 속성값을 얻습니다.

Enumeration getAttributeNames(): 이 요청이 갖는 속성들의 이름에 대한 Enumeration 객체를 얻습니다.

void setAttribute(String key, Object o): 주어진 이름의 속성을 설정합니다.

void remvoeAttribute(String key): 주어진 이름의 속성을 제거합니다.

String getProtocol(): "HTTP/1.1" 과 같은 형식으로 프로토콜 및 major/minor 버전을 얻습니다.

String getRemoteAddr(): 요청한 클라이언트의 IP(Internet Protocol) 주소를 얻습니다.

String getRemoteHost(): 요청한 클라이언트의 호스트 이름을 얻습니다.

String getScheme(): http, https, 또는 ftp 등과 같은 요청을 위해 사용된 방법의 이름을 얻습니다.

String getServerName(): 요청을 받은 서버의 이름을 얻습니다.

int getServerPort(): 요청을 받은 포트 번호를 얻습니다.

 

ServletRequest의 멤버메서드

클라이언트가 전송한 정보추출

String getCharacterEncoding(): 이 요청에 사용된 문자 인코딩을 얻습니다.

int getContentLength(): 이 요청에 포함되어 있는 데이터의 길이를 구하며, 만약 길이를 알 수 없는 경우에는 ?1이 리턴됩니다.

String getContentType(): 요청에 포함되어 있는 내용에 대한 MIME 타입 또는 모를 경우에는 null을 얻습니다.

Enumeration getParameterNames(): 매개변수들의 이름에 대한 Enumeration 객체를 얻습니다.

String getParameter(String name): 주어진 이름의 매개변수가 갖는 값을 얻습니다.

String[] getParameterValues(String name): 주어진 이름으로 전달된 매개변수가 갖는 모든 값을 문자열 배열로 얻습니다. 매개변수가 다중 선택이 가능한 리스트(list) 또는 선택박스(choicebox)의 값이라면, 여러 개의 값이 하나의 이름으로 전달될 수 있습니다.

BufferedReader getReader(): 요청 바디로부터 문자 인코딩에 따라 텍스트를 읽어들이기 위한 BufferedReader 객체를 얻습니다.

ServletInputStream getInputStream(): 이 요청의 바디로부터 바이너리 데이터를 읽어들이기 위해, 한 번에 한 라인씩 읽을 수 있는 ServletInputStream 객체를 얻습니다.

 

이와 같은 메서드들은 HTTP 프로토콜에 맞추어져 있는 것이 아니라 일반적인 네트웍 통신기반에 의해서 사용되는 메서드입니다. 그래서 HTTP프로토콜에 존재하는 Session과 Cookie같은 정보를 추출하는 작업은 할 수 없습니다. 그렇기 때문에 HTTP프로토콜을 지원하는 HttpServletRequest에서는 당연히 HTTP프로토콜에 사용되는 대부분의 기능을 포함하고 있습니다. HTTP프로토콜상에서 사용되는 기능별로 분류해 보면 다음과 같습니다.

 

HttpServletRequest의 기능별 분류

n        request객체의 요청 파라미터

n        request객체의 HTTP 헤더

n        request객체의 세션 데이터

n        request객체의 쿠키

n        request객체의 요청에 사용된 URL/URI

 

이러한 분류에 따라 메서드를 나누어 보면 다음과 같습니다.

 

request객체의 요청 파라미터

public String getParameter(String name) : 주어진 이름의 매개변수가 갖는 값을 얻습니다. 지정된 이름의 파라미터가 존재하지 않을 경우 null을 반환합니다.

public Enumeration getParameterNames(): 매개변수들의 이름에 대한 Enumeration으로 반환합니다.

public String[] getParameterValues(String name) : 주어진 이름으로 전달된 매개변수가 갖는 모든 값을 문자열 배열로 얻습니다. 매개변수가 다중 선택이 가능한 리스트(list) 또는 선택박스(choicebox)의 값이라면, 여러 개의 값이 하나의 이름으로 전달될 수 있지만 매개변수가 하나의 값을 갖는 경우라면 getParameter(String name)를 사용하는 것이 낫습니다.

 

 

request객체의 HTTP 헤더

public String getHeader(String headerName) : HTTP 요청헤더에 지정된 headerName의 값을 문자열로 반환합니다. 만약 HTTP 요청헤더에 headerName의 값이 존재하지 않는다면 null을 반환합니다.

public Enumeration getHeaderNames() : HTTP 요청헤더에 포함된 모든 헤더의 이름을 Enumeration으로 반환합니다.

public Enumeration getHeaders (String headerName) : HTTP 요청헤더에 포함된 headerName의 모든 값을 Enumeration으로 반환합니다.

public int getIntHeader (String headerName) : HTTP 요청헤더에 포함된 headerName의 값을 int로 반환합니다. 지정된 headerName의 값을 int로 변환 할 수 없는 경우 NumberFormatException이 발생하고 headerName 헤더가 HTTP 요청헤더에 존재하지 않을 경우에는 –1을 반환합니다.

public long getIDateHeader (String headerName) : HTTP 요청헤더에 포함된 headerName의 값을 millisecond 변환하여 long으로 반환합니다. 지정된 headerName의 값을 int로 변환 할 수 없는 경우 IllegalArgumentException이 발생하고 headerName 헤더가 HTTP 요청헤더에 존재하지 않을 경우에는 –1을 반환합니다.

 

request객체의 세션 데이터 

public HttpSession getSession() : 요청을 시도한 클라이언트에 지정된 HttpSession 객체를 얻습니다.  이전에 생성된 HttpSession 객체가 없었다면 새로운 세션 객체를 생성합니다. 

public HttpSession getSession(boolean create) : 요청을 시도한 클라이언트에 지정된 HttpSession 객체를 얻습니다. create가 false로 지정된 경우 해당 클라이언트에 대해 생성된 HttpSession 객체가 없는 경우 null을 반환합니다. create가 treu로 지정된 경우 이미 생성된 HttpSession 객체를 반환하고 만약 해당 클라이언트에 생성된 HttpSession 객체가 없는 경우 새로운 세션 객체를 생성하여 리턴합니다.

public String getRequestedSessionId(): 요청을 시도한 클라이언트의 세션 id를 문자열로 반환합니다.

public String isRequestedSessionId() : 요청을 시도한 클라이언트의 세션 id가 유효하면 true 아니면 false를 리턴합니다.

isRequestedSessionIdFromCookie() : 요청을 시도한 클라이언트의 세션 id가 쿠키로 전달된 경우 true 아니면 false를 리턴합니다.

isRequestedSessionIdFromURL() : 요청을 시도한 클라이언트의 세션 id가 URL에 포함된 경우 true 아니면 false를 리턴합니다.

 

request객체의 쿠키 

public Cookie[] getCookies() : 클라이언트의 요청에 포함된 쿠키를 Cookie배열로 리턴합니다.

 

request객체의 요청에 사용된 URL/URI 

public String getRequestURI() : 요청에 사용된 URL로부터 URI부분을 문자열로 리턴합니다.  

public String getQueryString():요청에 사용된 쿼리 문자열을 문자열로 리턴합니다..

public String getMethod() : 요청에 사용된 요청방식을 문자열로 리턴합니다.




개발자들이 직접 작성한 오픈소스 면접 질문들을 모아놓은 github 프로젝트 



#어썸인터뷰

https://github.com/MaximAbramchuck/awesome-interviews

 

#어썸인터뷰 자바개발자

https://github.com/MaximAbramchuck/awesome-interviews#java





Spring Web MVC offers seamless integration with different view technologies, including Excel document view. When configured properly, a Spring’s view resolver can generate an Excel document from model data and send it to the client for downloading or opening by a spreadsheet program like Microsoft Excel. For working with Excel view, Spring supports two popular libraries such as Apache POI and JExcelApi (Both are free and open source). This tutorial is going to help you in understanding how to configure Spring MVC to work with these libraries in order to deliver dynamic content in form of Excel document to the users, by developing a sample Spring MVC application that allows the users to download an Excel document generated on the fly:

Spring MVC Excel View Demo with Apache POI

Clicking on the download link will prompt the users for downloading/opening the document which looks like the following screenshot in Microsoft Excel program:

Open downloaded Excel document in MS Excel

About Apache POI

Apache POI is a set of pure Java libraries for reading and writing Microsoft Office documents such as Word, Excel, Powerpoint, Outlook, etc. Click the following link to download its latest distribution (which is Apache POI 3.9, as of this writing):

Apache POI Download

The distribution comes with several jar files, but the only the poi-VERSION.jar file is required for typical usage of generating Excel documents (if you want to generate Excel XML format such as *.xlsx files, use the poi-ooxml-VERSION.jarfile).

To generate an Excel document using Apache POI within Spring, we need to create a view class that extends from theAbstractExcelView class and override its method buildExcelDocument(). Then using Apache POI’s Excel API to generate the excel document.

About JExcelApi

JExcelApi is a Java library that is dedicated for reading, writing and modifying Excel spreadsheets. It supports Excel 2003 file format and older versions. You can download JExcelApi from the following link:

               JExcelApi DownloadTo work with JExcelApi, you need to add its only jar file: jxl.jar - to your project’s classpath. And Spring provides an abstract class called AbstractJExcelView which should be extended to generate an Excel document using JExcelApi, similarly to the case of Apache POI.

This tutorial will use Apache POI for the sample application. However, you can also download a JExcelApi version of the project in the Attachments section.

In Eclipse IDE, create a Dynamic Web Project called SpringMvcExcelViewDemo. We will end up with the following project structure:

Spring MVC Excel View Demo Eclipse project structure

The jar files used are:

      • spring-beans-3.2.3.RELEASE.jar
      • spring-context-3.2.3.RELEASE.jar
      • spring-context-support-3.2.3.RELEASE.jar
      • spring-core-3.2.3.RELEASE.jar
      • spring-expression-3.2.3.RELEASE.jar
      • spring-web-3.2.3.RELEASE.jar
      • spring-webmvc-3.2.3.RELEASE.jar
      • commons-logging-1.1.1.jar
    • Apache POI:
      • poi-3.9-20121203.jar
 

This book: Getting started with Spring Framework  helps you master all major concepts like Spring core modules, dependency injection, Spring AOP, annotation-driven development, and more.

 

1. Creating Model Class

We will generate an Excel document that contains a list of Java books, so create the following model class (Book.java):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package net.codejava.spring;
 
public class Book {
    private String title;
    private String author;
    private String isbn;
    private String publishedDate;
    private float price;
 
    public Book(String title, String author, String isbn, String publishedDate,
            float price) {
        this.title = title;
        this.author = author;
        this.isbn = isbn;
        this.publishedDate = publishedDate;
        this.price = price;
    }
 
    // getters and setters
 
}


2. Coding Entry JSP Page

We need to create a JSP page that displays a hyperlink on which the users will click to download the Excel file. Create a folder called jsp inside WEB-INF directory and create a JSP file called home.jsp under WEB-INF\jsp with the following content:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Spring MVC Excel View Demo (Apache POI)</title>
</head>
<body>
    <div align="center">
        <h1>Spring MVC Excel View Demo (Apache POI)</h1>
        <h3><a href="/downloadExcel">Download Excel Document</a></h3>
    </div>
</body>
</html>
The hyperlink Download Excel Document points to a relative URL downloadExcel which will be handled by a Spring controller class as described below.



3. Coding Spring Controller

Create a Spring controller class called MainController with the following code:

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
package net.codejava.spring;
 
import java.util.ArrayList;
import java.util.List;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
 
/**
 * A Spring controller that allows the users to download an Excel document
 * generated by the Apache POI library.
 *
 * @author www.codejava.net
 *
 */
@Controller
public class MainController {
 
    /**
     * Handle request to the default page
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String viewHome() {
        return "home";
    }
 
    /**
     * Handle request to download an Excel document
     */
    @RequestMapping(value = "/downloadExcel", method = RequestMethod.GET)
    public ModelAndView downloadExcel() {
        // create some sample data
        List<Book> listBooks = new ArrayList<Book>();
        listBooks.add(new Book("Effective Java""Joshua Bloch""0321356683",
                "May 28, 2008"38.11F));
        listBooks.add(new Book("Head First Java""Kathy Sierra & Bert Bates",
                "0596009208""February 9, 2005"30.80F));
        listBooks.add(new Book("Java Generics and Collections",
                "Philip Wadler""0596527756""Oct 24, 2006"29.52F));
        listBooks.add(new Book("Thinking in Java""Bruce Eckel""0596527756",
                "February 20, 2006"43.97F));
        listBooks.add(new Book("Spring in Action""Craig Walls""1935182358",
                "June 29, 2011"31.98F));
 
        // return a view which will be resolved by an excel view resolver
        return new ModelAndView("excelView""listBooks", listBooks);
    }
}
As we can see, this controller class implements two request handling methods:

    • viewHome(): this method simply returns a logical view name “home” which will be resolved to the home.jsp page (We will configure view resolver for JSP later).
    • downloadExcel(): this method creates some dummy data, e.g. creating some books and add them to a list. Finally this method returns a logical view name “excelView” and passes the list of books as the name “listBooks” to the model. We will configure an Excel view class for this view later.  

This book: Spring in Action  helps you learn the latest features, tools, and practices including Spring MVC, REST, Security, Web Flow, and more.


4. Coding Excel View Class

To generate an Excel document from the model data passed by the controller, create a subclass of the AbstractExcelViewclass as follows:

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
package net.codejava.spring;
 
import java.util.List;
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.springframework.web.servlet.view.document.AbstractExcelView;
 
/**
 * This class builds an Excel spreadsheet document using Apache POI library.
 * @author www.codejava.net
 *
 */
public class ExcelBuilder extends AbstractExcelView {
 
    @Override
    protected void buildExcelDocument(Map<String, Object> model,
            HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        // get data model which is passed by the Spring container
        List<Book> listBooks = (List<Book>) model.get("listBooks");
         
        // create a new Excel sheet
        HSSFSheet sheet = workbook.createSheet("Java Books");
        sheet.setDefaultColumnWidth(30);
         
        // create style for header cells
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontName("Arial");
        style.setFillForegroundColor(HSSFColor.BLUE.index);
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        font.setColor(HSSFColor.WHITE.index);
        style.setFont(font);
         
        // create header row
        HSSFRow header = sheet.createRow(0);
         
        header.createCell(0).setCellValue("Book Title");
        header.getCell(0).setCellStyle(style);
         
        header.createCell(1).setCellValue("Author");
        header.getCell(1).setCellStyle(style);
         
        header.createCell(2).setCellValue("ISBN");
        header.getCell(2).setCellStyle(style);
         
        header.createCell(3).setCellValue("Published Date");
        header.getCell(3).setCellStyle(style);
         
        header.createCell(4).setCellValue("Price");
        header.getCell(4).setCellStyle(style);
         
        // create data rows
        int rowCount = 1;
         
        for (Book aBook : listBooks) {
            HSSFRow aRow = sheet.createRow(rowCount++);
            aRow.createCell(0).setCellValue(aBook.getTitle());
            aRow.createCell(1).setCellValue(aBook.getAuthor());
            aRow.createCell(2).setCellValue(aBook.getIsbn());
            aRow.createCell(3).setCellValue(aBook.getPublishedDate());
            aRow.createCell(4).setCellValue(aBook.getPrice());
        }
    }
 
}
 

For working with JExcelApi, make the class extends the AbstractJExcelView class like this:

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
package net.codejava.spring;
 
import java.util.List;
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
 
import org.springframework.web.servlet.view.document.AbstractJExcelView;
 
/**
 * This class builds an Excel spreadsheet document using JExcelApi library.
 * @author www.codejava.net
 *
 */
public class ExcelBuilder extends AbstractJExcelView {
 
    @Override
    protected void buildExcelDocument(Map<String, Object> model,
            WritableWorkbook workbook, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
         
        // get data model which is passed by the Spring container
        List<Book> listBooks = (List<Book>) model.get("listBooks");
         
        // create a new Excel sheet
        WritableSheet sheet = workbook.createSheet("Java Books"0);
         
        // create header row
        sheet.addCell(new Label(00"Book Title"));
        sheet.addCell(new Label(10"Author"));
        sheet.addCell(new Label(20"ISBN"));
        sheet.addCell(new Label(30"Published Date"));
        sheet.addCell(new Label(40"Price"));
         
        // create data rows
        int rowCount = 1;
         
        for (Book aBook : listBooks) {
            sheet.addCell(new Label(0, rowCount, aBook.getTitle()));
            sheet.addCell(new Label(1, rowCount, aBook.getAuthor()));
            sheet.addCell(new Label(2, rowCount, aBook.getIsbn()));
            sheet.addCell(new Label(3, rowCount, aBook.getPublishedDate()));
            sheet.addCell(new jxl.write.Number(4, rowCount, aBook.getPrice()));
             
            rowCount++;
        }
    }
}
The above code is self-explanatory. As you can see, there are some differences between the Apache POI API and the JExcelApi.

 

See more: How to Write Excel Files in Java using Apache POI

 

This book: Spring Integration in Action help you learn more about enterprise integration and messaging using the Spring Integration framework.


5. Configuring Excel View Class

Next, we need to tell Spring to use the above ExcelBuilder class as view class for the view name “excelView” returned from the controller’s downloadExcel() method. There are two ways to do this by creating either a .properties file or an XML file.

Using views.properties file:

Create a .properties file called views.properties under the project’s classpath (which is under src directory in the Eclipse project), with the following line:

1
excelView.(class)=net.codejava.spring.ExcelBuilder
That tells the Spring’s view resolver to use the net.codejava.spring.ExcelBuilder class to process output for the view name “excelView”.

 

Using views.xml file:

An alternative to the views.properties file is to use XML version. Create views.xml file under WEB-INF directory with the following content:

1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
     
    <bean id="excelView" class="net.codejava.spring.ExcelBuilder" />
     
</beans>
Note that the bean’s ID attribute must correspond to the view name “excelView”.

 


6. Writing Spring Configuration File

Create a Spring configuration file named spring-mvc.xml under WEB-INF directory. In case you are usingviews.properties file, put the following content:

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:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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">
 
    <context:component-scan base-package="net.codejava.spring" />
 
   <bean id="viewResolver1" class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
        <property name="order" value="1"/>
        <property name="basename" value="views"/>
    </bean>
     
    <bean id="viewResolver2"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="order" value="2"/>
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
     
</beans>
As seen in the above configuration, there are two view resolvers used here:

    • ResourceBundleViewResolver: to resolve view names specified in the views.properties file.
    • InternalResourceViewResolver: to resolve view names to JSP pages.
The order property does matter here, in which the first resolver has higher priority than the second one.

 

In case the views.xml is used, configure Spring as follows:

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
<?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: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">
 
    <context:component-scan base-package="net.codejava.spring" />
 
   <bean id="viewResolver1" class="org.springframework.web.servlet.view.XmlViewResolver">
        <property name="order" value="1"/>
        <property name="location" value="/WEB-INF/views.xml"/>
    </bean>
     
    <bean id="viewResolver2"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="order" value="2"/>
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
 
     
</beans>
 

Discover how to write efficient batch applications with Spring Batch in Action


7. Configuring Spring MVC in web.xml

The final step is to configure Spring MVC in the web deployment descriptor file as follows:

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
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
     
    <display-name>SpringMvcExcelViewDemo</display-name>
     
    <servlet>
        <servlet-name>SpringController</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
 
    <servlet-mapping>
        <servlet-name>SpringController</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping
</web-app>


8. Testing the application

Type the following URL into browser to access the application we’ve built:

http://localhost:8080/SpringMvcExcelViewDemo/

The default page (home.jsp) gets displayed (in FireFox):

Test Spring MVC Excel View Demo in Firefox

Click on the “Download Excel Document” link, the browser will ask for opening or saving the file:

Opening downloadExcel dialog

Select Open with (Microsoft Office Excel), the document gets opened in Excel as follows:

Open downloaded Excel document in MS Excel

 

Download Eclipse project for this application in the Attachments section below





출처 : http://www.codejava.net/frameworks/spring/spring-mvc-with-excel-view-example-apache-poi-and-jexcelapi


Maven 으로 프로젝트 설정시에는 의존관계 라이브러리 (*.jar) 파일을 다운로드 받아 WEB-INF/lib 에 따로 설정할 필요가 없이 pom.xml 에 해당 의존관계 라이브러리에 대한 의존관계를 기술해 주면 자동을 관련 라이브러리를 다운로드 받아 프로젝트에서 사용할 수 있게 합니다.

properties 정의

properties Element 는 pom.xml 에서 사용하는 속성을 선언해 줄 수 있습니다. 해당 의존관계 라이브러리의 버전을 일괄적으로 적용하거나 내부 속성등을 설정하는 용도로 사용하시면 됩니다.
properties 에 정의된 속성을 사용할 경우에는 ${속성명} 과 같이 사용하시면 됩니다.
예를 들어 아래의 properties 하위에 정의된 org.springframework.version 속성을 사용하실 경우에는 ${org.springframework.version} 으로 하시면 해당 속성값을 “3.1.1.RELEASE” 로 적용하여 줍니다.

dependencies 정의

dependencies 는 프로젝트에서 사용할 의존관계 라이브러리들을 정의하는 Element 입니다. 아래의 설정을 복사하여 pom.xml 에 붙여 넣습니다.

Plugin 설정

현재 M2Eclipse 버전에서 생성된 Maven 프로젝트는 기본적으로 JDK v1.5 로 설정이 되어있으며, 해당 버전을 JDK v1.6 으로 변경한 후 WTP (Web Tools Platform) 지원을 하기위하여 plugins 항목에 아래와 같이 설정을 합니다.

전체 pom.xml 소스

pom.xml 설정 적용

pom.xml 파일을 저장하신 후 프로젝트 명에서 마우스 오른쪽 버튼을 클릭한 후 Maven > Update Project Configuration (1) 을 클릭하여 M2Eclipse 의 Maven 프로젝트 설정을 업데이트 합니다.

Maven 프로젝트 설정이 정상적으로 적용이 되면 아래의 그림과 같이 JDK 버전이 JavaSE-1.6 으로 변경이 됩니다.


출처 : http://blog.beany.co.kr/archives/1068

'Server Enterprise > Gradle & Maven' 카테고리의 다른 글

[Gradle] cache 삭제  (0) 2021.08.12
[maven] 외부 jar 추가  (0) 2016.10.26
[Maven] M2Eclipse project 생성 2  (0) 2015.08.26
[Maven] M2Eclipse project 생성 1  (0) 2015.08.26
[MAVEN] 설치 및 이클립스 연동  (0) 2015.08.17

maven-archetype-webapp 를 이용하여 Maven WebApp 을 생성했을 시에는 아래와 같이 maven 프로젝트의 webapp 디렉토리가 프로젝트 > src > main > webapp (1) 와 같이 위치하게 됩니다.

Web 프로젝트 작업시 webapp 디렉토리가 깊어질 경우 jsp 파일을 열기 위하여 약간의 손(?) 이 가게 되므로 해당 폴더를 프로젝트 바로 하위로 위치를 시키도록 합니다.

먼저 프로젝트 하위의 pom.xml 을 열어 <build> 요소 하위에 아래와 같이 Maven Plugin 을 설정합니다. warSourceDirectory 설정 항목에 원하시는 디렉토리 경로 및 디렉토리명을 설정 해주시면 됩니다. 현재는 webapp 로 지정을 하였습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<build>
    <finalName>sample-spring-webapp</finalName>
 
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.2</version>
            <configuration>
                <warSourceDirectory>webapp</warSourceDirectory>
            </configuration>
        </plugin>
    </plugins>
 
</build>

pom.xml 파일을 저장하신 후 프로젝트 명에서 마우스 오른쪽 버튼을 클릭한 후 Maven > Update Project Configuration (1) 을 클릭하여 M2Eclipse 의 Maven 프로젝트 설정을 업데이트 합니다.

Maven Project 가 정상적으로 업데이트가 되면 maven-war-plugin 의 warSourceDirectory 속성에서 설정한 디렉토리가 아래와 같이 같이 프로젝트 하위에 webapp (1) 폴더가 생성되게 됩니다.

기존의 webapp 디렉토리 (프로젝트 > src > main > webapp) 하위의 META-INF, WEB-INF, index.jsp 파일을 새로 생성된 프로젝트 > webapp 디렉토리 하위로 복사 시킨 후 (1) 기존의 webapp 디렉토리  (프로젝트 > src > main > webapp) 를 삭제 (2) 하여 최종적으로 아래의 그림과 같이 디렉토리를 구성합니다.


출처 : http://blog.beany.co.kr/archives/1044

M2Eclipse 의 상단 메뉴에서 File -> New -> Other 를 선택하거나 Ctrl + N 단축키를 통하여 프로젝트 생성 팝업을 띄웁니다.

아래와 같이 New 팝업이 나타나면 Maven -> Maven Project (1) 를 선택한 후 [Next >] 버튼 (2) 을 클릭하여 다음 설정 화면으로 이동합니다.

Maven Project 선택

Maven Project 가 저장될 위치를 확인한 후 [Next >] (1) 버튼을 클릭하여 다음 설정 화면으로 이동합니다.

Maven Project 에서 기본 으로 사용할 프로젝트 템플릿 (Archetype) 을 선택합니다. Spring WebApp 를 세팅하기 위해서는 maven-archetype-webapp (1) 을 선택한 후 [Next >] 버튼 (2) 을 클릭하여 다음 설정 화면으로 이동합니다.

프로젝트의 기본 정보를 입력하는 화면이며, 각 입력 항목 (1) 은 다음과 같습니다.

  • Group Id : 프로젝트 그룹의 식별 문자열을 입력합니다.
  • Artifact Id : Group Id 에 따른 하위 프로젝트를 구분하기 위한 ID 값을 입력합니다.
  • Version : Artifact 의 버전을 입력합니다.
  • Package : 프로젝트 생성시 기본으로 생성되는 패키지 명을 입력합니다. 빈 문자열을 넣어도 무방합니다.

기본 정보를 입력이 완료되면 [Finish] 버튼 (2) 을 클릭하여 Maven Project 을 생성을 완료합니다.

프로젝트가 정상적으로 생성이 되면 Package Explorer 에 아래의 화면과 같이 프로젝트 디렉토리가 구성이 됩니다.

maven-archetype-webapp 을 Maven 기본 템플릿으로 선택한 후 프로젝트 생성시에는 java 관련 src 폴더가 존재하지 않아, Package Explorer 에서도 Java Source 폴더가 보이지 않습니다. 프로젝트 > src > main 폴더 하위에 아래와 같이 java 폴더 (1) 를  생성하여 줍니다.

Java 폴더 생성 후 M2Eclipse 에서는 java 폴더를 Source 폴더로 인식하지 못하기 때문에 프로젝트 명에서 마우스 오른쪽 버튼을 클릭한 후 Maven > Update Project Configuration (1) 을 클릭하여 M2Eclipse 의 Maven 프로젝트 설정을 업데이트 합니다.

Maven 프로젝트 업데이트가 정상처리 되면 아래와 같이 java Source 폴더 (1) 로 인식되게 됩니다.

M2Eclipse 에서의 Maven Web Project 의 기본 생성이 완료되었습니다. 다음에는 Maven Layout 변경에 대한 설정을 합니다.


출처 : http://blog.beany.co.kr/archives/1030

MAVEN

MAVEN 설치 및 Eclipse 연동하기

MAVEN에 대해 알아보기에 앞서 먼저 설치하고 사용하는 방법을 알아보자.



MAVEN 설치

설치에 앞서 MAVEN을 다운로드 해주자. 다음 경로로 가서 받으면 된다.



메이븐 최신 버전을 받아주자. bin.tar.gz 또는 bin.zip 파일을 받아주면 된다.



메이븐은 설치를 위한 install 파일이 없기 때문에 사용할 경로에 압축을 풀어주면 바로 사용할 수 있다.



압축을 풀면 다음과 같은 폴더가 생성된다.


이제 환경변수 설정을 해주자. 



windows 탐색기나 'Win + E' 키를 이용하여 내 컴퓨터를 열어준 다음 좌측 내비게이터에서 '컴퓨터'의 속성을 클릭한다.



그러면 위와 같이 시스템 창이 나타나는데 좌측 탭에서 '고급 시스템 설정'을 클릭하고 '시스템 속성'에서 '환경 변수'를 클릭한다.

그 다음 메이븐 환경변수를 새로 만들어 주자.

'시스템 변수' 부분에서 새로 만들기를 클릭하고 다음과 같이 변수를 만들어주자.


변수이름 : MAVEN_HOME

변수 값 : MAVEN 폴더의 경로


메이븐 환경 변수를 만들었으면 Path에 메이븐 bin 폴더까지의 경로를 추가해주자.

시스템 변수 Path 항목의 맨 끝에 %MAVEN_HOME%\bin; 을 추가해주면 된다.



만약 자바 설치가 안되어 JAVA_HOME 환경 변수가 등록되어 있지 않다면 추가해주어야 한다. 등록 형식은 MAVEN_HOME 변수를 등록할 때의 형식과 동일하다. JDK를 다운로드 받아 환경변수로 등록해주면 된다.


* JDK 다운로드 경로


JAVA_HOME 은 다음과 같이 설정해주면 된다.



설정이 다 되었으면 메이븐이 잘 설치되었는지 확인해보자.

cmd 창에서 'mvn -version' 명령어를 쳐서 다음과 같이 출력되면 정상적으로 설치된 것이다.




Eclipse에 MAVEN 연동하기

이제 설치한 메이븐을 Eclipse에 연동해보자.


이클립스에서 메이븐을 사용하려면 메이븐 플러그인을 설치해주면 된다. 


Juno버전 이상의 이클립스부터 연동이 가능하다. 아래의 경로에서 해당 이클립스를 다운로드 받아주자.


다운로드가 완료되면 압축을 풀고 이클립스를 실행해주자.


메이븐 플러그인을 설치하여 이클립스에서 메이븐을 사용하기 위해선, M2E 라는 Maven Intergration을 설치해주면 된다. 


상단 메뉴에서 Help 의 Install New Software 를 클릭해보자.



아래와 같은 창이 나오는데 Work With에 M2E 를 업데이트 받을 사이트를 써주고 Add 를 눌러주면 된다.



M2E 업데이트 url은 수시로 변하는데 다음 주소에서 확인해주면 된다.


* M2E 업데이트 URL 확인 경로


Update Sites의 Latest m2e release (recommended) 에 적힌 주소를 사용하면 된다.



Add 버튼을 클릭 후 다음과 같이 M2E 업데이트 주소를 추가해주자.



주소 추가 후 다음과 같이 Maven Intergration for Eclipse가 나타나는데 체크 후 설치를 진행해주자.



Software 사용 동의 창이 나타나면 사용 동의에 체크 후 Finish를 클릭한다.



다음과 같이 설치가 진행되고 마무리된다. (설치 완료 후 이클립스를 재시작 해주자)



이클립스를 재시작했으면 M2E 의 repository를 설정해주자.


메이븐의 라이브러리 파일들을 받으면 메이븐 설치시 설정된 USER_HOME\.m2\repository 경로에 저장 되는데 이것을 수정하는 작업이다.


메이븐 디렉터리에 가보면 conf 디렉터리가 있는데 여기에 settings.xml 파일이 있다. 읽다보면 다음과 같이 localRepository 항목이 있는데 이 부분의 주석을 지우고 <localRepository> 태그 안의 경로를 수정해주면 된다.



수정 후 이클립스 메뉴의 Window > Preferences 로 들어가면 아래와 같은 창이 나타나는데 Maven 메뉴의 Installations 로 들어가보자.



Add 버튼을 눌러 메이븐의 경로를 추가하면 아래의 Global setting from installation directory 에 settings.xml 까지의 경로가 추가된다. 설정 적용을 위해 Apply 를 누르고 OK 를 눌러준다.


이클립스를 재시작한 후 이전과 같은 Window > Preferences 창에서 Maven 메뉴의 User Settings 로 들어가보자.



여기서도 User Settings 부분을 settings.xml 파일이 있는 경로로 수정해준다.

아래의 Local Repository 부분을 보면 수정된 경로가 나타난 것을 확인할 수 있다.


마지막으로 메이븐이 잘 동작하는지 테스트를 위해 현재 진행 중인 프로젝트 하나를 import 하고, 서버를 하나 만들었다. (서버는 Apache-Tomcat v6.0 을 사용하였다)


그 다음 상단 메뉴의 Project 탭에서 Build Automatically 의 체크를 해제해준다. 이클립스는 파일 수정 후 저장시 자동으로 컴파일을 하는데 MAVEN을 사용하여 유동적인 빌드를 하기위해 해제해주는 것이다. 


또한, 깔끔한 빌드를 위해 빌드 하기 전에 같은 Project 탭에 있는 Clean 을 해주는 것도 좋은 방법이다. Clean 동작은 이클립스 내의 캐시 정보나 컴파일된 .classes 파일을 정리해주는 역할을 수행한다.



이제 사용할 프로젝트를 빌드해보자.



해당 프로젝트를 마우스 우클릭하면 Run As 메뉴를 찾을 수 있다. 여기서 Maven build를 클릭하면 메이븐 빌드가 시작된다. 

Maven 메뉴도 보이는데 정상적으로 설치됬을 경우 보여지는 메뉴이다.



Edit Configuration 창이 나타나는데 Run 버튼을 클릭해주자.



콘솔 창에서 빌드가 진행되는데 마지막에 BUILD SUCCESS 라고 나타나면 빌드가 성공된 것이다. 

그 다음 서버를 실행해 주면 브라우저에서 해당 프로젝트가 정상 작동되는 모습을 확인할 수 있다.





출처 : http://freestrokes.tistory.com/


+ Recent posts