웹/spring

[Spring] 스프링 MVC의 Controller

은은하게미친자 2022. 8. 25. 17:42
728x90

1. 스프링 MVC의 Controller

  • HttpServletRequest, HttpServletResponse 를 거의 사용 할 필요없이 필요한 구현
  • 다양한 파라미터처리, 다양한타입의 리턴 타입 사용 가능
  • GET방식/POST방식 등 전송방식에 대한 처리를 어노테이션으로 처리가능
  • 상속/인터페이스 방식 대신에 어노테이션 만으로도 필요한 설정 가능

2. @Controller, @RequestMapping

  • @Controller : Controller객체임을 명시 , 사용시 servelet-context.xml 의 <context:component-scan base-package="kr.co.dong" />  태그에 설정된 패키지를 스캔하여 @Controller 및 스프링에 빈 설정에 사용되어있는 어노테이션을 자동으로 스프링 빈으로 등록 = > Controller라 정상적으로 스프링빈으로 등록 되면 클래서 옆에 s모양의 아이콘이추가됩니다

  • @RequestMapping : 현재 클래스의 모든 메서드들의 default URL경로 설정한다. 클래스,메소드에 사용가능
    • Method 에 사용시 에는 @GetMapping,@PostMapping 로 대체 가능하다.

3.1 컨트롤러의 파라미터 수집

파라미터 전달의 다양한 방식 참고 :  https://leggo.tistory.com/79

 

[spring] - request parameter 전달 받는 방법 4가지! 예제 /Cotroller의 파라미터 수집

Cotroller의 파라미터 수집 : Cotroller를작성할 때 가장 편리한 기능은 파라미터가 자동으로 수집되는 기능입니다! 이기능을 이용하면 매번 request.getParameter()를 이용하는 불편함을 줄일 수있습니다.

leggo.tistory.com

3.2. @InitBinder

: 파라미터 수집해서 객체로 변환 시에 사용

파라미터의 데이터는 변환이 가능한 데이터는 자동으로 변환되지만  경우에 따라서 파라미터를 변환해서 처리해야 하는 경우도 존재합니다. ex) "2022-08-25" 과 같이 문자열로 전달된 데이터를 java.util.Date 타입으로 변환해야 할때

1
2
3
4
5
6
    @InitBinder
    public void initbinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(java.util.Date.classnew CustomDateEditor(dateFormat, false));
    }    
    
cs

 

 

3.3. @DateTimeFormat

@InitBinder 대신에 하기 예제와 같이 사용 할 수 있다.

1
2
3
    @DateTimeFormat(pattern = "yyyy/MM/DD")
    private Date dueDate;
 
cs

4.1. Model 객체 

: JSP 컨트롤러에서 생성된 데이터를 담아서 전달 하는 역할, 뷰와 컨트롤러간의 데이터전달자.

뷰에서 생성된  데이터를 전달 하기 위해 사용

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    /**
     * Simply selects the home view to render by returning its name.
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(Locale locale, Model model) {
        logger.info("Welcome home! The client locale is {}.", locale);
        
        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
        
        String formattedDate = dateFormat.format(date);
        
        model.addAttribute("serverTime", formattedDate );
        
        return "home";
    }
cs

4.2. @ModelAttribute 

: 강제로 전달 받은 파라미터를 Model에 담아서 전달하도록 할때 필요한 어노테이션,

파라미터의 타입에 관계없이 무조건 Model에 담아서 전달

기본형 지역변수의 경후 함수가 끝난 이후에 사라져 화면에 전달 할 수없지만

@ModelAttribute  는 파라미터로 전달될 경우 attribute로 등록 되어 함수가 끝난이후에도 화면에 보여줄수있다.

controller

1
2
3
4
5
6
    @RequestMapping(value = "testpage", method = RequestMethod.GET)
    public String testpage (Model model, @ModelAttribute("modelattr"String mAtrr) {
        logger.info(mAtrr);
        model.addAttribute("msg""스프링은 처음이지???");
        return "testpage";
    }
cs

view1

1
2
3
4
5
            <form action="testpage">
                <input type="text" name="modelattr" />
                <input type="submit" value="test page로 이동하기">
                <a href="testpage"> testpage 로 이동하기</a>
            </form>
cs

view2

1
2
    model attribute : ${modelattr}
    <br>
cs

 

 

 

 

 

4.3. RedirectAttributes

:  일회성으로 데이터를 전달하는 용도로 사용, response.sendRedirect()를 사용할 때와 동일한 용도

addFlashAttribute(이름,값) 를 이용해서 화면에 한번만 사용하고 다음에는 사용되지 않는 데이터를 전달 하기위해서 사용합니다.

1
2
3
4
5
6
7
8
9
10
11
12
    @RequestMapping(value = "board/update", method = RequestMethod.POST)
    public String update(BoardDTO boardDTO, RedirectAttributes rttr,HttpServletRequest request) throws Exception {
        request.setCharacterEncoding("utf-8");
        int r = service.update(boardDTO);
        // 수정에 성공하면 목록보기로 이동
        if (r > 0) {
            rttr.addFlashAttribute("msg""수정에 성공 하였습니다.");
            return "redirect:list";
        }
        // 수정에 실패하면 수정보기 화면으로 이동
        return "redirect:update?bno=" + boardDTO.getBno();
    }

cs

redirect 참고 :

 

5. Controller 의 리턴타입

  • String : jsp 파일 경로와 파일이름으로 이동하기위해 사용
  • void : 호출하는 URL과 동일한 이름의 JSP 으로 이동하기위해 사용
  • VO.DTO  : 주로JSON타입의 데이터를 만들어서 반환하는 용도로 사용
  • ResponseEntity : reponse할떄 HTTP헤더 정보와 내용을 가공하는 용도로 사용
  • Model, ModelAndView : Model로 데이터를 반환하거나 화면까지 같이 지정하는 경우에 사용합니다.
  • HttpHeaders : 응답에 내용이 없이 Http헤더메세지만 전달 하는 용도로 사용 

 

 

 

728x90