반응형
하나의 요청 URL에 대해 HTTP GET 요청과 POST요청을 한 개의 컨트롤러에서 처리해 줘야 할때가 생긴다.
예를들어 GET 요청이 들어오면 글쓰기 폼을 보여주고, POST 요청이 들어오면 글쓰기 폼 전송을 처리한다 가정한다.
내용을 저장해 사용할 set get 메소드를 만든다.
private String title; // 변수 생성
private String content;
private int parentId;
// set get메소드
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
....... set get..
// 프린팅될 내용을 [content = 000, parentId = 000, title = 000]처럼 출력하기위해 Override 오버라이딩시킬 to String .
@Override
public String toString() {
return "NewArticleCommand [content=" + content + ", parentId="
+ parentId + ", title=" + title +"]";
}
dispatcher-servlet.xml
<bean id="newArticleController" class="madvirus.spring.controller.NewArticleController"
p:articleService-ref="articleService" />
<bean id="articleService" class="madvirus.spring.service.ArticleService" />
컨트롤러
package madvirus.spring.controller;
import madvirus.spring.service.ArticleService;
import madvirus.spring.service.NewArticleCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
// 클래스에 맵핑을 걸고 컨트롤러로 지정한다.
@Controller
@RequestMapping("/article/newArticle.do")
public class NewArticleController {
// 필요한 의존 객체의 타입에 해당하는 빈을 찾도록 Autowired을 지정해준다.
// 우선 값은 null...
@Autowired
private ArticleService articleService;
// form의내용을 GET방식의 메소드로처리
@RequestMapping(method = RequestMethod.GET)
public String form() {
return "article/newArticleForm";
}
// submit의 내용을 POST방식의 메소드로 처리
@RequestMapping(method = RequestMethod.POST)
// ModelAttribute는 이름을 재지정해준다.
// 들어오는 NewArticleCommand의 값을 받아서 article/newArticleSubmitted에 리턴시켜준다.
public String submit(@ModelAttribute("command") NewArticleCommand command) {
articleService.writeArticle(command); // sysout로 값이 들어왔는지 알아보기위함.
return "article/newArticleSubmitted";
}
// 클래스에 멤버 변수를 지정
public void setArticleService(ArticleService articleService) {
this.articleService = articleService;
}
}
ArticleService
public class ArticleService { // 잘 등록이 되는지 프린팅으로 확인할거고
public void writeArticle(NewArticleCommand command) {
System.out.println("신규 게시글 등록: " + command);
}
}
Form 과 Submitted jsp를 만든다.
처리 결과.


반응형
'Java > SPRING' 카테고리의 다른 글
스프링 프레임워크 [Spring Framework] MVC 컨트롤러(Controller) 메서드의 파라미터 타입 (0) | 2021.12.22 |
---|---|
스프링 프레임워크 [Spring Framework] MVC 커맨드(Command) 객체로 List 받기 (0) | 2021.12.22 |
자바[SPRING] MVC패턴 Hello.do 기본기 (0) | 2021.12.21 |
스프링 프레임워크 [Spring Framework] MVC 흐름 및 구성 요소 (0) | 2021.12.21 |
스프링 프레임워크[Spring Framework]란 (0) | 2021.12.21 |