본문 바로가기

JAVA - Backend/SpringBoot - ApplicationFramework

Spring WebMVC Structure Concept

참고: https://onlyformylittlefox.tistory.com/category/Develop/Server

 

'Develop/Server' 카테고리의 글 목록

흔한 개발자의 발자취

onlyformylittlefox.tistory.com

Controller

URL(Request) Mapping Class
사용자가 브라우져에서 특정 URL로 요청한 Request를 메소드에 Mapping 하여 처리할 수 있도록 하는 역할

@Controller 스프링 컨텍스트에 Bean으로 등록될 수 있도록한다.
@RestController 응답을 View가 아닌 응답 본문에 직접 씀 객체의 경우 httpmassageconverter를 통해 JSON 반환
@ResponsBody @Controller에서 특정 메서드만 응답을 응답 본문에 직접 쓰고 싶은 경우 사용
@RequestMapping Controller 메서드에 특정 URL과 Method(GET, POST, DELETE 등등)를 Mapping
@RequestMapping(value="/userInfo", method=RequestMethod.GET)
@GetMapping 등 @RequestMapping 대신 @GetMapping("/event/{id}") 처럼 써도 됨 더 간결함
@PathVariable public Event getEvent(@PathVariable Integer id) : {id}처럼 URL에 PlaceHolder 변수 처리
@RequestParam Request에 넘어온 Parameter 처리
public String postUserInfo(@RequestParam("userName") String userName, @RequestParam("userAge") String userAge, Model model)
Model ModelMap 템플릿에 전달할 내용을 담아 넘기는 용도
    model.addAttribute("userName", userName);
    model.addAttribute("userAge", userAge);
    return "user"; // user 템플릿으로 model이 같이 넘어감
VO Value Object
@Autowired Context에 등록되어 있는 Bean 객체의 Reference 주입
Controller에서는 보통 Service Bean을 주입받아 사용

Domain (VO - Value Object + DTO - Data Transfer Object)

VO - Getter, Setter 둘다 필요 (DTO의 역할까지 할 수 있음)

유사한 데이터를 묶어 처리하는 데이터 집합 클래스
ex) Request 파라메터가 많아졌을때 @RequestParam을 사용하면 코드도 긿어지고 가독성도 떨어짐

AS-IS
public String postUserInfo(@RequestParam("userName") String userName, @RequestParam("userAge") String userAge, Model model)

TO-BE
User VO 정의
@DATA
public class User { private int userID; private String userName;}
Controller에서 사용
public String postUserInfo(User user, Model model)

Spring은 변수 이름을 보고 매핑 시킴

DTO - Getter만 정의하고 데이터는 생성자로 넣는다. Setter는 없어도 됨

DB나 외부 서비스에서 가져온 데이터를 담는 용도의 클래스

Service (Service - Interface, ServiceImpl - Service Interface 구현체로 Pair 구성)

비지니스 로직 기술 : 정보 가공 및 DB데이터 핸들링

ServiceImpl은 @Service로 Bean 생성 및 등록

Mapper : MyBatis case, Persistant : JPA
(JAVA Mapper는 DAO - Data Access Object Interface + Resource Mapper는 SQL.xml)

 

관심사이동

Controller -> VO(DTO) -> Service -> DAO -> SQL.xml -> DAO -> VO(DTO) -> Service -> Controller -> View

Controller

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
 
import com.example.demo.service.UserService;
import com.example.demo.vo.User;
 
@RequestMapping(value="/user")
@RestController
public class UserController {
     
    @Autowired
    private UserService userService;
     
    @RequestMapping(value = "/userInfo.do", method = RequestMethod.GET)
    public User userInfo(User user) throws Exception{
        return userService.getUserInfo(user);
    }
}

 

VO - DTO

public class User {
     
    private int id;
    private String userId;
    private String userPassword;
    private String userName;
     
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
    public String getUserPassword() {
        return userPassword;
    }
    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
 
}

 

Service

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.dao.UserDAO;
import com.example.demo.service.UserService;
import com.example.demo.vo.User;
 
@Service
public class UserServiceImpl implements UserService{
     
    @Autowired
    private UserDAO userDAO;
 
    @Override
    public User getUserInfo(User user) throws Exception {
        // TODO Auto-generated method stub
        return userDAO.selectUser(user);
    }
 
}

 

DAO

public interface UserDAO {
    public User selectUser(User user) throws Exception;
}

 

Mapper

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.demo.dao.UserDAO">
 
    <select id="selectUser"
        parameterType="com.example.demo.vo.User"
        resultType="com.example.demo.vo.User">
        SELECT
        USER_NAME
        FROM user
        WHERE USER_ID = #{userId}
            AND USER_PASSWORD = #{userPassword}
    </select>
</mapper>