Notice
Recent Posts
Recent Comments
Link
개발 무지렁이
[Spring] 어노테이션(annotation)과 파라미터(parameter), 리턴(return) 본문

SERVLET BEAN 설정을 javaBase로, @annotation
컨트롤러 클래스 자동스캔
🪅. Spring MVC 컨포넌트를 다음과 같은 @annotation으로 변환할 수 있다.
web.xml => @WebServlet
Handler Mapping => @RequestMapping
⚠️. MVC에서는 메서드로 호출X, URL 요청주소가 맞는 것이 중요하다.
Controller => @Controller
return: ModelAndView, String, void
[RequestMappingController.java]
⚠️. URL 요청주소에 .do(쩜두)를 붙이는 것은 관례이다.
@Controller
@RequestMapping("/rem")
public class RequestMappingController {
/**
* 뷰로 전달할 데이터가 있는 경우 ModelAndView return
* 어떤 뷰로 전달할지 viewName(경로) set
* */
@RequestMapping("/a.do")
public ModelAndView aa() {
System.out.println("a.do가 요청되었습니다.");
ModelAndView mv = new ModelAndView();
mv.addObject("message", "Spring 재밌다."); // ${requestScope.message}, ${message}
mv.setViewName("result"); // prefix + result + suffix, in servlet-context.xml
return mv;
}
/**
* 여러개의 요청을 하나의 메서드로 호출 가능
* 뷰로 전달할 데이터가 없는 경우에 String(뷰이름) return
* 뷰의 이름과 url 요청주소가 같은 경우에는 void return
* */
@RequestMapping(value = {"/b.do", "/c.do"})
public String aaaa() {
System.out.println("b.do, c.do 요청되었음");
return "result" // prefix + result + suffix, in servlet-context.xml
}
}
파라미터(parameter)와 null 바인딩
int 같은 경우는 null이 들어올 수 없으니 에러가 난다.
(int => Integer)
@Controller
@RequestMapping("/param")
public class ParameterController {
@RequestMapping("/a.do")
public String aa(String name, Integer age) {
System.out.println("name: " + name);
System.out.println("age: " + age);
return "result"
}
}
Controller별 공유가능한 (뷰에 전달할)데이터 설정
이 메서드를 포함한 Controller를 거치는 모든 요청들은, 뷰에서 ${별칭} 시용가능
@ModelAttribute("hobbys")
public List<String> hobbys() {
return Arrays.asList("골프", "낚시", "수영", "놀기", "먹기");
}
Ajax전용 annotation
(리턴하는 값이 그대로 브라우저에 전송)
@RestController: controller 내 모든 메서드의 return값을 응답객체로 본다.
(@Controller + @ResponseBody)
@RestController // @Controller + @ResponseBody
public class ResponseBodyController {
@RequestMapping("/responseBody.do)
public String aa() {
System.out.println("responseBody.do 요청입니다.");
return "Have a nice day";
}
@RequestMapping(value = "/responseBody2.do", produces = "text/html;charset=UTF-8") // WAS에서 프론트단으로 보낼때 한글 인코딩
public String bb() {
System.out.pritnln("responseBody2.do 요청입니다.");
return "리턴값이 그대로 브라우저에 전송";
}
}
'Backend > 스프링' 카테고리의 다른 글
[Spring] 파일 업로드와 파일 다운로드 설정 및 기능구현 (0) | 2023.05.05 |
---|---|
[Spring] 예외처리 @ExceptionHandler와 국한되지 않는 예외처리 SimpleMappingExceptionResolver (1) | 2023.05.05 |
[Spring] front Controller: DispatcherServlet(in web.xml)과 Spring MVC bean(in SPRING BEAN 설정문서.xml) (0) | 2023.05.02 |
[Spring] 관점지향프로그래밍 AOP와 Advice, 프록시 서버(Proxy Server) (0) | 2023.05.01 |
[Spring] 생성과 주입의 annotation, & 활성화 (0) | 2023.04.30 |