JAX-RS provides the functionality for Representational State Transfer (RESTful) web services. REST is well-suited for basic, ad hoc integration scenarios. Spring MVC offers controllers to create RESTful web services.
In Spring MVC 3.0, we need to explicitly annotate a class with the @Controller
annotation in order to specify a controller servlet and annotate each and every method with @ResponseBody
to serve JSON, XML, or a custom media type. With the advent of the Spring 4.0 @RestController
stereotype annotation, we can combine @ResponseBody
and @Controller
.
The following example will demonstrate the usage of @RestController
:
RESTfulWeb
.web.xml
file and add a configuration to intercept requests with a Spring DispatcherServlet
:<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>RESTfulWeb</display-name> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/dispatcher-servlet.xml </param-value> </context-param> </web-app>
DispatcherServlet
expects a configuration file with the naming convention [servlet-name]-servlet.xml
. Create an application context XML, dispatcher-servlet.xml
. We'll use annotations to configure Spring beans, so we need to tell the Spring container to scan the Java package in order to craft the beans. Add the following lines to the application context in order to instruct the container to scan the com.packt.controller
package:<context:component-scan base-package="com.packt.controller" /> <mvc:annotation-driven />
com.packt.controller
package and add a SpringService
controller class. To configure the class as a REST controller, we need to annotate it with the @RestController
annotation. The following code snippet represents the class:@RestController
@RequestMapping("/hello")
public class SpringService {
private Set<String> names = new HashSet<String>();
@RequestMapping(value = "/{name}", method =
RequestMethod.GET)
public String displayMsg(@PathVariable String name) {
String result = "Welcome " + name;
names.add(name);
return result;
}
@RequestMapping(value = "/all/", method =
RequestMethod.GET)
public String anotherMsg() {
StringBuilder result = new StringBuilder("We
greeted so far ");
for(String name:names){
result.append(name).append(", ");
}
return result.toString();
}
}
We annotated the class with @RequestMapping("/hello")
. This means that the SpringService
class will cater for the requests with the http://{site}/{context}/hello
URL pattern, or since we are running the app in localhost, the URL can be http://localhost:8080/RESTfulWeb/hello
.
The displayMsg
method is annotated with @RequestMapping(value = "/{name}", method = RequestMethod.GET)
. So, the method will handle all HTTP GET
requests with the URL pattern /hello/{name}
. The name can be any String, such as /hello/xyz
or /hello/john
. In turn, the method stores the name to Set
for later use and returns a greeting message, welcome {name}
.
The anotherMsg
method is annotated with @RequestMapping(value = "/all/", method = RequestMethod.GET)
, which means that the method accepts all the requests with the http://{SITE}/{Context}/hello/all/
URL pattern. Moreover, this method builds a list of all users who visited the /hello/{names}
URL. Remember, the displayMsg
method stores the names in Set
; this method iterates Set
and builds a list of names who visited the /hello/{name}
URL.
There is some confusion though: what will happen if you enter the /hello/all
URL in the browser? When we pass only a String literal after /hello/
, the displayMsg
method handles it, so you will be greeted with welcome all
. However, if you type /hello/all/
instead—note that we added a slash after all
—it means that the URL does not match the /hello/{name}
pattern and the second method will handle the request and show you the list of users who visited the first URL.
/hello/{name}
URL, the following output is displayed:When we access http://localhost:8080/RESTfulWeb/hello/all/
, the following output is displayed:
Therefore, our RESTful application is ready for use, but just remember that in the real world, you need to secure the URLs against unauthorized access. In a web service, development security plays a key role. You can read the Spring security reference manual for additional information.
52.14.82.217