SampleControllerTests.java
package com.jjundol.controller;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.google.gson.Gson;
import com.jjundol.domain.Ticket;
import lombok.Setter;
import lombok.extern.log4j.Log4j;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration({
"file:src/main/webapp/WEB-INF/spring/root-context.xml",
"file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml"})
@Log4j
public class SampleControllerTests {
@Setter(onMethod_ = @Autowired)
private WebApplicationContext ctx;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(ctx).build();
}
@Test
public void testConvert() {
Ticket ticket = new Ticket();
ticket.setBon(123);
ticket.setGrade("Admin");
ticket.setOwner("AAA");
String jsonStrTicket = new Gson().toJson(ticket);
log.info("testConvert.... : " + jsonStrTicket);
// testConvert.... : {"bon":123,"owner":"AAA","grade":"Admin"}
try {
mockMvc.perform(post("/sample/ticket")
.contentType(MediaType.APPLICATION_JSON)
.content(jsonStrTicket))
.andExpect(status().is(200));
// /sample/ticket으로 JSON데이터를 전달, Gson : Java객체 -> JSON
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
SampleController.java
- @RestController : 해당 클래스는 REST 처리를 해주는 Controller임을 지정
- producer 속성 : 처리 결과로 반환해줄 데이터의 형식 지정
- ResponseEntity : 데이터 반환시 HTTP 상태값도 같이 반환하기 위한 용도
- @PathVariable : @GetMapping의 value의 { } 에 있는 내용을 파라미터로 받도록 처리
- @RequestBody() : json 형태의 데이터를 java 객체의 형태로 변환시켜줌
package com.jjundol.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.jjundol.domain.SampleVO;
import com.jjundol.domain.Ticket;
import lombok.extern.log4j.Log4j;
@RestController
@RequestMapping("/sample")
@Log4j
public class SampleController {
// /sample/getText
@GetMapping(value = "/getText", produces = "text/plain; charset=UTF-8")
public String getText() {
log.info("MIME TYPE: " + MediaType.TEXT_PLAIN_VALUE);
return "안녕하세요!?";
}
// /sample/getSample
@GetMapping(value = "/getSample", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE,
MediaType.APPLICATION_XML_VALUE })
public SampleVO getSample() {
return new SampleVO(112, "스타", "로드");
}
// /sample/getSample2
@GetMapping(value = "/getSample2") // produces 속성은 생략가능
public SampleVO getSample2() {
return new SampleVO(113, "스타2", "로드2");
}
// /sample/getMap
@GetMapping(value = "/getMap")
public Map<String, SampleVO> getMap() {
Map<String, SampleVO> map = new HashMap<String, SampleVO>();
map.put("First", new SampleVO(114, "베이비", "그루트"));
return map;
}
// /sample/check?height=177&wieht=65
@GetMapping(value = "/check", params = { "height", "weight" })
public ResponseEntity<SampleVO> check(Double height, Double weight) {
SampleVO sample = new SampleVO(0, ""+height, ""+weight);
ResponseEntity<SampleVO> result;
if(height < 150) {
result = ResponseEntity.status(HttpStatus.BAD_GATEWAY).body(sample);
} else {
result = ResponseEntity.status(HttpStatus.OK).body(sample);
}
return result;
}
// /sample/product/bag/789
@GetMapping(value = "/product/{cat}/{pid}")
public String[] getPath(@PathVariable("cat") String cat, @PathVariable("pid") String pid) {
return new String[] {cat, pid};
}
// /sample/ticket, json데이터를 처리(@RequestBody(json -> 객체))
@PostMapping(value = "/ticket")
public Ticket convert(@RequestBody Ticket ticket) {
// JSON > 객체
log.info("convert....Ticket" + ticket);
// convert....TicketTicket(bon=123, owner=AAA, grade=Admin)
return null;
}
}
'WEB > spring' 카테고리의 다른 글
Maven 프로젝트 생성 (0) | 2020.04.28 |
---|---|
AOP예시 (0) | 2020.03.21 |
AOP (0) | 2020.03.21 |
HikariCP 커넥션 풀 (0) | 2019.12.30 |
이클립스 프로젝트 JDBC 연결 (0) | 2019.12.30 |