DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Aggregating REST APIs Calls Using Apache Camel
  • How to Develop Microservices With Spring Cloud and Netflix Discovery
  • Building a REST Service That Collects HTML Form Data Using Netbeans, Jersey, Apache Tomcat, and Java
  • Spring Boot - How To Use Native SQL Queries | Restful Web Services

Trending

  • Proactive Security in Distributed Systems: A Developer’s Approach
  • How to Format Articles for DZone
  • Building a Real-Time Change Data Capture Pipeline With Debezium, Kafka, and PostgreSQL
  • Using Python Libraries in Java
  1. DZone
  2. Coding
  3. Frameworks
  4. Add REST to Standalone Java with Jetty and Spring WebMVC

Add REST to Standalone Java with Jetty and Spring WebMVC

I’m going to start by discussing the Spring WebMVC configuration and move on from there in future posts.

By 
Alan Hohn user avatar
Alan Hohn
·
Oct. 07, 13 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
36.2K Views

Join the DZone community and get the full member experience.

Join For Free

There are a lot of tutorials out there about providing REST web services in a servlet container by building and deploying a WAR. There are also cases where someone is looking to put a REST interface on an existing Java application. In that case it isn’t always possible to turn the application into a WAR or EAR and adding a servlet container as a separate process just adds a layer of complexity.

At the time, I didn’t see a good example that brought all the pieces together for a standalone Java application that exposes REST interfaces using Spring WebMVC. So I put together a small example. If I’d looked harder, I would have found one, but now I’ve written it and get to share it.

Even though the example is small, there are a number of moving parts, and I want to do them justice. So I’m going to start by discussing the Spring WebMVC configuration and move on from there in future posts.

One other thing I like about this example is that we can build up everything required to actually make a WAR, but then run it as a standalone Java application. I’ve always thought that to be one of the coolest things about Jenkins and I think it’s a useful technique in general.

To begin, in order to make a webapp, we’ll add a web.xml file. With Servlet 3.0 we could avoid having a web.xml, but it’s nice to have one as it keeps us compatible with Servlet 2.x. We’re using Maven, so it goes insrc/main/webapp/WEB-INF.

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC 
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 
 "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>

  <display-name>REST API</display-name>
  <description>Sample Spring WebMVC REST API</description>

  <servlet>
    <servlet-name>rest</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>2</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>rest</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>

</web-app>

There’s not much to this configuration. The main thing to note is that we’re not implementing a servlet ourselves; we’re letting Spring WebMVC’s DispatcherServlet do the work. The DispatcherServlet does exactly what it sounds like: it takes in requests and figures out where they should go.

In the same WEB-INF directory we now need to configure Spring WebMVC. To do this we need a file called rest-servlet.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:mvc="http://www.springframework.org/schema/mvc"
  xsi:schemaLocation="
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
  http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <context:component-scan base-package="org.anvard.webmvc.server"/>
    <mvc:annotation-driven/>

</beans>

The file name is important, as Spring WebMVC is going to look for a file with this name because of the <servlet-name> we provided in web.xml. It’s important to remember to change one if you change the other.

This is a regular Spring XML configuration file. We could create arbitrary beans here, link them together, configure transaction management, persistence, whatever we choose. In this case, we’re using two items that were added to Spring within the last few years and relate to Spring’s new annotation-driven configuration.

  • <context:component-scan> tells Spring that rather than listing all the beans in the XML file, we want it to scan the classpath. We give it a base-package to make the search more efficient and to make sure it doesn’t pick up things we don’t want. There are a number of Spring class-level annotations that will tell Spring that a class should be instantiated as a bean, but for WebMVC purposes we will use @Controller.
  • <mvc:annotation-driven/> tells Spring that as beans are added to the Spring application context, it should search them for WebMVC annotations in order to find targets for the dispatcher. More on this next time, but there’s also the excellent Spring reference documentation.

As the name implies, Spring WebMVC is about bringing the model-view-controller design pattern to web programming. Controllers handle requests, optionally pulling in data from the model. As much as possible, the Spring framework itself handles the view, which for REST interfaces mostly means converting to JSON or XML.

Our controller Java class looks like this:

package org.anvard.webmvc.server; 

 import org.anvard.webmvc.api.Calculation;
 import org.springframework.stereotype.Controller;
 import org.springframework.util.Assert;
 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;
 import org.springframework.web.bind.annotation.ResponseBody;

 @Controller
 public class Calculator {

     @RequestMapping(value = "/calc/{op}/{left}/{right}", 
                     method = RequestMethod.GET)
     @ResponseBody
     public Calculation calculate(@PathVariable("op") String op, 
             @PathVariable("left") Integer left,
             @PathVariable("right") Integer right) {
         Assert.notNull(op);
         Assert.notNull(left);
         Assert.notNull(right);
         Calculation result = new Calculation();
         result.setOperation(op);
         result.setLeft(left);
         result.setRight(right);
         return doCalc(result);
     }

     @RequestMapping(value = "/calc2", method = RequestMethod.POST)
     @ResponseBody
     public Calculation calculate(@RequestBody Calculation calc) {
         Assert.notNull(calc);
         Assert.notNull(calc.getOperation());
         Assert.notNull(calc.getLeft());
         Assert.notNull(calc.getRight());
         return doCalc(calc);
     }

     private Calculation doCalc(Calculation c) {
         String op = c.getOperation();
         int left = c.getLeft();
         int right = c.getRight();
         if (op.equalsIgnoreCase("subtract")) {
             c.setResult(left - right);
         } else if (op.equalsIgnoreCase("multiply")) {
             c.setResult(left * right);
         } else if (op.equalsIgnoreCase("divide")) {
             c.setResult(left / right);
         } else {
             c.setResult(left + right);
         }
         return c;
     }

 }

Next time I’ll talk in detail about the various WebMVC annotations and how they’re used to expose different types of REST interfaces. For today, I want to finish with the point that this is a complete example of a Spring WebMVC REST application. We could build a WAR with these three files (and the Spring dependencies) and it would deploy to a servlet container and expose REST interfaces. With the right dependencies, this example will return XML or JSON to a client, depending on what the client requested.


Spring Framework REST Web Protocols Java (programming language) Jetty (web server)

Published at DZone with permission of Alan Hohn, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Aggregating REST APIs Calls Using Apache Camel
  • How to Develop Microservices With Spring Cloud and Netflix Discovery
  • Building a REST Service That Collects HTML Form Data Using Netbeans, Jersey, Apache Tomcat, and Java
  • Spring Boot - How To Use Native SQL Queries | Restful Web Services

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!