You are on page 1of 16

Spring With Rest Interview Questions

1. What does REST stand for?


REST stands for Representational State Transfer, which uses HTTP protocol to send data from
client to server e.g. a book in the server can be delivered to the client using JSON or XML.

2. What is a resource?
A resource is how data is represented in REST architecture.

By exposing entities as the resource it allows a client to read, write, modify, and create
resources using HTTP methods e.g. GET, POST, PUT, DELETE etc.

3. What are safe REST operations?


REST API uses HTTP methods to perform operations.

Some of the HTTP operations which doesn't modify the resource at the server is known as safe
operations e.g. GET and HEAD.

On the other hand, PUT, POST, and DELETE are unsafe because they modify the resource on the
server.

4. What are idempotent operations? Why is idempotency important?


There are some HTTP methods e.g. GET which produce same response no matter how many
times you use them e.g. sending multiple GET request to the same URI will result in same
response without any side-effect hence it is known as idempotent.

On the other hand, the POST is not idempotent because if you send multiple POST request, it
will result in multiple resource creation on the server, but again, PUT is idempotent if you are
using it to update the resource.

Even, multiple PUT request to update a resource on a server will give same end result. You can
further take HTTP Fundamentals course by Plural sight to learn more about idempotent
methods of HTTP protocol and HTTP in general.

5. Is REST scalable and/or interoperable?


Yes, REST is Scalable and interoperable.

It doesn't mandate a specific choice of technology either at client or server end.


You can use Java, C++, Python or JavaScript to create RESTful Web Services and Consume them
at the client end.

I suggest you read a good book on REST API e.g. RESTful Web Services to learn more about
REST.

6. What are the advantages of the RestTemplate?


The RestTemplate class is an implementation of Template method pattern in Spring framework.

Similar to other popular template classes e.g. JdbcTemplate or JmsTempalte, it also simplifies
the interaction with RESTful Web Services on the client side.

You can use it to consume a RESTful Web Servicer very easily.

7. Which HTTP methods does REST use?


REST can use any HTTP methods but the most popular ones are GET for retrieving a resource,
POST for creating a resource, PUt for updating resource and DELETE for removing a resource
from the server.

8. What is an HttpMessageConverter in Spring REST?


An HttpMessageConverter is a Strategy interface that specifies a converter that can convert
from and to HTTP requests and responses.

Spring REST uses this interface to convert HTTP response to various formats e.g. JSON or XML.

Each HttpMessageConverter implementation has one or several MIME Types associated with it.

Spring uses the "Accept" header to determine the content type client is expecting.

It will then try to find a registered HTTPMessageConverter that is capable of handling that
specific content-type and use it to convert the response into that format before sending to the
client.

9. How to create a custom implementation of HttpMessageConverter to support a


new type of request/responses?
You just need to create an implementation of AbstractHttpMessageConverter and register it
using the WebMvcConfigurerAdapter#extendMessageConverters() method with the classes
which generate a new type of request/response.
10. Is REST normally stateless?
Yes, REST API should be stateless because it is based on HTTP which is also stateless.

A Request in REST API should contain all the details required it to process i.e. it should not rely
on previous or next request or some data maintained at the server end e.g. Sessions.

REST specification put a constraint to make it stateless and you should keep that in mind while
designing your REST API.

11. What does @RequestMapping annotation do?


The @RequestMapping annotation is used to map web requests to Spring Controller methods.

You can map request based upon HTTP methods e.g. GET and POST and various other
parameters.

For examples, if you are developing RESTful Web Service using Spring then you can use
produces and consumes property along with media type annotation to indicate that this
method is only used to produce or consumers JSON as shown below:

@RequestMapping (method = RequestMethod.POST, consumes="application/json")


public Book save(@RequestBody Book aBook) {
return bookRepository.save(aBook);
}

12. Is @Controller a stereotype? Is @RestController a stereotype?

Yes, both @Controller and @RestController are stereotypes.

The @Controller is actually a specialization of Spring's @Component stereotype annotation.

This means that class annotated with @Controller will also be automatically be detected by
Spring container as part of container's component scanning process.

And, @RestController is a specialization of @Controller for RESTful web service.


