spring - REST 02

오늘·2021년 6월 11일
0

웹 페이지 연습

목록 보기
33/35

REST 방식으로 URI 표현

REST 방식은 서버에 데이터 조회 뿐 아니라 추가, 수정, 삭제 작업을 요청하고 이때 HTTP 메서드를 이용한다

Http 메소드의 기능

REST 방식으로 요청하는 URI 형식

/작업명/기본키+메소드+데이터

  • 작업명 : 요청하는 작업의 종류
  • 기본키 : 요청하는 작업에 해당하는 대상의 기본키
  • 메소드 : 요청하는 기능
  • 데이터 : 기능 수행에 필요한 json 데이터

REST로 게시판 기능 관련 URI 만들기


실습하기

자바파일 위치

jsp 위치

ArticleVO.java

package com.myspring.pro29.ex03;

public class ArticleVO {
	private int articleNo;
	private String writer;
	private String title;
	private String content;
	
	// 기본 메소드
	public ArticleVO() {}
	
	public ArticleVO(int articleNo, String writer, String title, String content) {
		this.articleNo = articleNo;
		this.writer = writer;
		this.title = title;
		this.content = content;
	}

	// getter-setter
	public int getArticleNo() {
		return articleNo;
	}

	public void setArticleNo(int articleNo) {
		this.articleNo = articleNo;
	}

	public String getWriter() {
		return writer;
	}

	public void setWriter(String writer) {
		this.writer = writer;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}
	
	// toString
	@Override
	public String toString() {
		String info = "";
		info += "\n" + articleNo + "\n" + writer + "\n" + title + "\n" + content + "\n";
		return info;
	}
}

BoardController.java

앞에서 설명한 REST 방식으로 컨트롤러의 메소드 구현하기. 메소드 속성에 GET, Post, PUT, DELETE를 지정하여 기능을 정의한다

package com.myspring.pro29.ex03;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/boards")
public class BoardController {
	static Logger logger = LoggerFactory.getLogger(BoardController.class);
	
	// Get 방식으로 요청하기 때문에 모든 글의 정보를 조회한다
	// -> 전체 글을 조회하히
	@RequestMapping(value = "/all", method = RequestMethod.GET)
	public ResponseEntity<ArticleVO> listArticles() {
		logger.info("listArticles 메소드 호출");
		List<ArticleVO> list = new ArrayList<ArticleVO>();
		
		for(int i=0; i<10; i++) {
			ArticleVO vo = new ArticleVO();
			vo.setArticleNo(i);
			vo.setWriter("홍길동" + i);
			vo.setTitle("테스트입니다" + i);
			vo.setContent("새 상품을 소개합니다" + i);
			list.add(vo);
		}
		return new ResponseEntity(list, HttpStatus.OK);
	}
	
	
	// Get 방식으로 요청하면서 글 번호를 전달하기 때문에, 글 번호에 대한 글 정보를 조회
	// -> 선택한 글에 대한 자료만 가져오기
	@RequestMapping(value = "/{articleNo}", method = RequestMethod.GET)
	public ResponseEntity<ArticleVO> findArticle(
					@PathVariable("articleNo") Integer articleNo) {
		logger.info("findArticle 메소드 호출");
		
		ArticleVO vo = new ArticleVO();
		vo.setArticleNo(articleNo);
		vo.setWriter("이자바");
		vo.setTitle("테스트 중입니다~");
		vo.setContent("이자바의 글입니다");
		
		return new ResponseEntity(vo, HttpStatus.OK);
	}
	
	
	// post 방식으로 요청하기 때문에
	// 요청이 들어오면 json으로 전달되는 객체를 새 글로 추가한다
	@RequestMapping(value = "", method = RequestMethod.POST)
	public ResponseEntity<String> addArticle(@RequestBody ArticleVO articleVo) {
		ResponseEntity<String> resEntity = null;
		try {
			logger.info("addArticle 메소드 호출");
			logger.info(articleVo.toString());
			resEntity = new ResponseEntity<String>("ADD_SUCCEEDED", HttpStatus.OK);
		} catch (Exception e) {
			resEntity = new ResponseEntity<String>(e.getMessage(), HttpStatus.BAD_REQUEST);
		}
		return resEntity;
	}
	
	
	// put 방식으로 요청하기 때문에 articleNo에 대한 글을
	// json 방식으로 수정한다
	@RequestMapping(value = "/{articleNo}", method = RequestMethod.PUT)
	public ResponseEntity<String> modArticle(
			@PathVariable("articleNo")Integer articleNo, @RequestBody ArticleVO articleVo) {
		ResponseEntity<String> resEntity = null;
		try {
			logger.info("modArticle 메소드 호출");
			logger.info(articleVo.toString());
			resEntity = new ResponseEntity<String>("MOD_SECCEEDED", HttpStatus.OK);
		} catch (Exception e) {
			resEntity = new ResponseEntity<String>(e.getMessage(), HttpStatus.BAD_REQUEST);
		}
		return resEntity;
	}
	
	
	// Delete 방식으로 요청하기 때문에
	// 전달되는 articleNo에 대한 글을 삭제할 수 있다
	@RequestMapping(value = "/{articleNo}", method = RequestMethod.DELETE)
	public ResponseEntity<String> removeArticle (@PathVariable("articleNo") Integer articleNo) {
		ResponseEntity<String> resEntity = null;
		try {
			logger.info("removeArticle 메서드 호출합니다");
			logger.info(articleNo.toString());
			resEntity = new ResponseEntity<String>("REMOVE_SECCEEDED", HttpStatus.OK);
		} catch (Exception e) {
			resEntity = new ResponseEntity<String>(e.getMessage(), HttpStatus.BAD_REQUEST);
		}
		return resEntity;
	}
}

