JSP 페이지:
write.jsp는 사용자로부터 기사 정보를 입력받는 양식을 제공합니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div>
<h3>기사 작성하기</h3>
<form action="${contextPath}/register.do" method="post">
<div>
<label for="articleNo">기사번호</label>
<input type="text" id="articleNo" name="articleNo">
</div>
<div>
<label for="title">기사제목</label>
<input type="text" id="title" name="title">
</div>
<div>
<label for="content">기사내용</label>
<input type="text" id="content" name="content">
</div>
<div>
<button type="submit">기사작성완료</button>
</div>
</form>
</div>
</body>
</html>
|
cs |
VO (Value Object) 클래스:
ArticleVo 클래스는 기사 정보를 저장하기 위한 데이터 객체로 사용됩니다.
이 클래스의 필드는 기사 번호(articleNo), 제목(title), 내용(content)을 나타냅니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
package com.gdu.app04.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@Data
public class ArticleVo {
private int articleNo;
private String title;
private String content;
}
|
cs |
컨트롤러 클래스:
MvcController 클래스는 Spring MVC에서 요청을 처리하는 컨트롤러 역할을 합니다.
여러 요청 매핑 메서드를 포함하고 있으며, 각 메서드는 특정 URL 경로로 들어오는 요청을 처리합니다.
/write.do : 기사 작성 양식을 제공하는 페이지로 이동하는 요청을 처리합니다.
/register.do : 기사를 등록하고 결과를 보여주는 페이지로 이동하는 요청을 처리합니다. 이 메서드는 다양한 방법으로 기사 정보를 받아와서 모델에 저장하고 결과 페이지로 이동합니다.
@ModelAttribute 어노테이션:
register4 메서드에서 @ModelAttribute 어노테이션을 사용하여 ArticleVo 객체를 매개변수로 받아 모델에 저장합니다.
이를 통해 기사 정보를 JSP 페이지에서 사용할 수 있게 됩니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
package com.gdu.app04.ctrl;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.gdu.app04.vo.ArticleVo;
@Controller
public class MvcController {
// DispatcherServlet(servlet-context.xml)에서 ViewResolver를 제거했으므로 JSP의 전체 경로를 모두 작성해야 한다.
@RequestMapping(value="/", method=RequestMethod.GET)
public String main() {
return "/WEB-INF/main.jsp";
}
@RequestMapping(value="/write.do", method=RequestMethod.GET)
public String write() {
return "/WEB-INF/article/write.jsp";
}
// @RequestMapping(value="/register.do", method=RequestMethod.POST)
public String register(HttpServletRequest request, Model model) {
int articleNo = Integer.parseInt(request.getParameter("articleNo"));
String title = request.getParameter("title");
String content = request.getParameter("content");
model.addAttribute("articleNo", articleNo);
model.addAttribute("title", title);
model.addAttribute("content", content);
return "/WEB-INF/article/result.jsp";
}
//@RequestMapping(value="/register.do", method=RequestMethod.POST)
public String register2(@RequestParam(value="articleNo") int articleNo
,@RequestParam(value="title") String title
,@RequestParam(value="content") String content
, Model model) {
ArticleVo vo = new ArticleVo(articleNo, title, content);
model.addAttribute("vo", vo);
return "/WEB-INF/article/result.jsp";
}
//@RequestMapping(value="/register.do", method=RequestMethod.POST)
public String register3(ArticleVo vo) {
return "/WEB-INF/article/result.jsp";
}
@RequestMapping(value="/register.do", method=RequestMethod.POST)
public String register4(@ModelAttribute(value="atcVo") ArticleVo vo) {
return "/WEB-INF/article/result.jsp";
}
}
|
cs |
result.jsp는 입력된 기사 정보를 표시합니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div>
<div>${articleNo}</div>
<div>${title}</div>
<div>${content}</div>
</div>
<hr>
<div>
<div>${vo.articleNo}</div>
<div>${vo.title}</div>
<div>${vo.content}</div>
</div>
<hr>
<div>
<div>${articleVo.articleNo}</div>
<div>${articleVo.title}</div>
<div>${articleVo.content}</div>
</div>
<hr>
<div>
<div>${atcVo.articleNo}</div>
<div>${atcVo.title}</div>
<div>${atcVo.content}</div>
</div>
</body>
</html>
|
cs |
=======================================================================
redirect 하는 방법
1. return "redirect:이동경로";
public String add() {
return "redirect:/list.do";
}
2. location.href='이동경로';
public void add(HttpServletResponse response){
PrintWriter out = response.getWriter();
out.println("<script>");
out.println("location.href='이동경로'");
out.println("</script>");
}
redirect 이동경로
1. 반드시 URLMapping값을 작성한다.
2. 이동할 JSP 경로를 작성할 수 없다.
▶add 메서드
URL 매핑: /faq/add.do
HTTP 메서드: POST
요청 파라미터로 title과 content를 받아옵니다.
addResult 변수에 따라 redirect 경로를 생성합니다. addResult가 빈 문자열이면 0, 아니면 1로 설정됩니다.
redirect:/faq/list.do?addResult=와 addResult 값을 조합하여 FAQ 목록 페이지로 redirect합니다.
▶list 메서드
URL 매핑: /faq/list.do
HTTP 메서드: GET
addResult를 모델에 추가하여 FAQ 목록 페이지로 전달합니다.
▶add2 메서드
URL 매핑: /faq/add.do
HTTP 메서드: POST
addResult를 Flash attribute로 저장합니다. Flash attribute는 한 번만 읽을 수 있는 데이터이며, redirect 후에는 사라집니다.
FAQ 목록 페이지로 redirect합니다.
▶list2 메서드
URL 매핑: /faq/list.do
HTTP 메서드: GET
FAQ 목록 페이지를 반환합니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
package com.gdu.app03.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
public class MyController05 {
//@RequestMapping(value="/faq/add.do", method=RequestMethod.POST)
public String add(HttpServletRequest request) {
// 요청 파라미터
String title = request.getParameter("title");
String content = request.getParameter("content");
// title이 빈 문자열이면 add 실패로 가정(DB 처리할 때 insert 성공 1, 실패는 0이다)
int addResult = title.isEmpty() ? 0 : 1;
// addResult를 가지고 faq 목록보기로 이동
return "redirect:/faq/list.do?addResult=" + addResult;
}
//@RequestMapping(value="/faq/list.do", method=RequestMethod.GET)
public String list(@RequestParam(value="addResult", required=false) String addResult, Model model) {
model.addAttribute("addResult", addResult);
// ViewResolver prefix : /WEB-INF/views/
// ViewResolver suffix : .jsp
return "faq/list"; // /WEB-INF/views/faq/list.jsp
}
@RequestMapping(value="/faq/add.do", method=RequestMethod.POST)
public String add2(HttpServletRequest request
, RedirectAttributes redirectAttributes) { // redirect 상황에서 값을 전달할 때 사용한다.
// 요청 파라미터
String title = request.getParameter("title");
// title이 빈 문자열이면 add 실패
int addResult = title.isEmpty() ? 0 : 1;
// faq 목록보기로 redirect 할 때 addResult를 "flash attribute"로 전달하기
redirectAttributes.addFlashAttribute("addResult", addResult);
// faq 목록보기로 redirect
return "redirect:/faq/list.do";
}
@RequestMapping(value="/faq/list.do", method=RequestMethod.GET)
public String list2() {
return "faq/list";
}
}
|
cs |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
var addResult = '${addResult}'; // var addResult ='1'; add 성공
// var addResult ='0'; add 실패
// var addResult =''; add와 상관없음
if(addResult !== ''){
if(addResult === '1'){
alert('add 성공했습니다');
}else {
alert('add 실패했습니다');
}
}
</script>
</head>
<body>
faq 목록
</body>
</html>
|
cs |
'코딩기록 저장소 🐕 > spring(JPA)🌱' 카테고리의 다른 글
Spring DI 2 (0) | 2023.10.05 |
---|---|
Spring DI (0) | 2023.10.04 |
Spring core 의존관계주입 자동 주입 (김영한의 스프링) (0) | 2023.10.01 |
Spring core 스프링 컨테이너, 컴포넌트스캔(김영한의 스프링) (0) | 2023.09.27 |
Spring core 스프링 컨테이너, 싱글톤컨테이너(김영한의 스프링) (0) | 2023.09.27 |