It not only combines @ResponseBody and @Controller annotation but also gives more meaning
to your controller class to clearly indicate that it deals with RESTful requests.

Spring Framework may also use this annotation to provide some more useful features related
to REST API development in future.

13. What is the difference between @Controller and @RestController?


There are many differences between @Controller and @RestController as you get
the @ResponseBody annotation automatically, which means you don't need to separately
annotate your handler methods with @ResponseBody annotation.

This makes the development of RESTful web service easier using Spring.

14. When do you need @ResponseBody annotation in Spring MVC?


The @ResponseBody annotation can be put on a method to indicates that the return type
should be written directly to the HTTP response body (and not placed in a Model, or
interpreted as a view name).

For example:
@RequestMapping(path = "/hello", method = RequestMethod.PUT)
@ResponseBody
public String helloWorld() {
return "Hello World";
}

Alternatively, you can also use @RestController annotation instead of @Controller annotation.

This will remove the need for using @ResponseBody because as discussed in the previous
answer, it comes automatically with @RestController annotation.

15. What does @PathVariable do in Spring MVC? Why it's useful in REST with
Spring?
It's one of the useful annotations from Spring MVC which allows you to read values from URI
like query parameter.
16. What is the HTTP status return code for a successful DELETE statement?
There is no strict rule with respect to what status code your REST API should return after a
successful DELETE i.e it can return 200 Ok or 204 No Content.

In general, if the DELETE operation is successful and the response body is empty return 204.

If the DELETE request is successful and the response body is NOT empty, return 200

17.What does CRUD mean?


CRUD is a short form of Create, Read, Update and Delete.

In REST API, the POST is used to create a resource, GET is used to read a resource, PUT is used
to updated a resource and DELETE is used to remove a resource from the server.

18. Where do you need @EnableWebMVC?


The @EnableWebMvc annotation is required to enable Spring MVC when Java configuration is
used to configure Spring MVC instead of XML.

It is equivalent to <mvc: annotation-driven> in XML configuration.

It enables support for @Controller-annotated classes that use @RequestMapping to map


incoming requests to handler methods not already familiar with Spring's support for Java
configuration.

19. When do you need @ResponseStatus annotation in Spring MVC?


The @ResponseStatus annotation is required during error handling in Spring MVC and REST.
Normally when an error or exception is thrown at server side, web server return a blanket HTTP
status code 500 - Internal server error.

This may work for a human user but not for REST clients.

You need to send them proper status code e.g. 404 if the resource is not found.

That's where you can use @ResponseStatus annotation, which allows you to send custom HTTP
status code along with proper error message in case of Exception.
In order to use it, you can create custom exceptions and annotated them
using @ResponseStatus annotation and proper HTTP status code and reason.

When such exceptions are thrown from controller's handler methods and not handled
anywhere else, then appropriate HTTP response with the proper HTTP status code, which you
have set is sent to the client.

For example, if you are writing a RESTful Web Service for a library which provides book
information then you can use @ResponseStatus to create Exception which returns HTTP
response code 404 when a book is not found instead of Internal Server Error (500), as shown
below:

@ResponseStatus(value=HttpStatus.NOT_FOUND, reason="No such Book")


// 404
public class BookNotFoundException extends RuntimeException {
// ...
}

If this Exception is thrown from any handler method then HTTP error code 404 with reason "No
such Book" will be returned to the client.

20. Is REST secure? What can you do to secure it?


Security is a broad term, it could mean security of message which is provided by encryption or
access restriction which is provided using authentication and authorization.

REST is normally not secure but you can secure it by using Spring security.

At the very least you can enable HTTP basic authentication by using HTTP in your Spring security
configuration file.

Similarly, you can expose your REST API using HTTPS if the underlying server supports HTTPS.

21. Does REST work with transport layer security (TLS)?


TLS or Transport Layer Security is used for secure communication between client and server. It
is the successor of SSL (Secure Socket Layer). Since HTTPS can work with both SSL and TLS, REST
can also work with TLS.

Actually, REST says anything about Security, it's up to the server which implements that. Same
RESTful Web Service can be accessed using HTTP and HTTPS if the server supports SSL.

