API 실습
in Web Dev on Java Spring
Maven project - org.apache.maven.archetype - webapp 타입의 프로젝트 만들어준다.
라이브러리 추가
- mysql
- json 라이브러리
- servlet- api
- jstl
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>kr.or.connect</groupId> <artifactId>webapiexam</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>webapiexam Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <!-- web.xml 파일을 삭제해도 eclipse에서 오류가 발생하지 않는다. --> <failOnMissingWebXml>false</failOnMissingWebXml> </properties> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.45</version> </dependency> <!-- json 라이브러리 databind jackson-core, jackson-annotaion에 의존성이 있다. --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.4</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>webapiexam</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.6.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
추가 후, maven에 update project 눌러준다.
navigator에 main 안, java 폴더 만들어준다. 3.1로 버전 바꿔준다.
실습 - 롤 객체 하나 받아오기
Servlet을 만들 때, URL mapping 도 바꿀 수 있고, POST나 GET function 만들 수 있다.
package kr.or.connect.webapiexam.api;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import kr.or.connect.jdbcexam.dao.RoleDao;
import kr.or.connect.jdbcexam.dto.Role;
/**
* Servlet implementation class RoleById
*/
@WebServlet("/roles/*") //어떤 문자든지 모두 올 수 있다.
public class RoleById extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public RoleById() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setCharacterEncoding("utf-8");
response.setContentType("application/json");
String pathInfo = request.getPathInfo();
String[] pathParts = pathInfo.split("/");
String idStr = pathParts[1];
int id = Integer.parseInt(idStr);
RoleDao dao = new RoleDao();
Role role = dao.getRole(id);
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(role);
PrintWriter out = response.getWriter();
out.println(json);
out.close();
}
}
response의 객체의 setCharacterEncoding, setContentType을 사용해 설정한다.
- request 객체로 url info를 가져와 url의 role id 정보를 가져온다.
- RoleDao 객체의 getRole(id)로 role 객체를 가져온다.
- ObjectMapper 객체의 writeValueAsString(role)로 json 스트링을 가져온다.
- response.getWriter로 PrintWriter 객체를 가져온다.
- PrintWriter 객체로 json 정보를 출력한다.
실습 - 롤 리스트 받아오기
@WebServlet("/Roles")
public class RolesServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public RolesServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
response.setCharacterEncoding("utf-8");
response.setContentType("application/json");
RoleDao dao=new RoleDao();
List<Role> list = dao.getRoles();
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(list);
PrintWriter out = response.getWriter();
out.print(json);
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}