Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Hello World Restful Web Service Using Spring

DZone's Guide to

Hello World Restful Web Service Using Spring

· Java Zone
Free Resource

The single app analytics solutions to take your web and mobile apps to the next level.  Try today!  Brought to you in partnership with CA Technologies

Spring Framework   provides all kinds of wonderful benefits to the modern developer. It has provided a way to build REST Web Services that is straightforward and productive. You only have to use what you need from Spring, its not an all or nothing framework.
In order to facilitate building our 'Hello World' service, we will first open  IntelliJ IDEA 13 Community Edition  and create a new project.



Select Maven as the project type and enter the project name as HelloWorldRestService as shown.


Click the Next button and select the checkbox [] Create from archetype, then choose the maven-archetype-webapp, click next and finish. If asked, select to enable auto import for your maven settings.
Your project should look like the following.




Replace your pom.xml file will the contents below.

<?xml version="1.0" encoding="UTF-8"?>
<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>HelloWorldRestService</groupId>
 <artifactId>HelloWorldRestService</artifactId>
 <version>1.0-SNAPSHOT</version>
 <packaging>war</packaging>
 <properties>
 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 <java.version>1.7</java.version>
 <maven.compiler.plugin>2.3.2</maven.compiler.plugin>
 <spring.version>4.0.0.RELEASE</spring.version>
 </properties>

<dependencies>
 <dependency>
 <groupId>junit</groupId>
 <artifactId>junit</artifactId>
 <version>4.11</version>
 <scope>test</scope>
 </dependency>
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-core</artifactId>
 <version>${spring.version}</version>
 </dependency>

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-context</artifactId>
 <version>${spring.version}</version>
 </dependency>

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-beans</artifactId>
 <version>${spring.version}</version>
 </dependency>

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-web</artifactId>
 <version>${spring.version}</version>
 </dependency>

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-webmvc</artifactId>
 <version>${spring.version}</version>
 </dependency>

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-jms</artifactId>
 <version>${spring.version}</version>
 </dependency>

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-orm</artifactId>
 <version>${spring.version}</version>
 </dependency>

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-oxm</artifactId>
 <version>${spring.version}</version>
 </dependency>

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-test</artifactId>
 <version>${spring.version}</version>
 </dependency>

<dependency>
 <groupId>log4j</groupId>
 <artifactId>log4j</artifactId>
 <version>1.2.17</version>
 </dependency>

<dependency>
 <groupId>org.slf4j</groupId>
 <artifactId>slf4j-api</artifactId>
 <version>1.7.2</version>
 <type>jar</type>
 </dependency>

<dependency>
 <groupId>com.google.code.gson</groupId>
 <artifactId>gson</artifactId>
 <version>2.2.2</version>
 </dependency>
 </dependencies>

<build>
 <plugins>
 <plugin>
 <groupId>org.apache.maven.plugins</groupId>
 <artifactId>maven-compiler-plugin</artifactId>
 <version>${maven.compiler.plugin}</version>
 <configuration>
 <source>${java.version}</source>
 <target>${java.version}</target>
 <compilerArgument>
 -XDignore.symbol.file
 </compilerArgument>
 </configuration>
 </plugin>
 </plugins>
 </build>
</project>


Create Rest Controller

Create a new package named hello in /src/main/java. Create a new class named HelloRestController, then annotate the class with the @Controller annotation and enter the following code.

private final Logger logger = LoggerFactory.getLogger(HelloRestController.class);

@RequestMapping(value = "/helloworld", method = RequestMethod.GET)
 public @ResponseBody String displayTemplateJSON() throws Exception {
 logger.info("displayTemplateJSON() method invoked.");
 Map<String, Object> dataStructure = new HashMap<>();
 Map<String, Object> data = new HashMap<>();
 Gson gson = new Gson();

// build a simple data structure
 dataStructure.put("dataStructure", getStructure());
 logger.info("displayTemplateJSON(), building data structure.");

// convert Map to JSON
 String json = gson.toJson(dataStructure, Map.class);
 logger.info("displayTemplateJSON(), converting data structure to JSON.");

if (json != null) {
 logger.info("displayTemplateJSON(), returning data structure as JSON.");
 return json;
 }

return "\"{ \"No data foundl.\"}\"";
 }

 private Map<String, Object> getStructure() {
 Map<String, Object> data = new HashMap<>();
 data.put("Task", "Learn Spring Rest Web Services.");
 data.put("Company", "Example Inc.");

List<String> requestTypes = new ArrayList<>();
 requestTypes.add("RequestTypeOne");
 requestTypes.add("RequestTypeTwo");
 requestTypes.add("RequestTypeThree");
 requestTypes.add("RequestTypeFour");
 requestTypes.add("RequestTypeFive");
 requestTypes.add("RequestTypeSix");
 requestTypes.add("RequestTypeSeven");
 requestTypes.add("RequestTypeEight");
 data.put("RequestTypes", requestTypes);

logger.info("displayTemplateJSON(), data structure is: {}", data);
 return data;
 }



Configuration

You're almost done. To ensure that Spring knows about your MVC Controller and outputs your logging, create a class named WebConfig, annotate it with @Configuration, @EnableWebMvc and @ComponentScan as shown.




Next, create log4j.properties in /src/main/resources with the following content.




web.xml Configuration
A web.xml is required for this setup (note: there are ways to get rid of this as well, not covered in this article). Replace the contents of your web.xml with the following.

<?xml version="1.0" ?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 version="3.0">

<display-name>Web Application</display-name>
<servlet>
<servlet-name>myServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
 <param-name>contextClass</param-name>
 <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>hello.WebConfig</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
 <servlet-name>myServlet</servlet-name>
 <url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>


Building and Deploying
Run maven clean and then install, deploy to your favorite Servlet container.
Enjoy.

CA App Experience Analytics, a whole new level of visibility. Learn more. Brought to you in partnership with CA Technologies.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}