Jetty RESTFul Web Service
If you are working on spring standalone project and wanted to expose this applicaiton as web serivce you could use Jetty to expose it. Using Jetty it’s very easy just you will have to add few line of code into your existing project. Please follow steps below:
- Create maven project name: JettyApplication as below is shonw complete project strucure after all configuration:
- pom.xml:
<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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javahonk</groupId> <version>0.0.1</version> <artifactId>JettyApplication</artifactId> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <org.springframework.version>4.1.5.RELEASE</org.springframework.version> </properties> <dependencies> <!-- Jetty/Jersey dependency --> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-server</artifactId> <version>1.9</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-json</artifactId> <version>1.9</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> <version>1.8.8</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.8.8</version> </dependency> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-server</artifactId> <version>8.1.12.v20130726</version> </dependency> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-servlet</artifactId> <version>8.1.12.v20130726</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.1</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.9</version> </dependency> <!-- Apache HTTP client --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3.6</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.16</version> </dependency> </dependencies> </project>
- spring-context.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd"> <context:annotation-config /> <context:component-scan base-package="com.javahonk" /> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:jetty/Jetty.properties</value> </list> </property> <property name="ignoreUnresolvablePlaceholders" value="true"/> </bean> <bean id="jettyService" class="com.javahonk.JettyService" /> <bean id="messageHandler" class="com.javahonk.MessageHandler" /> </beans>
- Jetty.properties:
#jetty server config web.port=8080
- JettyService.java:
package com.javahonk; import javax.annotation.PostConstruct; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.eclipse.jetty.server.Server; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @SuppressWarnings("restriction") public class JettyService { @Value("${web.port}") private int port; @Autowired private MessageHandler handler; private static final Logger logger = LogManager.getLogger(JettyService.class.getName()); @PostConstruct public void init() throws Exception { logger.info("starting jetty server at port {}", port); Server server = new Server(port); server.setHandler(handler); server.start(); } }
- MessageHandler.java:
package com.javahonk; import java.io.BufferedReader; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.HttpMethod; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.AbstractHandler; public class MessageHandler extends AbstractHandler { private static final Logger logger = LogManager.getLogger(MessageHandler.class.getName()); private static String URL_OPTION_EXPIRY = "/app/javahonk/test"; public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { logger.info("HTTP remote box- " + request.getRemoteAddr()); logger.info("HTTP request- " + request.getPathInfo()); if (request.getMethod().equals(HttpMethod.POST)) { StringBuilder sb = new StringBuilder(); BufferedReader bufferedReader = null; try { bufferedReader = request.getReader(); char[] charBuffer = new char[128]; int bytesRead; while ((bytesRead = bufferedReader.read(charBuffer)) != -1) sb.append(charBuffer, 0, bytesRead); if (request.getPathInfo().equals(URL_OPTION_EXPIRY)) { System.out.println("Post request value: -->"+sb.toString()); } else { logger.error("Unable to process request from URL [ {} ]" , request.getPathInfo()); } } catch (Exception e) { logger.error("Error :", e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e) { logger.error("Error :", e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } } } response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); } }
- HttpClientPost.java:
package com.javahonk; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.impl.client.HttpClientBuilder; public class HttpClientPost { public static void main(String[] args) { postHttpPost("http://localhost:8080/app/javahonk/test", new String("Java Honk").getBytes()); } private static void postHttpPost(String url, byte[] message) { try { HttpClient httpClient = HttpClientBuilder.create().build(); HttpPost postRequest = new HttpPost(url); ByteArrayEntity entity = new ByteArrayEntity(message); entity.setContentType(MediaType.APPLICATION_OCTET_STREAM); postRequest.setEntity(entity); HttpResponse response = httpClient.execute(postRequest); if (response.getStatusLine().getStatusCode() != Response.Status.OK .getStatusCode()) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } BufferedReader br = new BufferedReader(new InputStreamReader( (response.getEntity().getContent()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
- MainApp.java:
package com.javahonk; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args){ ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml"); System.out.println(context); } }
- Now to start this application start MainApp.java class as java application you will below output on console:
- To test this appication I have written class: HttpClientPost.java strat this class as java application which will send one post parameter “Java Honk” in request to Jetty and once handler receive request it will print out put on console as below:
- That’s it. For more information please visit here
Download Project: JettyApplication