If you are using Tomcat, you can see here to learn more about how to enable SSL in Tomcat.
22. Do you need Spring MVC in your classpath for developing RESTful Web
Service?
Short answer is Yes, you need Spring MVC in your Java application's classpath to develop
RESTful web services using Spring framework.

It's actually Spring MVC which provides all useful annotations


e.g. @RestController, @ResponseCode, @ResponseBody, @RequestBody, and @PathVariable,
hence you must spring-mvc.jar or appropriate Maven entry in your pom.xml

23. What is Spring MVC?

Spring Web MVC framework built based on Servlet API Which is merged into Spring Framework.

“Spring Web MVC,” comes from the name of its source module (spring-web MVC), but it is
formally known as “Spring MVC”.

The Spring Web model-view-controller (MVC) framework is designed around a


DispatcherServlet that dispatches requests to handlers, with configurable handler mappings,
view resolution, locale, and theme resolution as well as support for uploading files.

The default handler is based on the @Controller and @RequestMapping annotations, offering a
wide range of flexible handling methods.

24. Explain the role of DispatcherServlet in spring MVC?

DispatcherServlet acts as a front controller for Spring based web applications.

It provides a mechanism for request processing where actual work is performed by


configurable, delegate components.

It is inherited from javax.servlet.http.HttpServlet, it is typically configured in the web.xml file.

A web application can define any number of DispatcherServlet instances.

Each servlet will operate in its own namespace, loading its own application context with
mappings, handlers, etc.

Only the root application context as loaded by ContextLoaderListener, if any, will be shared.

In most cases, applications have only single DispatcherServlet with the context-root URL(/), that
is, all requests coming to that domain will be handled by it.
By Spring configuration classes, DispatcherServlet discovers the delegate components it needs
for request mapping, view resolution, exception handling, etc.

25. What is HandlerMapping?

The functionality a basic HandlerMapping provides is the delivering of a


HandlerExecutionChain, which must contain the handler that matches the incoming request,
and may also contain a list of handler interceptors that are applied to the request.

While Request comes in, the DispatcherServlet will hand it over to the handler mapping to let it
inspect the request and come up with an appropriate HandlerExecutionChain. Then the
DispatcherServlet will execute the handler and interceptors in the chain (if any).

Mapping request with handler along the list of interceptors for pre and post processing. Based
on varies criteria mapping has enabled where the details of criteria varied by HandlerMapping
implementation.

26. What is ViewResolver?

For Resolve, logical String-based view names, which is returned from a handler to an actual
View, for rendering the response. Interface to be implemented by objects that can resolve
views by name.

Views in Spring are addressed by a view name and are resolved by a view resolver.

27. What is web application Initializer?

Interface to be implemented in Servlet 3.0+ environments in order to configure the


ServletContext programmatically — as opposed to (or possibly in conjunction with) the
traditional web.xml-based approach.

Implementations of this SPI will be detected automatically by SpringServletContainerInitializer,


which itself is bootstrapped automatically by any Servlet 3.0 container

28. What is the use of AbstractAnnotationConfigDispatcherServletInitializer?

WebApplicationInitializer to register a DispatcherServlet and use Java-based Spring


configuration.

Here some Implementations are required to implement:

getRootConfigClasses() — for “root” application context (non-web infrastructure) configuration.


getServletConfigClasses() — for DispatcherServlet application context (Spring MVC
infrastructure) configuration.

If an application context hierarchy is not required, applications may return all configuration
via getRootConfigClasses() and return null from getServletConfigClasses().

29. What is the use of AbstractDispatcherServletInitializer?

Base class for WebApplicationInitializer implementations that register a DispatcherServlet in


the servlet context.

Most applications should consider extending the Spring Java config subclass Abstract
Annotation Config Dispatcher Servlet Initializer.

30.Use of @Controller annotation?

This annotation serves as a specialization of @Component, allowing for implementation classes


to be autodetected through classpath scanning.

It is typically used in combination with annotated handler methods based on the


RequestMapping annotation.

31.Use of @RequestMapping annotation?

Annotation for mapping web requests onto methods in request handling classes with flexible
method signatures.