JOSNTest2.jsp

컨트롤러의 반환 값을 가져와서 josn으로 생성하기!

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"  isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"  %>

<c:set var="contextPath" value="${pageContext.request.contextPath}"  />
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JSONTest2</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>

<script>
$(function() {
	$("#checkJson").click(function() {
		var article = {
				<!-- 새로운 글 정보를 json으로 생성한다 -->
				articleNo:"114",
				writer:"김연아",
				title:"안녕하세요",
				content:"소개하는 글입니다"
		};
		$.ajax({
			<!-- 새로운 글 등록은 post 방식으로 요청하고 -->
			type:"POST",
			<!-- 새 글을 등록하는 메소드를 호출 -->
			url:"${contextPath}/boards",
            
   			type:"PUT",
			url:"${contextPath}/boards/114",
			
			contentType:"application/json",
			<!-- 글 정보를 json 형식으로 전송 -->
			data :JSON.stringify(article),
		    success:function (data,textStatus){
		    	alert(data);
			},
			error:function(data, textStatus){
				alert("에러가 발생했습니다")
			},
			complete:function(data, textStatus){
			}
		});//end ajax
	});
});
</script>
</head>
<body>
	<input type="button" id="checkJson" value="새글 쓰기" /><br><br>
	<div id="output"></div>
</body>
</html>

HomeController.java

에서 반환? 불러오는 걸 JOSNTest2로 변경해준다

package com.myspring.pro29;

import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


//@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		
		return "JSONTest2";
	}
	
}package com.myspring.pro29;

import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		
		return "JSONTest2";
	}
}

실행

오류가 없어서 놀랐다. http://localhost:8700/pro29/boards/all 로 요청했고, 아래와 같이 전체 글 정보가 전송되어 출력되었다.

http://localhost:8700/pro29/boards/144로 요청 시 에러. 어쩐지 수월하다 했다 -> 수정 하니 해당 글만 제대로 출력

http://localhost:8700/pro29/ 으로 요청하면 jsp에 작성해줬던 버튼이 출력되고

버튼을 누르니 에러가 발생 -> 코드에서 빠진 부분 있어서 다시 수정
다시 버튼 클릭하니 수정이 완료되었다는 팝업이 출력

콘솔 확인하니 script로 적어줬던 내용대로 출력된 것을 확인할 수 있었다


0개의 댓글

관련 채용 정보