그래도 개발자일 때 좋았다

Simple RESTful Web Services with Jersey 본문

Development/Java

Simple RESTful Web Services with Jersey

실러캔스 2012. 9. 10. 14:55

There are a lot of ways to implement RESTful web services.

I am going to explain how to implemnet a simple RESTful web service with Jersey, Java, and HSQLDB.

(With my best effort and knowledge)

 

1. RESTful Web Service

   : REpresentational State Transfer(REST) is a style of software architecture for distributed systems such as the World Wide Web. (http://en.wikipedia.org/wiki/Representational_state_transfer)

 

2. Preparation

- Java JDK 1.6.0_33

- Eclipse IDE for Java EE Developers, Indigo

- Jersey Archive 1.13

  => asm-3.1.jar

  => jackson-core-asl-1.9.2.jar

  => jackson-jaxrs-1.9.2.jar

  => jackson-mapper-asl-1.9.2.jar

  => jackson-xc-1.9.2.jar

  => jersey-client-1.13.jar

  => jersey-core-1.13.jar

  => jersey-json-1.13.jar

  => jersey-server-1.13.jar

  => jersey-servlet-1.13.jar

  => jettison-1.1.jar

  => jsr311-api-1.1.1.jar

- HSQLDB 2.2.9

- Apache Tomcat 7.0

 

3. Create a new Dynamic Web Project on Eclipse.

- File -> New -> Web -> Dynamic Web Project

 

4. Put Jersey libraries and HSQL JDBC Driver library into the project.

- ex> WebContent\WEB-INF\lib

 

5. web.xml

<servlet>
   <servlet-name>RESTTest</servlet-name>
   <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
   <init-param>
      <param-name>com.sun.jersey.config.property.packages</param-name>
      <param-value>test</param-value> <!-- this is a package name -->
   </init-param>
   <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
   <servlet-name>RESTTest</servlet-name>
   <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

 

 

6. Examples of Java

  : You can ignore </testvo> tags. They appear becase of "List<TestVO>. I'll find a solution one day.

 

- TestSetVO.java : A set of TestVO

package test.rest.vo;

import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class TestSetVO {
	private int          resultCode;
	private String       msg;
	private List test;
	
	public int getResultCode() {
		return resultCode;
	}
	public void setResultCode(int resultCode) {
		this.resultCode = resultCode;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	public List getTest() {
		return test;
	}
	public void setTest(List test) {
		this.test = test;
	}
}

 

- TestVO.java : A set of properties

package test.rest.vo;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class TestVO {
	private int    testNo;
	private String testId;
	
	public int getTestNo() {
		return testNo;
	}
	public void setTestNo(int testNo) {
		this.testNo = testNo;
	}
	public String getTestId() {
		return testId;
	}
	public void setTestId(String testId) {
		this.testId = testId;
	}
}

 

- TestService.java : Service Interface

package test.rest.service;

import test.rest.vo.TestSetVO;
import test.rest.vo.TestVO;

public interface TestService {
	public TestSetVO getTestList() throws Exception;
	public TestSetVO getTestById() throws Exception;
	public int addTest(TestVO testVO) throws Exception;
}

 

- TestServiceImpl.java : Service Implementation Class

package test.rest.service;

import test.rest.dao.TestServiceDAO;
import test.rest.vo.TestSetVO;
import test.rest.vo.TestVO;

public class TestServiceImpl implements TestService {
	private TestServiceDAO testServiceDAO = new TestServiceDAO();
	
	@Override
	public TestSetVO getTestList() throws Exception {
		return testServiceDAO.getTestList();
	}

	@Override
	public TestSetVO getTestById(String testId) throws Exception {
		return testServiceDAO.getUserById(testId);
	}

	@Override
	public int addTest(TestVO testVO) throws Exception {
		return testServiceDAO.addUser(testVO);
	}

}

 

- TestServiceDAO.java : Providing database result

package test.rest.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import test.common.DBConnector;
import test.rest.vo.TestSetVO;
import test.rest.vo.TestVO;

public class TestServiceDAO {
	public TestSetVO getTestList() throws Exception {
		StringBuffer sqlBuf = new StringBuffer();
		sqlBuf.append("SELECT test_no\n");
		sqlBuf.append("     , test_id\n");
		sqlBuf.append("  FROM test\n"   );
		
		Connection con = DBConnector.getConnection();
		Statement stmt = con.createStatement();
		ResultSet rs = stmt.executeQuery(sqlBuf.toString());
		List testList = new ArrayList();
		
		while (rs.next()) {
			TestVO testVO = new TestVO();
			testVO.setTestNo(rs.getInt("test_no"));
			testVO.setTestId(rs.getString("test_id"));
			testList.add(testVO);
		}
		
		rs.close();
		stmt.close();
		con.close();
		
		TestSetVO testSetVO = new TestSetVO();
		testSetVO.setResultCode(1);	// Assuming, "1" is success.
		testSetVO.setMsg("Total Count : " + testList.size());
		testSetVO.setTest(testList);
		
		return testSetVO;
	}
	
	public TestSetVO getUserById(String testId) throws Exception {
		StringBuffer sqlBuf = new StringBuffer();
		sqlBuf.append("SELECT test_no\n"    );
		sqlBuf.append("     , test_id\n"    );
		sqlBuf.append("  FROM test\n"       );
		sqlBuf.append(" WHERE test_id = ?\n");
		
		Connection con = DBConnector.getConnection();
		PreparedStatement pstmt = con.prepareStatement(sqlBuf.toString());
		pstmt.setString(1, testId);
		ResultSet rs = pstmt.executeQuery();
		List testList = new ArrayList();
		
		while (rs.next()) {
			TestVO testVO = new TestVO();
			testVO.setTestNo(rs.getInt("test_no"));
			testVO.setTestId(rs.getString("test_id"));
			testList.add(testVO);
		}
		
		rs.close();
		pstmt.close();
		con.close();
		
		TestSetVO testSetVO = new TestSetVO();
		testSetVO.setResultCode(1);	// Assuming, "1" is success.
		testSetVO.setMsg("Total Count : " + testList.size());
		testSetVO.setTest(testList);
		
		return testSetVO;	
	}
	
	public int addUser(TestVO testVO) throws Exception {
		StringBuffer sqlBuf = new StringBuffer();
		sqlBuf.append("INSERT INTO test\n");
		sqlBuf.append("VALUES (?, ?)");
		
		Connection con = DBConnector.getConnection();
		PreparedStatement pstmt = con.prepareStatement(sqlBuf.toString());
		pstmt.setInt   (1, testVO.getTestNo());
		pstmt.setString(2, testVO.getTestId());
		
		int result = pstmt.executeUpdate();
		
		pstmt.close();
		con.close();
		
		return result;
	}
}

 

- TestRest.java : Providing RESTful Service

package test.rest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import test.rest.service.TestService;
import test.rest.service.TestServiceImpl;
import test.rest.vo.TestSetVO;
import test.rest.vo.TestVO;

@Path("/test")
public class TestRest {
	private TestService testService = new TestServiceImpl();
	
	@GET
	@Produces(MediaType.TEXT_XML)
	@Path("/add/{testNo}={testId}")
	public TestSetVO addTest(@PathParam("testNo") final int testNo
			, @PathParam("testId") final String testId) {
		TestSetVO testSetVO = new TestSetVO();
		if (testNo < 0) {
			testSetVO.setResultCode(-1); // Assuming, "-1" is failure.
			testSetVO.setMsg("invalid parameter : testNo");
			return testSetVO;
		}
		
		if ("".equals(testId) || testId == null) {
			testSetVO.setResultCode(-1); // Assuming, "-1" is failure.
			testSetVO.setMsg("invalid parameter : testId");
			return testSetVO;
		}
		
		try {
			TestVO testVO = new TestVO();
			testVO.setTestNo(testNo);
			testVO.setTestId(testId);
			testService.addTest(testVO);
			
			testSetVO.setResultCode(1); // Assuming, "1" is success.
			testSetVO.setMsg("success");
		} catch (Exception e) {
			testSetVO.setResultCode(-1);
			testSetVO.setMsg(e.getMessage());
		}
		
		return testSetVO;
	}
	
	@GET
	@Produces(MediaType.TEXT_XML)
	@Path("/get")
	public TestSetVO getTestList() {
		TestSetVO testSetVO = new TestSetVO();
		try {
			testSetVO = testService.getTestList();
		} catch (Exception e) {
			testSetVO.setResultCode(-1); // Assuming, "-1" is failure.
			testSetVO.setMsg(e.getMessage());
		}
		
		return testSetVO;
	}
	
	@GET
	@Produces(MediaType.TEXT_XML)
	@Path("/get/{testId}")
	public TestSetVO getTestById(@PathParam("testId") final String testId) {
		TestSetVO testSetVO = new TestSetVO();
		try {
			testSetVO = testService.getTestById(testId);
		} catch (Exception e) {
			testSetVO.setResultCode(-1); // Assuming, "-1" is failure.
			testSetVO.setMsg(e.getMessage());
		}
		
		return testSetVO;
	}
}

 

- DBConnector.java : Providing a temporary DB connection

package test.common;

import java.sql.Connection;
import java.sql.DriverManager;

public class DBConnector {

	public static Connection getConnection() throws Exception {
		Class.forName("org.hsqldb.jdbc.JDBCDriver");
		Connection con = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/hsql", "SA", "");
		return con;
	}
}

 

7. Create a table.

CREATE TABLE TEST
(    TEST_NO INTEGER PRIMARY_KEY NOT NULL
   , TEST_ID VARCHAR(10) PRIMARY KEY NOT NULL
)

 

8. Test

- Run HSQLDB.

- Start a server.

- Launch your favorite web browser.

- Type below url in sequence.

 : http://localhost:8080/rest/test/get => It might return no result.

   http://localhost:8080/rest/test/add/10=test => It might return success.

   http://localhost:8080/rest/test/add/10=test => It might return error, PK constraint.

   http://localhost:8080/rest/test/add/20=test2 => It might return success.

   http://localhost:8080/rest/test/get =>It might return two results.

   http://localhost:8080/rest/test/get/test => It might return a result.

   http://localhost:8080/rest/test/get/test3 => It might return no result.

- Just type whatever you want to do.

 

9. Any Question?

Good luck :)

'Development > Java' 카테고리의 다른 글

Java DNS TTL 관리  (0) 2018.03.19
JCommander를 통한 JAR 실행 Parameter 관리  (0) 2017.03.27
Java Rome Library를 이용한 RSS Feed 수집  (0) 2017.02.13
Comments