SpringMVC(JDBC 사용)

Spring 2016. 5. 19. 20:40


Spring JDBC

=> JDBC 를 이용하여 반복코드를 줄이고(드라이버로드, 커넥션 생성 및 DB 연결, 

SQL 실행, 자원해제 등), Spring 빈을 이용하여 코드를 간소화 할 수 있다.


JDBC 를 이용한 리스트 목록 생성과 DB 연동


환경설정)

 servlet-context.xml   에 추가

1
2
3
4
5
6
7
8
9
10
11
12
13
<beans:bean name="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <beans:property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></beans:property>
        <beans:property name="url"
            value="jdbc:oracle:thin:@localhost:1521:XE"></beans:property>
        <beans:property name="username" value="hr"></beans:property>
        <beans:property name="password" value="orcl"></beans:property>
    </beans:bean>
 
    <beans:bean name="template"
        class="org.springframework.jdbc.core.JdbcTemplate">
        <beans:property name="dataSource" ref="dataSource"></beans:property>
    </beans:bean>
cs

오라클 데이터 베이스와 연동(ID : hr / PW : orcl)


 pom.xml  에 추가

1
2
3
4
5
6
7
8
9
10
11
12
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.2.0.3</version>
        </dependency>
        
        
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>
cs

위는 JDBC 아래는 JDBC Template 설정 부분


 BController.java  에 추가

1
2
3
4
5
@Autowired
    public void setTemplate(JdbcTemplate template) {
        this.template = template;
        com.java.spring_mvc_board.util.Constant.template = this.template;
    }
cs

의존관계를 자동으로 설정(Template 해당 빈을 생성 후 값을 전달)


 Constant.java  생성 

1
2
3
4
5
6
7
8
package com.java.spring_mvc_board.util;
 
import org.springframework.jdbc.core.JdbcTemplate;
 
public class Constant {
 
    public static JdbcTemplate template;
}
cs


 ojdbc-11.2.0.3.jar  파일을 해당 경로에 추가


파일구조



