본문 바로가기

Spring

"Spring Controller 전격 파헤치기"

Spring 컨트롤러, 메소드 10개로 끝내기

public class MyController{} ---> 자바 Object 클래스!!

---------------------------------------------------------------------------------------------

com.encore.control;


@Controller 

public class MyController{}

-----> 스프링 컨트롤러 객체!!

-----> 단, 컨트롤러 객체 등록: servlet-context.xml

----> 방법1) <bean class="com.encore.control.MyController"></bean>

---> 앞으로 생성되는 모든 컨트롤러를 등록하는 것이 불편할  수 있다!!

----> 방법2) <context:component-scan base-package="com.encore.control"/>

---> base-package에 정의된 패키지 또는 하위 패키지에서 만든 

컨트롤러는 별도의 <bean> 등록이 필요 없음!!


@Controller

@RequestMapping("가상경로")

public class MyController{


@RequestMapping("가상경로")

public void method(){

-요청분석

- (클라이언트가 보낸)데이터 얻기

- 모델객체생성, 호출, 리턴값 영역에 저장하기

- (단순 이동 또는 모델의 값을 출력할)페이지 설정

----> 서블릿의 service(req,resp) 메소드, 스트럿츠의 execute()메소드에 해당


}

------------------------------------------------------------------------------------------------------------------

//단순 JSP페이지 포워딩 case1)

@RequestMapping("test1")

public void m1(){

//만약 리턴 타입을 명시하지 않는다면 (void) ---> [요청URL == 이동할 View]

----> /WEB-INF/views/ + test1 + .jsp

----> /WEB-INF/views/test1.jsp

}


//단순 JSP페이지 포워딩 case1)

@RequestMapping("test2") //URL 요청

public String m2(){

return "0828/hello";

//리턴 타입을 명시 ===>  스프링 컨테이너에서 뷰 정보로 인식

----> /WEB-INF/views/ + 0828/hello + .jsp

----> /WEB-INF/views/0828/hello.jsp //이동할 페이지

}


//폼안의 데이터 얻어오기 @RequestMapping("test3") public String m3(HttpServletRequest request){ String name = request.getParameter("username"); request.setAttribute("msg",name); //뷰와 공유할 데이터를 request영역에 저장

return "0828/hello";    //hello.jsp에서 msg키에 저장된 name을 공유 }
//폼안의 데이터 얻어오기 @RequestMapping("test4") public String m4(HttpServletRequest request, HttpSession session){ String name = request.getParameter("username"); session.setAttribute("msg",name);    // 뷰와 공유할 데이터를 session 영역에 저장 return "0828/hello"; }
//폼안의 데이터 얻어오기 @RequestMapping("test5") public String m5(String username, Model model){ System.out.println("UserName: "+ username); model.addAttribute("msg", username); // model.addAttribute("키값", 공유Object); //---> 스프링에서는 Model이라는 데이터 저장영역을 사용하고 있음 ---> request영역처럼 사용 return "0828/hello"; } //폼안의 데이터 얻어오기 @RequestMapping("test6") public String m6(String name, int age, String job){ System.out.println("이름:"+ name +",나이:"+age+",직업:"+job); return "0828/hello"; } //폼안의 데이터 얻어오기 @RequestMapping("test7") public String m7(Person p, Model m){ System.out.println("사람정보:"+p); m.addAttribute("p",p); return "0828/hello"; } //폼안의 데이터 얻어오기 @RequestMapping("test8") public String m8(@ModelAttribute("p") Person ppp){ //"p" ---->영역키로 사용, 변수명ppp ----> 현재메소드내에서 사용할 이름 System.out.println("사람정보:"+ppp); return "0828/hello"; }
//폼안의 데이터 얻어오기         <---- 참고만 하세요 @RequestMapping("test9") public ModelAndView m9(Person p){ ModelAndView mav = new ModelAndView();
//ModelAndView객체: Model(데이터: String, VO, List)과 View정보(hello.jsp)를 담는 바구니클래스
mav.addObject("p",p); //데이터 저장, 위의 코드 model.addAttribute("p",p); 와 같음
mav.setViewName("0828/hello"); //이동할 페이지, return "0828/hello";와 같음
return mav; //공유할 데이터와 이동할 페이지를 한꺼번에 리턴 }
//폼안의 데이터 얻어오기 <---- 참고만 하세요!! @RequestMapping("insert") public String m10(RedirectAttributes attr){ attr.addFlashAttribute("favoriteColor","파랑색"); //RedirectAttributes: 리다이렉트 이동시 request공유할 데이터를 표현 return "redirect:/list"; //m9메소드까지는 forward이동!! //리턴문자열 중 접두사 " redirect:"을 붙이면 리다이렉트 이동!!
//---> 필요한 경우: insert, delete, update 후 이동페이지를 표현할 때 사용.
//---> 왜? 만약 포워드 이동시 (F5기능키 누를때) DML을 다시한번 실행 할 수도 있기 때문.
}

@RequestMapping("list") public String m11(RedirectAttributes attr){ return "0828/list"; }