※ Spring Framework 구성요소
* DispathcerServlet
- Conroller의 대장(?), 서버로 들어오는 모든 요청을 처리해주는 첫번째 컨트롤러, 일종의 게이트웨이로 해석하고 있다.
-> Controller와 상호작용
-> View와 상호작용
* Annotation
(ex: @Conroller, @RestController, @RequestMapping...)
- Spring Framework가 호출하면 자동으로 객체를 생성
- MVC 패턴에서 C(Controller)를 맡고 있고, 모델과 뷰를 연결하는 역할을 수행
- Class: @Controller, @RestController
- Method: @RequestMapping
(예)
@Controller
public class sample{
@RequestMapping("/list") // list.jsp
public String list(){
/*
Business Logic, DB Code
*/
return "list";
}
// GET 방식
@RequestMapping("/user/get")
public String user(HttpServletRequest request){
String sNum = request.getParameter("num");
int num = Integer.parseInt(sNum);
}
@RequestMapping("/user/get")
public String user(@RequestParam("num") int num){
}
// http://localhost:8080/user/get/3
// 위의 url을 분석
@RequestMapping("/user/get/{num}")
public String user(@PathVariable("num") int num){
}
}
- Url 창에서 /list를 입력할 경우 list()가 실행됨
- 서버로 user 번호를 전달하는 방식(차이점: 데이터가 어디에 위치했는가?)
1) GET 방식: URL 주소에 참조하여 전달(Query String, url 끝에 ?로 변수를 넘기는 방식)
ex) http://localhost:8080/user/get?num=5
=> String sNum = request.getParameter("num"); 으로 get하는 방식
- SELECT 기능면에서 우수, 전송속도 우수
2) POST 방식: HTTP의 메시지 Body에 담아서 전송
- CREATE, UPDATE, DELETE 기능면에서 우수
- 보안 우수
- ajax로 post로 송신
@Component @Service @Controller @Repository |
- 구성요소 정의 - Service - Controller - Repsoitory(File I/O) |
@Autowired | - Dependency Injection(의존성 주입) - Controller에서 @Autowired를 사용하여 정의하면, 자동 객체 생성 - new 명령어 없이 객체 생성 ex) @Autowired private 클래스명 객체명; |
@RequestMapping @GetMapping @PostMapping |
- RequestMapping은 Get과 Post가 둘 다 가능한 넓은 범위의 Mapping - RequestMapping은 클래스와 메서드에 적용 가능 - GetMapping은 메서드에만 적용 가능 - 다음의 URL에 매핑 ex) @RequestMapping("/Index") |
@RequestParam | - URL 주소 뒤에 입력하는 변수를 get - getParameter()와 유사 ex) @RequestParam("URL 참조 변수 명") DataType 변수명 |
@PathVariable | - URL주소 뒤에 입력하는 변수를 찾아와서 바로 전환 ex) @PathVariable("URL 참조 변수 명") DataType 변수명 |
@ResponseBody | - Method에서 리턴되는 값이 View를 통해 출력되지 않고 HTTP Body에 작성 ex) public @ResponseBody DataType 함수명(){ return ~; } |
@ModelAttribute | - jsp 파일로 주고 받는 Model의 속성을 참조할 수 있음 ex) public DataType Method명(@ModelAttribute(Key) DataType Value){ } |
* RequestMapping
// http://localhost:8080/gugu/dan/5
@RequestMapping(value = "/gugu/dan/{n}", method = RequestMethod.GET)
public @ResponseBody String gugu4 (@PathVariable("n") int dan) {
String g = "";
for(int i = 1; i<=9 ; i++) {
g += String.format("%d * %d = %d<br>", dan, i, dan*i);
}
return g;
}
@RequestMapping(value, method)를 지정함으로서 GET, POST를 정할 수 있다.
* @RequestMapping, gugu.jsp 활용하여 구구단 출력
- 입력: http://localhost:8080/gugu/view/{n}
(Controller.java)
@RequestMapping("/gugu/dan/{n}")
public String gugu5 (@PathVariable("n") int n, Model m) {
String gugu = "";
for(int i = 1; i<=9 ; i++) {
gugu += String.format("%d * %d = %d<br>", n, i, n*i);
}
m.addAttribute("gugu", gugu);
return "gugu";
}
(gugu.jsp)
<%@ page contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<% //prefix="c"는 앞으로 쓰일 jstl 태그 앞에 c가 들어가야 한다는 것 %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>구구단 보기</title>
</head>
<body>
<h3>구구단 ${dan}단 보기</h3>
<div>
${gugu}
</div>
</body>
</html>
+ Model을 ModelMap으로 변경할 경우, addAttribute를 put으로 변경해야한다.
* Request 와 Model 의 관계
- Request.setAttribute() 는 Model.addAttribute()와 같은 기능을 수행
- Model
1) Model.addAttribute()
2) ModelMap.put()
3) ModelMap.addAttribute()
4) @ModelAttribute(Key) DataType VariableName
cf) Parameter: 외부에서 전달되는 데이터를 저장하는 변수
Attribute: 속성
Argument: Parameter 변수 안에 저장되는 실제 값
'프로그래밍' 카테고리의 다른 글
[MyBatis] ORM 프레임워크 활용(1) (0) | 2021.07.06 |
---|---|
[MySQL] With Recursive 문, 세션 변수 활용, Pagination (0) | 2021.07.06 |
[웹] Java Spring Framework 활용 (0) | 2021.06.25 |
[웹] JSP 예제(MySQL과 연동, 웹 브라우저 출력)(3) (0) | 2021.06.23 |
[웹] JSP 예제(MySQL과 연동, 웹 브라우저 출력)(2) (0) | 2021.06.23 |