게시판 Dao 코드의 간소화

 BDao.java 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class BDao {
 
    DataSource dataSource;
    
    public BDao() {
        // TODO Auto-generated constructor stub
        
        try {
            Context context = new InitialContext();
            dataSource = (DataSource) context.lookup("java:comp/env/jdbc/Oracle11g");
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
cs


 BDao.java 

1
2
3
4
5
6
7
8
9
10
public class BDao {
 
    DataSource dataSource;
    
    JdbcTemplate template = null;
    
    public BDao() {
        // TODO Auto-generated constructor stub
        template = Constant.template;
    }
cs


list

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
    public ArrayList<BDto> list() {
        
        ArrayList<BDto> dtos = new ArrayList<BDto>();
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        
        try {
            connection = dataSource.getConnection();
            
            String query = "select bId, bName, bTitle, bContent, bDate, bHit, bGroup, bStep, bIndent from mvc_board order by bGroup desc, bStep asc";
            preparedStatement = connection.prepareStatement(query);
            resultSet = preparedStatement.executeQuery();
            
            while (resultSet.next()) {
                int bId = resultSet.getInt("bId");
                String bName = resultSet.getString("bName");
                String bTitle = resultSet.getString("bTitle");
                String bContent = resultSet.getString("bContent");
                Timestamp bDate = resultSet.getTimestamp("bDate");
                int bHit = resultSet.getInt("bHit");
                int bGroup = resultSet.getInt("bGroup");
                int bStep = resultSet.getInt("bStep");
                int bIndent = resultSet.getInt("bIndent");
                
                BDto dto = new BDto(bId, bName, bTitle, bContent, bDate, bHit, bGroup, bStep, bIndent);
                dtos.add(dto);
            }
            
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {
            try {
                if(resultSet != null) resultSet.close();
                if(preparedStatement != null) preparedStatement.close();
                if(connection != null) connection.close();
            } catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }
        return dtos;
    }
cs

list

1
2
3
4
5
6
public ArrayList<BDto> list() {
        if(template != null)
            System.out.println("list");
        String query = "select bId, bName, bTitle, bContent, bDate, bHit, bGroup, bStep, bIndent from mvc_board order by bGroup desc, bStep asc";
        return (ArrayList<BDto>)template.query(query, new BeanPropertyRowMapper<BDto>(BDto.class));
    }
cs



write

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
    public void write(String bName, String bTitle, String bContent) {
        // TODO Auto-generated method stub
        
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        
        try {
            connection = dataSource.getConnection();
            String query = "insert into mvc_board (bId, bName, bTitle, bContent, bHit, bGroup, bStep, bIndent) values (mvc_board_seq.nextval, ?, ?, ?, 0, mvc_board_seq.currval, 0, 0 )";
            preparedStatement = connection.prepareStatement(query);
            preparedStatement.setString(1, bName);
            preparedStatement.setString(2, bTitle);
            preparedStatement.setString(3, bContent);
            int rn = preparedStatement.executeUpdate();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {
            try {
                if(preparedStatement != null) preparedStatement.close();
                if(connection != null) connection.close();
            } catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }
        
    }
cs


write

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public void write(final String bName, final String bTitle, final String bContent) {
        
        template.update(new PreparedStatementCreator() {
 
            @Override
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                String query = "insert into mvc_board (bId, bName, bTitle, bContent, bHit, bGroup, bStep, bIndent) values (mvc_board_seq.nextval, ?, ?, ?, 0, mvc_board_seq.currval, 0, 0 )";
                PreparedStatement ps = con.prepareStatement(query);
                ps.setString(1, bName);
                ps.setString(2, bTitle);
                ps.setString(3, bContent);
                // TODO Auto-generated method stub
                return ps;
            }
        });
    }
cs




contentView

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
public BDto contentView(String strID) {
        // TODO Auto-generated method stub
        
        upHit(strID);
        
        BDto dto = null;
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        
        try {
            
            connection = dataSource.getConnection();
            
            String query = "select * from mvc_board where bId = ?";
            preparedStatement = connection.prepareStatement(query);
            preparedStatement.setInt(1, Integer.parseInt(strID));
            resultSet = preparedStatement.executeQuery();
            
            if(resultSet.next()) {
                int bId = resultSet.getInt("bId");
                String bName = resultSet.getString("bName");
                String bTitle = resultSet.getString("bTitle");
                String bContent = resultSet.getString("bContent");
                Timestamp bDate = resultSet.getTimestamp("bDate");
                int bHit = resultSet.getInt("bHit");
                int bGroup = resultSet.getInt("bGroup");
                int bStep = resultSet.getInt("bStep");
                int bIndent = resultSet.getInt("bIndent");
                
                dto = new BDto(bId, bName, bTitle, bContent, bDate, bHit, bGroup, bStep, bIndent);
            }
            
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {
            try {
                if(resultSet != null) resultSet.close();
                if(preparedStatement != null) preparedStatement.close();
                if(connection != null) connection.close();
            } catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }
        return dto;
    }
cs



contentView

1
2
3
4
5
public BDto contentView(String bId) {
        String query = "select * from mvc_board where bId =" + bId;
        upHit(bId);
        return template.queryForObject(query, new BeanPropertyRowMapper<BDto>(BDto.class));
    }
cs



modify

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
public void modify(String bId, String bName, String bTitle, String bContent) {
        // TODO Auto-generated method stub
        
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        
        try {
            connection = dataSource.getConnection();
            
            String query = "update mvc_board set bName = ?, bTitle = ?, bContent = ? where bId = ?";
            preparedStatement = connection.prepareStatement(query);
            preparedStatement.setString(1, bName);
            preparedStatement.setString(2, bTitle);
            preparedStatement.setString(3, bContent);
            preparedStatement.setInt(4, Integer.parseInt(bId));
            int rn = preparedStatement.executeUpdate();
            
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {
            try {
                if(preparedStatement != null) preparedStatement.close();
                if(connection != null) connection.close();
            } catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }
    }
cs


modify

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public void modify(final String bId, final String bName, final String bTitle, final String bContent) {
        String query = "update mvc_board set bName = ?, bTitle = ?, bContent = ? where bId = ?";
        template.update(query, new PreparedStatementSetter() {
            
            @Override
            public void setValues(PreparedStatement ps) throws SQLException {
                ps.setString(1, bName);
                ps.setString(2, bTitle);
                ps.setString(3, bContent);
                ps.setInt(4, Integer.parseInt(bId));
                // TODO Auto-generated method stub
            }
        });
    }

cs




delete

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
public void delete(String bId) {
        // TODO Auto-generated method stub
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            
            connection = dataSource.getConnection();
            String query = "delete from mvc_board where bId = ?";
            preparedStatement = connection.prepareStatement(query);
            preparedStatement.setInt(1, Integer.parseInt(bId));
            int rn = preparedStatement.executeUpdate();
            
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {
            try {
                if(preparedStatement != null) preparedStatement.close();
                if(connection != null) connection.close();
            } catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }
    }
cs


delete

1
2
3
4
5
6
7
8
9
10
11
public void delete(final String bId) {
        String query = "delete from mvc_board where bId = ?";
        template.update(query, new PreparedStatementSetter() {
 
            @Override
            public void setValues(PreparedStatement ps) throws SQLException {
                // TODO Auto-generated method stub
                ps.setInt(1, Integer.parseInt(bId));
            }
        });
    }
cs



reply_view

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
public BDto reply_view(String str) {
        // TODO Auto-generated method stub
        BDto dto = null;
        
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            
            connection = dataSource.getConnection();
            String query = "select * from mvc_board where bId = ?";
            preparedStatement = connection.prepareStatement(query);
            preparedStatement.setInt(1, Integer.parseInt(str));
            resultSet = preparedStatement.executeQuery();
            
            if(resultSet.next()) {
                int bId = resultSet.getInt("bId");
                String bName = resultSet.getString("bName");
                String bTitle = resultSet.getString("bTitle");
                String bContent = resultSet.getString("bContent");
                Timestamp bDate = resultSet.getTimestamp("bDate");
                int bHit = resultSet.getInt("bHit");
                int bGroup = resultSet.getInt("bGroup");
                int bStep = resultSet.getInt("bStep");
                int bIndent = resultSet.getInt("bIndent");
                
                dto = new BDto(bId, bName, bTitle, bContent, bDate, bHit, bGroup, bStep, bIndent);
            }
            
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {
            try {
                if(preparedStatement != null) preparedStatement.close();
                if(connection != null) connection.close();
            } catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }
        
        return dto;
    }
cs



reply_view

1
2
3
4
public BDto reply_view(String str) {
        String query = "select * from mvc_board where bId = " +str;
        return template.queryForObject(query, new BeanPropertyRowMapper<BDto>(BDto.class));
    }
cs



reply

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
public void reply(String bId, String bName, String bTitle, String bContent, String bGroup, String bStep, String bIndent) {
        // TODO Auto-generated method stub
        
        replyShape(bGroup, bStep);
        
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        
        try {
            connection = dataSource.getConnection();
            String query = "insert into mvc_board (bId, bName, bTitle, bContent, bGroup, bStep, bIndent) values (mvc_board_seq.nextval, ?, ?, ?, ?, ?, ?)";
            preparedStatement = connection.prepareStatement(query);
            
            preparedStatement.setString(1, bName);
            preparedStatement.setString(2, bTitle);
            preparedStatement.setString(3, bContent);
            preparedStatement.setInt(4, Integer.parseInt(bGroup));
            preparedStatement.setInt(5, Integer.parseInt(bStep) + 1);
            preparedStatement.setInt(6, Integer.parseInt(bIndent) + 1);
            
            int rn = preparedStatement.executeUpdate();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {
            try {
                if(preparedStatement != null) preparedStatement.close();
                if(connection != null) connection.close();
            } catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }
        
    }
cs


reply

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
    public void reply(final String bId, final String bName, final String bTitle, final String bContent, final String bGroup, final String bStep, final String bIndent) {
        
        template.update(new PreparedStatementCreator() {
 
            @Override
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                // TODO Auto-generated method stub
                replyShape(bGroup, bStep);
                String query = "insert into mvc_board (bId, bName, bTitle, bContent, bGroup, bStep, bIndent) values (mvc_board_seq.nextval, ?, ?, ?, ?, ?, ?)";
                PreparedStatement ps = con.prepareStatement(query);    
                ps.setString(1, bName);
                ps.setString(2, bTitle);
                ps.setString(3, bContent);
                ps.setInt(4, Integer.parseInt(bGroup));
                ps.setInt(5, Integer.parseInt(bStep)+1);
                ps.setInt(6, Integer.parseInt(bStep)+1);
                return ps;
            }
        });
    }
cs



replyShape

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
private void replyShape( String strGroup, String strStep) {
        // TODO Auto-generated method stub
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        
        try {
            connection = dataSource.getConnection();
            String query = "update mvc_board set bStep = bStep + 1 where bGroup = ? and bStep > ?";
            preparedStatement = connection.prepareStatement(query);
            preparedStatement.setInt(1, Integer.parseInt(strGroup));
            preparedStatement.setInt(2, Integer.parseInt(strStep));
            
            int rn = preparedStatement.executeUpdate();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {
            try {
                if(preparedStatement != null) preparedStatement.close();
                if(connection != null) connection.close();
            } catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }
    }
cs


replyShape

1
2
3
4
5
6
7
8
9
10
11
12
private void replyShape(final String strGroup, final String strStep) {
        String query = "update mvc_board set bStep = bStep + 1 where bGroup = ? and bStep > ?";
        template.update(query, new PreparedStatementSetter() {
 
            @Override
            public void setValues(PreparedStatement ps) throws SQLException {
                // TODO Auto-generated method stub
                ps.setString(1, strGroup);
                ps.setString(2, strStep);
            }
        });
    }
cs



upHit

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
private void upHit( String bId) {
        // TODO Auto-generated method stub
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        
        try {
            connection = dataSource.getConnection();
            String query = "update mvc_board set bHit = bHit + 1 where bId = ?";
            preparedStatement = connection.prepareStatement(query);
            preparedStatement.setString(1, bId);
            
            int rn = preparedStatement.executeUpdate();
                    
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {
            try {
                if(preparedStatement != null) preparedStatement.close();
                if(connection != null) connection.close();
            } catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }
    }
}
cs


upHit

1
2
3
4
5
6
7
8
9
10
11
12
private void upHit(final String bId) {
        String query = "update mvc_board set bHit = bHit + 1 where bId = ?";
        template.update(query, new PreparedStatementSetter() {
 
            @Override
            public void setValues(PreparedStatement ps) throws SQLException {
                // TODO Auto-generated method stub
                ps.setInt(1, Integer.parseInt(bId));
            }
        });
    }
 
cs


각 코드가 상당히 간소화 되었다.






'Spring' 카테고리의 다른 글

SpringMVC 게시판  (0) 2016.05.18
SpringMVC(get, post 방식으로 값 넘기기)  (0) 2016.05.17
SpringMVC  (0) 2016.05.17
AOP 구현(@Aspect 어노테이션 기반)  (0) 2016.05.13
AOP 구현(XML 스키마 기반 Advice 종류 예제)  (0) 2016.05.13
,

SpringMVC 게시판

Spring 2016. 5. 18. 21:42

SpringMVC 프레임워크로 만드는 게시판


1. SpringMVCFramework 구조와 설계 




=> 프로젝트를 생성하는 것은 이전과 같고, Board.command, Board.controller, Board.dao, Boadrd.dto 

패키지에 각각 Command, Controller, DAO, DTO 를 생성하였다. 

클라이언트의 요청과 알맞은 URL 을 Controller 에서 확인 후 그에 맞는 Command 를 수행, 

DAO, DTO 를 통해 DB 와 연동하여 로직을 실행 후에 다시 Controller 로 돌아온 값들을 가지고 

View 페이지를 보여주게 된다.


2. 데이터 베이스


bId NUMBER(4) PRIMARY KEY => 고유번호

bName VARCHAR2(20) => 작성자명

bTitle VARCHAR2(100) => 글 제목

bContent VARCHAR2(300) => 글 내용

bDate DATE DEFAULT SYSDATE => 글 작성일

bHit NUMBER(4) DEFAULT 0 => 조회수

bGroup NUMBER(4) => 그룹(원글과 답변의 묶음)번호

bStep NUMBER(4) => 답글의 번호(기본 글들은 글을 쓴 순서에 따라 정렬이 되지만 답글은 글들의 

중간에도 위치할 수 있기 때문에, 중간에 쓴 답글을 기준으로하여 게시글의 번호를 +1 씩 함)

bIndent NUMBER(4) => 들여쓰기(원글의 대한 답글인지, 답글에 대한 답글인지 여부)

create sequence mvc_board seq => sequence 는 초기값 0, 후에 1씩 증가(글들의 정렬을 위해)



*실행결과 

=> list.jsp(뷰페이지) 를 실행하였다. 

 list.jsp 

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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>Insert title here</title>
</head>
<body>
    
    <table width="500" cellpadding="0" cellspacing="0" border="1">
        <tr>
            <td>번호</td>
            <td>이름</td>
            <td>제목</td>
            <td>날짜</td>
            <td>히트</td>
        </tr>
        <c:forEach items="${list}" var="dto">
        <tr>
            <td>${dto.bId}</td>
            <td>${dto.bName}</td>
            <td>
                <c:forEach begin="1" end="${dto.bIndent}">-</c:forEach>
                <a href="content_view?bId=${dto.bId}">${dto.bTitle}</a></td>
            <td>${dto.bDate}</td>
            <td>${dto.bHit}</td>
        </tr>
        </c:forEach>
        <tr>
            <td colspan="5"> <a href="write_view">글작성</a> </td>
        </tr>
    </table>
    
</body>
</html>
cs


글작성
 을 눌렀을 때 보이는 페이지 이다.


list.jsp 의 <a href="write_view">글작성</a> 에 따라 Controller 을 거친 클라이언트의 요청에 맞게 

 write_view.jsp   를 불러오게 된다. (write_view.jsp 의 실행 모습은 위와 같음)

 BController.java    의 write_view 메핑 부분

1
2
3
4
5
6
@RequestMapping("/write_view")
    public String write_view(Model model) {
        System.out.println("write_view()");
        
        return "write_view";
    }
cs

위의 테이블에 이름과 제목 그리고 내용을 적고 '입력' 버튼을 누르게 되면 '입력' 버튼에 

<form> 태그로 연결된 write 가 불려지게 되며 이 write 는 BController.java  에 매핑된 

1
2
3
4
5
6
7
8
9
10
@RequestMapping("/write")
    public String write(HttpServletRequest request, Model model) {
        System.out.println("write()");
        
        model.addAttribute("request", request);
        command = new BWriteCommand();
        command.execute(model);
        
        return "redirect:list";
    }
cs

에 따라 BWriteCommand() 을 실행하게 된다. BWriteCommand() 는 다음과 같다.

 BWriteCommand.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
package com.javalec.springMVCBoard.command;
 
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
 
import org.springframework.ui.Model;
 
import com.javalec.springMVCBoard.dao.BDao;
 
 
public class BWriteCommand implements BCommand {
 
    @Override
    public void execute(Model model) {
        // TODO Auto-generated method stub
        
        Map<String, Object> map = model.asMap();
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        String bName = request.getParameter("bName");
        String bTitle = request.getParameter("bTitle");
        String bContent = request.getParameter("bContent");
        
        BDao dao = new BDao();
        dao.write(bName, bTitle, bContent);
    }
}
cs

입력된 작성자명과 글제목 그리고 글내용을 가지고와서  dao.write(bName, bTitle, bContent)

를 실행시킨다.(DB와 연동) 

 BDao.java   의 dao.write() 부분

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
public void write(String bName, String bTitle, String bContent) {
        // TODO Auto-generated method stub
        
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        
        try {
            connection = dataSource.getConnection();
            String query = "insert into mvc_board (bId, bName, bTitle, bContent, bHit, bGroup, bStep, bIndent) values (mvc_board_seq.nextval, ?, ?, ?, 0, mvc_board_seq.currval, 0, 0 )";
            preparedStatement = connection.prepareStatement(query);
            preparedStatement.setString(1, bName);
            preparedStatement.setString(2, bTitle);
            preparedStatement.setString(3, bContent);
            int rn = preparedStatement.executeUpdate();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {
            try {
                if(preparedStatement != null) preparedStatement.close();
                if(connection != null) connection.close();
            } catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }
        
    }
cs

데이터 베이스와 연동하여 쿼리문을 실행, 입력된 작성자명과 글 제목 그리고 글 내용을 DB에 저장한다.

(preparedStatement 를 사용, 1 - 작성자명 / 2 - 글 제목 3 - 글 내용 을 저장하였다.)

위에서 만들었던  create sequence mvc_board seq 에 의해서 bId 의 부분은 mvc_board_seq.nextval

로써 첫번째 게시글은 글 번호가 1이 된다. 입력 버튼을 누르게 되면 BController.java  에 매핑된 

return "redirect:list";  에 따라서 작성한 글 리스트를 가지고 글 목록으로 돌아가게 된다.

*실행결과

'입력' 클릭 시



-계속-


'Spring' 카테고리의 다른 글

SpringMVC(JDBC 사용)  (0) 2016.05.19
SpringMVC(get, post 방식으로 값 넘기기)  (0) 2016.05.17
SpringMVC  (0) 2016.05.17
AOP 구현(@Aspect 어노테이션 기반)  (0) 2016.05.13
AOP 구현(XML 스키마 기반 Advice 종류 예제)  (0) 2016.05.13
,


SpringMVC 프로젝트에서 get 과 post 방식으로 값을 넘기는 예제이다.


get 방식 예제)


1. student1.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<%@ 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>Insert title here</title>
</head>
<body>
    <form action = "student" method = "get">
        student id : <input type = "text" name = "id"><br/>
        <input type = "submit" value = "전송">
    </form>
</body>
</html>
cs


2. student2.jsp

1
2
3
4
5
6
7
8
9
10
11
12
<%@ 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>Insert title here</title>
</head>
<body>
    StudentId : ${studentId}
</body>
</html>
cs


3. 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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.java.ex;
 
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
 
import javax.servlet.http.HttpServletRequest;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
 
/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
    
    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
    
    /**
     * Simply selects the home view to render by returning its name.
     */
 
    @RequestMapping("student1")
    public String gostudent1(){
        return "/student/student1";
    }
    
    @RequestMapping(value = "/student", method = RequestMethod.GET)
    public String goStudent(HttpServletRequest httpServletRequest, Model model) {
        
        System.out.println("RequestMethod.GET");
        
        String id = httpServletRequest.getParameter("id");
        System.out.println("id : " + id);
        model.addAttribute("studentId", id);
        
        return "student/student2";
    }
}    
cs


*실행결과




=> HomeController.java 는 @Controller 어노테이션을 클래스에 적용하고, 

@RequestMapping 어노테이션을 이용하여 클라이언트의 요구에 따라 처리할 메서드를 지정하였다.

(내부적으로 스프링에 속해있는 Dispatcher(web.xml 에 설정되어 있음) 가 

클라이언트의 요청과 컨트롤러를 통한 결과 값 그리고 뷰페이지 생성에 관여함)

따라서 student1 라는 url 이 왔을 때 student 폴더에 들어있는 student1.jsp 뷰 페이지를 보여주고 

여기에 작성한 student id 가 Controller 를 거쳐 GET 방식으로 student2.jsp 뷰 페이지에서 불러지게 된다.

get 방식이기 때문에 student2 의 url 에서 값이 보이는 것을 볼 수 있다.


post 방식 예제)

1. student1.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<%@ 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>Insert title here</title>
</head>
<body>
    <form action = "student" method = "post">
        student id : <input type = "text" name = "id"><br/>
        <input type = "submit" value = "전송">
    </form>
</body>
</html>
cs


2. student2.jsp

1
2
3
4
5
6
7
8
9
10
11
12
<%@ 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>Insert title here</title>
</head>
<body>
    StudentId : ${studentId}
</body>
</html>
cs


3. 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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.java.ex;
 
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
 
import javax.servlet.http.HttpServletRequest;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
 
/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
    
    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
    
    /**
     * Simply selects the home view to render by returning its name.
     */
 
    @RequestMapping("student1")
    public String gostudent1(){
        return "/student/student1";
    }
    
    @RequestMapping(value = "/student", method = RequestMethod.POST)
    public ModelAndView goStudent(HttpServletRequest httpServletRequest) {
        
        System.out.println("RequestMethod.POST");
        
        String id = httpServletRequest.getParameter("id");
        System.out.println("id : " + id);
        
        ModelAndView mav = new ModelAndView();
        mav.setViewName("student/student2");
        mav.addObject("studentId", id);
        
        return mav; 
    }
}
cs


*실행결과




=> get 방식과는 다르게 ModelAndView 를 이용하였다. post 방식으로 값과 경로를

모두 관리하기 위헤서 ModelAndView 객체를 따로 생성하여 값을 student/student2 로 

보내겠다고 지정하였다. post 방식이기 때문에 url 에 값이 보이지 않는 것을 확인할 수 있다.



'Spring' 카테고리의 다른 글

SpringMVC(JDBC 사용)  (0) 2016.05.19
SpringMVC 게시판  (0) 2016.05.18
SpringMVC  (0) 2016.05.17
AOP 구현(@Aspect 어노테이션 기반)  (0) 2016.05.13
AOP 구현(XML 스키마 기반 Advice 종류 예제)  (0) 2016.05.13
,

SpringMVC

Spring 2016. 5. 17. 20:57

스프링 MVC 프레임워크(Spring Model View Controller Framework)

=> 스프링이 제공하는 트랜잭션(데이터 베이스 내에서 한꺼번에 처리되어야 할 일련의 연산들)

 처리, DI, AOP 를 보다 손쉽게 사용 가능하게 해주는 기능이다.

SpringMVC 의 주요 구성 요소와 처리 및 흐름은 다음과 같다.

우선 모든 요청을 Dispatcher Servlet 에서 받고 이 요청을 적절히 처리할 Controller 를 

URL에 따라 선택하기 위해서 Handler Mapping 을 이용한다. 선택된 Controller

요청을 처리 후 ModelAndViewDispatcher Servlet 에게 돌려주며 Dispatcher Servlet

돌아온 ModelAndView 를 통해서 View Resolver 를 호출하여 View 를 얻는다.  이 때 얻은 

ViewModel 을 적용하여 Response 를 만들고 Request 를 보냈던 Client 에게 돌려준다.


SpringMVC 프로젝트 생성

1. New -> Project 를 눌러 프로젝트


2. Spring Legacy Project 를 선택 후 Next 로 넘어간다.


3. Project name 을 입력하고, Templates 를 Spring MVC Project 선택 후 Next 로 넘어간다.


4. package 이름 설정(3단계로) 후 완료


5. 자동으로 HomeController.java 와 home.jsp 등 컨트롤러와 뷰페이지 그리고 폴더들이 자동으로 생성된다.


,


AOP 구현 방식 중 @Aspect 어노테이션을 기반으로 한 예제이다.


1. LogAop.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
package com.java.ex3;
 
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
 
@Aspect
public class LogAop {
    
    @Pointcut("bean(*ker)")        //~ker로 끝나는 빈에만 적용
    private void pointcutMethod() {
    }
    
    @Around("pointcutMethod()")
    public Object loggerAop(ProceedingJoinPoint joinpoint) throws Throwable {
        String signatureStr = joinpoint.getSignature().toShortString();
        System.out.println(signatureStr + "is start.");
        long st = System.currentTimeMillis();
        
        try {
            Object obj = joinpoint.proceed();
            return obj;
        } finally {
            long et = System.currentTimeMillis();
            System.out.println(signatureStr + " is finished.");
            System.out.println(signatureStr + " 경과시간 : " + (et - st));
        }
    }
    
    @Before("within(com.java.ex3.*)")
    public void beforeAdvice() {
        System.out.println("beforeAdvice()");
    }
}
cs


2. MainClass.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.java.ex3;
 
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
 
public class MainClass {
    public static void main(String[] args) {
        
        AbstractApplicationContext ctx
        = new GenericXmlApplicationContext("classpath:applicationCTX3.xml");
        
        Student student = ctx.getBean("student", Student.class);
        student.getStudentInfo();
        
        Worker worker = ctx.getBean("worker", Worker.class);
        worker.getWorkerInfo();
        
        ctx.close();
    }
}
cs


3. Student.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
package com.java.ex3;
 
public class Student {
    private String name;
    private int age;
    private int gradeNum;
    private int classNum;
    
    public void getStudentInfo() {
        System.out.println("이름 : " + getName());
        System.out.println("나이 : " + getAge());
        System.out.println("학년 : " + getGradeNum());
        System.out.println("반 : " + getClassNum());
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    public int getGradeNum() {
        return gradeNum;
    }
 
    public void setGradeNum(int gradeNum) {
        this.gradeNum = gradeNum;
    }
 
    public int getClassNum() {
        return classNum;
    }
 
    public void setClassNum(int classNum) {
        this.classNum = classNum;
    }
}
cs


4. Worker.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
package com.java.ex3;
 
public class Worker {
    private String name;
    private int age;
    private String job;
    
    public void getWorkerInfo() {
        System.out.println("이름 : " + getName());
        System.out.println("나이 : " + getAge());
        System.out.println("직업 : " + getJob());
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    public String getJob() {
        return job;
    }
 
    public void setJob(String job) {
        this.job = job;
    }
}
cs


5. applicationCTX3.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:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
 
    <aop:aspectj-autoproxy />
    <bean id="logAop" class="com.java.ex3.LogAop" />
    
    <bean id="student" class="com.java.ex3.Student">
        <property name="name" value="홍길동" />
        <property name="age" value="10" />
        <property name="gradeNum" value="3" />
        <property name="classNum" value="5" />
    </bean>
    
    <bean id="worker" class="com.java.ex3.Worker">
        <property name="name" value="홍길순" />
        <property name="age" value="35" />
        <property name="job" value="개발자" />
    </bean>
    
</beans>
cs


*실행결과

=> 앞에 작성했던 XML 스키마 기반과 달리 @Aspect 어노테이션을 사용하여 AOP를 구현 하였다.
또 pointcut을 지정하기 위해 표현식으로 Aspectj 문법을 사용하였다.

 @Pointcut("bean(*ker)")        //~ker로 끝나는 빈에만 적용
    private void pointcutMethod() {
    }

ker로 끝나는 빈에만 적용을 지정하였기 떄문에 실행결과에서 Student 는 공통 기능(LogAop)이
적용되지 않았고 Worker 에만 적용이 된 모습을 확인할 수 있다.


'Spring' 카테고리의 다른 글

SpringMVC 게시판  (0) 2016.05.18
SpringMVC(get, post 방식으로 값 넘기기)  (0) 2016.05.17
SpringMVC  (0) 2016.05.17
AOP 구현(XML 스키마 기반 Advice 종류 예제)  (0) 2016.05.13
AOP 구현(XML 스키마 기반)  (0) 2016.05.13
,


AOP 구현(XML 스키마 기반)에서 Advice 의 종류 5가지를 설명하였다.

Advice 종류 5가지를 모두 적용시켜 본 예제이다.


예제)

1. pom_xml(의존설정)

1
2
3
4
5
6
7
<!-- AOP -->
 
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.7.4</version>
        </dependency>
cs


2. Log.Aop.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
package com.java.ex2;
 
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
 
public class LogAop {
        public Object loggerAop(ProceedingJoinPoint joinpoint) throws Throwable {
            String signatureStr = joinpoint.getSignature().toShortString();
            System.out.println(signatureStr + "is start.");
            long st = System.currentTimeMillis();
            
            try {
                Object obj = joinpoint.proceed();
                return obj;
            } finally {
                long et = System.currentTimeMillis();
                System.out.println(signatureStr + " is finished.");
                System.out.println(signatureStr + " 경과시간 : " + (et - st));
            }
        }
        
        public void beforeActive(JoinPoint joinPoint) {
            System.out.println("beforeAdvice()");
        }
        
        public void afterReturnActive(JoinPoint joinPoint) {
            System.out.println("afterReturnAdvice()");
        }
        
        public void afterThrowingActive(JoinPoint joinPoint) {
            System.out.println("afterThrowingAdvice()");
        }
        
        public void afterActive(JoinPoint joinPoint) {
            System.out.println("afterAdvice()");
        }
}
cs


3. Student.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
package com.java.ex1;
 
public class Student {
    private String name;
    private int age;
    private int gradeNum;
    private int classNum;
    
    public void getStudentInfo() {
        System.out.println("이름 : " + getName());
        System.out.println("나이 : " + getAge());
        System.out.println("학년 : " + getGradeNum());
        System.out.println("반 : " + getClassNum());
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    public int getGradeNum() {
        return gradeNum;
    }
 
    public void setGradeNum(int gradeNum) {
        this.gradeNum = gradeNum;
    }
 
    public int getClassNum() {
        return classNum;
    }
 
    public void setClassNum(int classNum) {
        this.classNum = classNum;
    }
}
 
cs


4. Worker.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
package com.java.ex1;
 
public class Worker {
    private String name;
    private int age;
    private String job;
    
    public void getWorkerInfo() {
        System.out.println("이름 : " + getName());
        System.out.println("나이 : " + getAge());
        System.out.println("직업 : " + getJob());
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    public String getJob() {
        return job;
    }
 
    public void setJob(String job) {
        this.job = job;
    }
}
cs


5. MainClass.Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.java.ex1;
 
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
 
public class MainClass {
 
    public static void main(String[] args) {
 
        AbstractApplicationContext ctx
        = new GenericXmlApplicationContext("classpath:applicationCTX2.xml");
 
        Student student = ctx.getBean("student", Student.class);
        student.getStudentInfo();
 
        Worker worker = ctx.getBean("worker", Worker.class);
        worker.getWorkerInfo();
        
        ctx.close();
    }
}
cs


6. applicationCTX2.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
<?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:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
 
    <bean id="logAop" class="com.java.ex2.LogAop" />
    
    <aop:config>
        <aop:aspect id="logger" ref="logAop">
            <aop:pointcut expression="within(com.java.ex2.*)" id="publicM"/>
            <aop:around method="loggerAop" pointcut-ref="publicM"/>
        </aop:aspect>
        
        <aop:aspect id="logger" ref="logAop">
            <aop:pointcut expression="within(com.java.ex2.*)" id="publicM"/>
            <aop:before method="beforeActive" pointcut-ref="publicM"/>
        </aop:aspect>
        
        <aop:aspect id="logger" ref="logAop">
            <aop:pointcut expression="within(com.java.ex2.*)" id="publicM"/>
            <aop:after-returning method="afterReturnActive" pointcut-ref="publicM"/>
        </aop:aspect>
        
        <aop:aspect id="logger" ref="logAop">
            <aop:pointcut expression="within(com.java.ex2.*)" id="publicM"/>
            <aop:after-throwing method="afterThrowingActive" pointcut-ref="publicM"/>
        </aop:aspect>
        
        <aop:aspect id="logger" ref="logAop">
            <aop:pointcut expression="within(com.java.ex2.*)" id="publicM"/>
            <aop:after method="afterActive" pointcut-ref="publicM"/>
        </aop:aspect>
    
    </aop:config>
 
    <bean id="student" class="com.java.ex2.Student">
        <property name="name" value="홍길동" />
        <property name="age" value="10" />
        <property name="gradeNum" value="3" />
        <property name="classNum" value="5" />
    </bean>
    
    <bean id="worker" class="com.java.ex2.Worker">
        <property name="name" value="홍길순" />
        <property name="age" value="35" />
        <property name="job" value="개발자" />
    </bean>
 
</beans>
cs

*실행결과


=> Advice의 종류 다섯가지를 모두 적용 시켜 실행시킨 결과이다.

예외가 발생하지 않았기 때문에 after-throwing(예외 발생 시)을 제외하고 

befor(메소드 실행 전), after-returning(정상적으로 메소드 실행 후), 

after(메소드 실행 시 예외 발생에 상관없이), around(메소드 실행 전과 후 및 예외 발생 시)가

모두 실행되었음을 볼 수 있다.



'Spring' 카테고리의 다른 글

SpringMVC 게시판  (0) 2016.05.18
SpringMVC(get, post 방식으로 값 넘기기)  (0) 2016.05.17
SpringMVC  (0) 2016.05.17
AOP 구현(@Aspect 어노테이션 기반)  (0) 2016.05.13
AOP 구현(XML 스키마 기반)  (0) 2016.05.13
,

AOP 구현의 방식 중 XML 스키마를 기반으로 한 예제이다.


예제)

1. pom_xml(의존설정)

1
2
3
4
5
6
7
<!-- AOP -->
 
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.7.4</version>
        </dependency>
cs


2. Log.Aop.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.java.ex1;
import org.aspectj.lang.ProceedingJoinPoint;
 
public class LogAop {
 
    public Object loggerAop(ProceedingJoinPoint joinpoint) throws Throwable {
            String signatureStr = joinpoint.getSignature().toShortString();
            System.out.println(signatureStr + "is start.");
            long st = System.currentTimeMillis()
 
            try {
                Object obj = joinpoint.proceed();
                return obj;
            } finally {
                long et = System.currentTimeMillis();
                System.out.println(signatureStr + " is finished.");
                System.out.println(signatureStr + " 경과시간 : " + (et - st));
            }
        }
}
cs


3. Student.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
package com.java.ex1;
 
public class Student {
    private String name;
    private int age;
    private int gradeNum;
    private int classNum;
    
    public void getStudentInfo() {
        System.out.println("이름 : " + getName());
        System.out.println("나이 : " + getAge());
        System.out.println("학년 : " + getGradeNum());
        System.out.println("반 : " + getClassNum());
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    public int getGradeNum() {
        return gradeNum;
    }
 
    public void setGradeNum(int gradeNum) {
        this.gradeNum = gradeNum;
    }
 
    public int getClassNum() {
        return classNum;
    }
 
    public void setClassNum(int classNum) {
        this.classNum = classNum;
    }
}
 
cs


4. Worker.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
package com.java.ex1;
 
public class Worker {
    private String name;
    private int age;
    private String job;
    
    public void getWorkerInfo() {
        System.out.println("이름 : " + getName());
        System.out.println("나이 : " + getAge());
        System.out.println("직업 : " + getJob());
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    public String getJob() {
        return job;
    }
 
    public void setJob(String job) {
        this.job = job;
    }
}
cs


5. MainClass.Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.java.ex1;
 
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
 
public class MainClass {
 
    public static void main(String[] args) {
 
        AbstractApplicationContext ctx
        = new GenericXmlApplicationContext("classpath:applicationCTX1.xml");
 
        Student student = ctx.getBean("student", Student.class);
        student.getStudentInfo();
 
        Worker worker = ctx.getBean("worker", Worker.class);
        worker.getWorkerInfo();
        
        ctx.close();
    }
}
cs


6. applicationCTX1.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
<?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:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
 
    <bean id="logAop" class="com.java.ex1.LogAop" />
    
    <aop:config>
        <aop:aspect id="logger" ref="logAop">
            <aop:pointcut expression="within(com.java.ex1.*)" id="publicM" />
            <aop:around method="loggerAop" pointcut-ref="publicM" />
        </aop:aspect>
    </aop:config>
    
    <bean id="student" class="com.java.ex1.Student">
        <property name="name" value="홍길동" />
        <property name="age" value="10" />
        <property name="gradeNum" value="3" />
        <property name="classNum" value="5" />
    </bean>
    
    <bean id="worker" class="com.java.ex1.Worker">
        <property name="name" value="홍길순" />
        <property name="age" value="35" />
        <property name="job" value="개발자" />
    </bean>
</beans>
cs


*실행결과

=> 관점 지향 프로그래밍 AOP 구현을 위해 pom_xml에서 의존설정을 해주었다.

관점 지향 프로그래밍에 맞게 공통 기능과 핵심 기능으로 기능을 분리한다.

공통 기능은 공통기능이 필요한 핵심 기능의 부분에만 적용할 것이기 때문이다.

LogAop.java 에 작성된 코드가 공통 기능에 해당하고, 이를 applicationCTX1.xml에 

추가하였다.  <bean id="logAop" class="com.java.ex1.LogAop" />

<aop:config>
        <aop:aspect id="logger" ref="logAop">
            <aop:pointcut expression="within(com.java.ex1.*)" id="publicM" />
            <aop:around method="loggerAop" pointcut-ref="publicM" />
        </aop:aspect>
    </aop:config>

위의 코드를 보면 Advice(공통 기능 자체)가 around 로 지정되어있는 것을 볼 수 있다.

AOP구현에 있어서 Advice의 종류는 5가지가 있는데 그 중  around 는 메서드의 실행 전 / 후 및 

exception 발생시 Advice를 실행한다. 따라서 실행결과를 보면 Student 와 Worker 가 print 되기 

전 후로 공통 기능(LogAop)이 실행된 것을 확인 할 수 있다.



Advice의 종류


<aop:before> : 메소드 실행 전에 advice실행

<aop:after-returning> : 정상적으로 메소드 실행 후에 advice실행

<aop:after-throwing> : 메소드 실행중 exception 발생시 advice실행

<aop:after> : 메소드 실행중 exception 이 발생하거나 하지 않아도 advice실행

<aop:around> : 메서 실행 전/  exception 발생시 advice실행





'Spring' 카테고리의 다른 글

SpringMVC 게시판  (0) 2016.05.18
SpringMVC(get, post 방식으로 값 넘기기)  (0) 2016.05.17
SpringMVC  (0) 2016.05.17
AOP 구현(@Aspect 어노테이션 기반)  (0) 2016.05.13
AOP 구현(XML 스키마 기반 Advice 종류 예제)  (0) 2016.05.13
,