본문 바로가기

Spring/이론

[Spring] Singleton

 두 값을 입력받아서 form으로 post요청을 보낸 뒤

두 값을 더한 값과 계산 횟수를 콘솔에 출력하려고합니다.

 

<form action = "calculate.do" method = "post">
<table>
  <tr>
  <td>이름: <input name="n" placeholder = "name" autofocus = "autofocus"></td>
  </tr>
  <tr>
  <td>X: <input name="x" placeholder = "X" autofocus = "autofocus"></td>
  </tr>
  <tr>
  <td>Y: <input name="y" placeholder = "Y" autofocus = "autofocus"></td>
  </tr>
  <tr>
  <td><button>버튼</button></td>
  </tr>
</table>
</form>

 

jsp코드는 간단하게 짰습니다.

 

요청파라미터명과 JavaBean멤버변수명을 같게 하면


 자동으로 요청파라미터의 값을 Javabean객체에 맵핑을 하게 됩니다.

 

public class CalcResult {
    private String n;
    public String getN() {
      return n;
  }
  public void setN(String n) {
      this.n = n;
  }
  public int getX() {
      return x;
  }
  public void setX(int x) {
      this.x = x;
  }
  public int getY() {
      return y;
  }
  public void setY(int y) {
      this.y = y;
  }
  private int x;
    private int y;
    public CalcResult() {
      // TODO Auto-generated constructor stub
  }
  public CalcResult(String n, int x, int y) {
      super();
      this.n = n;
      this.x = x;
      this.y = y;
  }
}

 

CalrResult라는 객체를 만드는데

요청파라미터의 이름과 멤버 변수 명을 같게하면

Spring MVC 프레임워크에서 자동으로 요청 데이터를 CalcResult 객체에 바인딩할 수 있습니다.

 

그리고 입력받은 값을 계산해주는

DAO클래스도 하나 만들겠습니다.

 

package com.puft.feb112.calc;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;



@Service // servlet-context.xml에 CalcDAO 객체 하나를 등록해 놓은 효과
public class CalcDAO {

    private int allCalcCount; // 몇 번 계산했는지
   
    //요청파라미터명과 자바빈의 객체의 변수명이 같다면 자동 맵핑
    public void calculate(CalcResult cr, HttpServletRequest req ) {
        allCalcCount++;
        System.out.println(allCalcCount);
        int add = cr.getX() + cr.getY();
        System.out.println(add);
       
       
    }
   
   
}

 

allCalcCount는 계산 횟수를 의미하고

calculate

객체를 파라미터로 받아와서

더해주는 메소드입니다.

 

이제 컨트롤러 쪽에서

두 객체를 생성 후 연결해주면 되겠네요.

@RequestMapping(value = "calculate.do", method = RequestMethod.POST)
    public String calcXY(CalcResult cr, HttpServletRequest req) {
        CalcDAO cDAO = new CalcDAO();
        cDAO.calculate(cr, req);
       
       
        return "jsp/index";
    }
   
   
   

 

CalcResult는 메소드의 파라미터로,

CalcDAO는 메소드 내에 선언했습니다.

그런데 출력을 해보면 문제가 하나 발생합니다.

 

증가하지 않는 계산횟수

 

계산횟수를 뜻하는 CalcDAO변수인

allCalcCount가 증가를 하지 않습니다.

그 이유는 CalcDAO객체가

POST메소드 안에서 선언되기 때문에

요청을 받을때마다 생성되기 때문에

count변수가 초기화됩니다.

이를 해결하려면 어떻게 해야할까요?

 

CalcDAO를 singleton으로 처리하면됩니다.


Spring식의 Singleton 처리 방법이 있는데요.

 

@Autowired
    private CalcDAO cDAO;
   
    @RequestMapping(value = "calculate.do", method = RequestMethod.POST)
    public String calcXY(CalcResult cr, HttpServletRequest req) {
       
        cDAO.calculate(cr, req);
       
       
        return "jsp/index";
    }

 

POST메소드 밖에서

CalcDAO객체를 자동 맵핑 시켜주면 됩니다.

이때 Autowired 어노테이션을 사용합니다.

 

증가된 계산횟수

 

계산횟수가 잘 증가되네요.

'Spring > 이론' 카테고리의 다른 글

[Spring] MyBatis  (0) 2025.02.13
[Spring] POST요청  (0) 2025.02.11
[Spring] Autowired  (0) 2025.02.10
[Spring] Bean  (0) 2025.02.10
[Spring] Annotation  (0) 2025.02.10