Both Spring MVC and Spring WebFlux support this annotation through
aRequestMappingHandlerMapping and RequestMappingHandlerAdapter in their respective
modules and package structure.

For the exact list of supported handler method arguments and return types in each, please use
the reference documentation links below:

Spring MVC Method Arguments and Return Values, Spring WebFlux Method Arguments and
Return Values
@RequestMapping(value = “/something”, headers = “content-type=text/*”)

32.Difference between @RequestMapping vs @GetMapping?

RequestMapping can be used at class level:

This annotation can be used both at the class and at the method level. In most cases, at the
method level applications will prefer to use one of the HTTP method specific variants
@GetMapping, @PostMapping, @PutMapping, @DeleteMapping, or @PatchMapping.

while GetMapping only applies to the method:

Annotation for mapping HTTP GET requests onto specific handler methods.

33.Use of @ComponentScan(“”) annotation?

Configures component scanning directives for use with @Configuration classes.

Provides support parallel with Spring XML’s <context:component-scan> element.

Either basePackageClasses() or basePackages() (or its alias value()) may be specified


to define specific packages to scan.

If specific packages are not defined, scanning will occur from the package of the class
that declares this annotation.

34.Use of @RestController

@RestController annotation, which marks the class as a controller where every


method returns a domain object instead of a view. It’s shorthand for @Controller and
@ResponseBody rolled together.

35. How do you declare request and response Media Types in spring MVC?

@RequestMapping(method=RequestMethod.GET, value="/fooBar")

public ResponseEntity<String> fooBar2() {

String json = "jsonResponse";

HttpHeaders responseHeaders = new HttpHeaders();


responseHeaders.setContentType(MediaType.APPLICATION_JSON);

return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED);

36. What is CORS?

Cross-Origin Resource Sharing (CORS) is a specification that enables truly open access across
domain-boundaries.

If you serve public content, please consider using CORS to open it up for universal
JavaScript/browser access.

37. What is RestTemplate?

Synchronous client to perform HTTP requests, exposing a simple, template method API over
underlying HTTP client libraries such as the JDK HttpURLConnection, Apache HttpComponents,
and others.

The RestTemplate offers templates for common scenarios by HTTP method, in addition to the
generalized exchange and execute methods that support of less frequent cases.

38. How do you handle the exception in Spring MVC?

In Spring MVC, unexpected exceptions might be thrown during execution of its controllers.
Spring provides two approaches for handling these exceptions:

Using XML configuration: this is similar to exception handling in Servlet/JSP, by declaring a


SimpleMappingExceptionResolverbean in Spring’s application context file and map exception
types with view names. This approach applies to all controllers in the application.

Using the exception handler method: Spring provides the @ExceptionHandler annotation type
which is used to annotate a method to handle exceptions raised by the controller’s methods.
This approach applies to only the controller in which the handler method is declared.

39. How do you handle container errors in spring MVC?

For access to errors from validation and data binding for a command object
(@ModelAttribute argument) or errors from the validation of a @RequestBody else
@RequestPart arguments, You must declare an Errors or BindingResult argument immediately
after the validated method argument.
40. What is @ResponseBody annotation?

Annotation that indicates a method return value should be bound to the web response body.
Supported for annotated handler methods.

As of version 4.0, this annotation can also be added on the type level in which case it is
inherited and does not need to be added on the method level.

41.Use of @RequestParam, @RequestHeader, @PathVariable, @MatrixVariable,


and @CookieValue?

@RequestParam

Annotation which indicates that a method parameter should be bound to a web request
parameter.Supported for annotated handler methods in Spring MVC and Spring WebFlux as
follows:

In Spring MVC, “request parameters” map to query parameters, form data, and parts in
multipart requests. This is because the Servlet API combines query parameters and form data
into a single map called “parameters”, and that includes automatic parsing of the request body.

In Spring WebFlux, “request parameters” map to query parameters only. To work with all 3,
query, form data, and multipart data, you can use data binding to a command object annotated
with ModelAttribute.

If the method parameter type is Map and a request parameter name is specified, then the
request parameter value is converted to a Map assuming an appropriate conversion strategy is
available.

If the method parameter is Map<String, String> or MultiValueMap<String, String> and a


parameter name is not specified, then the map parameter is populated with all request
parameter names and values.
@PathVariable

Annotation which indicates that a method parameter should be bound to a URI template
variable. Supported for RequestMapping annotated handler methods.

If the method parameter is Map<String, String> then the map is populated with all path variable
names and values.

@MatrixVariable

Annotation which indicates that a method parameter should be bound to a name-value pair
within a path segment. Supported for RequestMapping annotated handler methods.

If the method parameter type is Map and a matrix variable name is specified, then the matrix
variable value is converted to a Map assuming an appropriate conversion strategy is available.

If the method parameter is Map<String, String> or MultiValueMap<String, String> and a


variable name is not specified, then the map is populated with all matrix variable names and
values.

@CookieValue

Annotation which indicates that a method parameter should be bound to an HTTP cookie.

The method parameter may be declared as type Cookie or as a cookie value type (String, int,
etc.).

42.Use of @RequestBody?

Annotation that indicates a method return value should be bound to the web response body.
Supported for annotated handler methods.

43.Use of @InitBinder?

The value in @InitBinder is the names of command/form attributes and/or request parameters
that this init-binder method is supposed to apply to. The default is to apply to all
command/form attributes and all request parameters processed by the annotated handler
class. Specifying model attribute names or request parameter names here restricts the init-
binder method to those specific attributes/parameters, with different init-binder methods
typically applying to different groups of attributes or parameters.
44. What is DataBinder?

Binder that allows for setting property values onto a target object, including support for
validation and binding result analysis. The binding process can be customized through
specifying allowed fields, required fields, custom editors, etc.

45. What is ResponseBodyEmitter?

A controller method return value type for asynchronous request processing where one or more
objects are written to the response.

While DeferredResult is used to produce a single result, a ResponseBodyEmitter can be used to


send multiple objects where each object is written with a compatible HttpMessageConverter.

Supported as a return type on its own as well as within a ResponseEntity.

46. What is DeferredResult and Callable?

DeferredResult provides an alternative to using a Callable for asynchronous request processing.


While a Callable is executed concurrently on behalf of the application, with a DeferredResult
the application can produce the result from a thread of its choice.

Subclasses can extend this class to easily associate additional data or behavior with the
DeferredResult. For example, one might want to associate the user used to create the
DeferredResult by extending the class and adding an additional property for the user.

In this way, the user could easily be accessed later without the need to use a data structure to
do the mapping

47. What is WebClient?

Non-blocking, reactive client to perform HTTP requests, exposing a fluent, reactive API over
underlying HTTP client libraries such as Reactor Netty.

48. How do you redirect a page using Spring MVC?

Prefix in a view name lets you perform a redirect. The UrlBasedViewResolver and its subclasses
recognize this as an instruction that a redirect is needed. The rest of the view name is the
redirect URL.
The net effect is the same as if the controller had returned a RedirectView, but now the
controller itself can operate in terms of logical view names.

A logical view name such as redirect:/myapp/some/resource, redirects relative to the current


Servlet context, while a name such as a redirect:http://myhost.com/some/arbitrary/ path
redirects to an absolute URL.

@RequestMapping(value = "/redirect", method = RequestMethod.GET)

public String redirect() {

return "redirect:finalPage";

@RequestMapping(value = "/finalPage", method = RequestMethod.GET)

public String finalPage() {

return "final";

49. How do you forward a request to another page using Spring MVC?

@RequestMapping("/myController/test")

public String myMethod(@RequestParam("reqParam") String reqParamValue) {

return "forward:/someOtherUrl?reqParam="+reqParamValue;

//forward request to another controller with the param and value

or

@RequestMapping("/myController/test")

public String myMethod(@RequestParam("reqParam") String reqParamValue,

HttpServletRequest request) {

request.setAttribute("reqParam", reqParamValue);
return "forward:/someOtherUrl";

50. How do you handle FileUpload using Spring MVC?

@RequestMapping(method = RequestMethod.POST)

public String fileUploaded(Model model, @Validated File file,

BindingResult result) {
String returnVal = "successFile";

if (result.hasErrors()) {

returnVal = "file";

} else {

MultipartFile multipartFile = file.getFile();

return returnVal;

You might also like