> For the complete documentation index, see [llms.txt](https://www.pentestwiki.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.pentestwiki.com/web-application/java/java-web-application/spring-mvc.md).

# Spring MVC

MVC(Model, View, Controller)는 애플리케이션 파이프라인을 3가지로 구분하여 역할에 맞게 개발하는 방식이며, Spring MVC는 그 모델을 Spring에서 구현한 프레임워크입니다.

MVC에서는 사용자의 요청을 `Controller → Service → DAO/Mapper → DB → DTO에 매핑 → DAO → Service → Controller` 순서로 처리합니다.

예를 들어서 id를 기반으로 게시글을 구분하는 게시판에 사용자가 접근했다고 했을 때, 각 단계별로 아래와 같은 코드로 구현되어 있습니다.

#### Controller

`/board/detail` 엔드포인트로 접근하는 GET 메서드 요청을 받고 boardService.getBoardDetail을 호출

```java
@Controller
public class BoardController {

    private BoardService boardService;

    @GetMapping("/board/detail")
    @ResponseBody
    public BoardDto detail(@RequestParam int id) {
        return boardService.getBoardDetail(id);
    }
}
```

#### Service

전달된 id 식별값이 올바른 경우 boardDao.selectBoard 를 호출

```java
@Service
public class BoardService {

    private BoardDao boardDao;

    public BoardDto getBoardDetail(int id) {
        if (id <= 0) {
            throw new IllegalArgumentException("invalid id");
        }

        return boardDao.selectBoard(id);
    }
}
```

#### DAO

JDBC 혹은 SQL Mapper 등을 통해 DB에 접근하고, SQL 실행 결과로 매핑된 DTO 반환

```java
@Repository
public class BoardDao {

    private SqlMapClientTemplate sqlMapClientTemplate;

    public BoardDto selectBoard(int id) {
        return (BoardDto) sqlMapClientTemplate.queryForObject(
            "Board.selectBoard",
            id
        );
    }
}
```

#### SQL Mapper

Board 네임스페이스에 selectBoard를 정의해두고, DAO로 인해 호출되면 저장해둔 쿼리를 실행

```xml
<sqlMap namespace="Board">

    <select id="selectBoard"
            parameterClass="int"
            resultClass="com.example.BoardDto">
        SELECT
            id,
            title,
            writer,
            content
        FROM board
        WHERE id = #value#
    </select>

</sqlMap>
```

#### DTO

실행된 결과를 담는 객체 역할

```java
public class BoardDto {
    private int id;
    private String title;
    private String writer;
    private String content;

    public int getId() { return id; }
    public void setId(int id) { this.id = id; }

    public String getTitle() { return title; }
    public void setTitle(String title) { this.title = title; }

    public String getWriter() { return writer; }
    public void setWriter(String writer) { this.writer = writer; }

    public String getContent() { return content; }
    public void setContent(String content) { this.content = content; }
}
```
