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?

Trending

  • Bridging UI, DevOps, and AI: A Full-Stack Engineer’s Approach to Resilient Systems
  • Can You Run a MariaDB Cluster on a $150 Kubernetes Lab? I Gave It a Shot
  • Apache Spark 4.0: Transforming Big Data Analytics to the Next Level
  • Security by Design: Building Full-Stack Applications With DevSecOps

11 Spring MVC and REST Web Service Interview Questions

Preparing for Spring MVC interviews? Find 11 frequently-asked interview questions for programmers with two to three years of experience.

By 
Javin Paul user avatar
Javin Paul
·
Apr. 07, 22 · Opinion
Likes (5)
Comment
Save
Tweet
Share
4.4K Views

Join the DZone community and get the full member experience.

Join For Free

If you are preparing for Java and Spring interviews or Spring certification and looking for some frequently asked Spring MVC and REST interview questions, you've come to the right place. 

Since the Spring Framework is the most popular and standard framework for developing Java web applications and RESTful web services, a good knowledge of Spring core and Spring MVC is expected from any senior Java developer.

But, if the job description mentions REST and web services, you also need to be aware of how to develop RESTful web services using the Spring Framework.

From Spring 3.1, the framework has been enhanced a lot to support many features needed for the RESTFul API. The HTTPMessageConverter can convert your HTTP response to JSON or XML just by detecting a relevant library in the classpath, like Jackson and JAXB.

Spring also provides customized annotations for RESTful Web Services, like @RestController, which can make your Controller REST more aware, so that you don’t need to do common stuff required by every single REST API, like converting the response to JSON.

Deep knowledge of Spring Security is also mandatory for developing security for RESTful web services in the real world. Since you cannot make life a non-trivial REST API without security, a good knowledge of security basics, HTTP basic authentication, digest authentication, OAuth, and JWT is very important.

11 Spring MVC + REST Web Service Interview Questions With Answers for Java Programmers

Here are a couple of frequently asked questions about using REST web services in the Spring Framework.

1. When Do You Need @ResponseStatus Annotation in Spring Mvc?

This is a good question for three to five years as an experienced Spring developer. 

The @ResponseStatus annotation is required during error handling in Spring MVC and REST. Normally, when an error or exception is thrown at the server-side, the webserver returns 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 the proper status code, like 404, if the resource is not found. That’s where you can use them @ResponseStatus annotation, which allows you to send custom HTTP status codes along with proper error messages in case of an exception.

In order to use it, you can create custom exceptions and annotate them using the @ResponseStatus annotation and proper HTTP status code and reason.

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

For example, if you are writing a RESTful web service for a library that provides book information, then you can use @ResponseStatus to create an exception that returns the HTTP response code 404 when a book is not found instead of the 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 the HTTP error code 404 with the reason “No such Book” will be returned to the client.

11 Spring MVC + REST Web Service Interview Questions with Answers for Java Programmers

2. What Does @RequestMapping Annotation Do?

The @RequestMapping annotation is used to map web requests to Spring Controller methods. You can map a request based upon HTTP methods, e.g. GET, POST, and various other parameters.

For example, if you are developing a RESTful web service using Spring, then you can use, produce, and consume property along with media type annotations to indicate that this method is only used to produce or consume JSON, as shown below:

@RequestMapping 
(method = RequestMethod.POST, consumes="application/json")
public Book save(@RequestBody Book aBook) {
  return bookRepository.save(aBook);
}


Similarly, you can create other handler methods to produce JSON or XML. 

How view resolvers work in spring

3. 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 the class annotated with the @Controller will also be automatically detected by the Spring container, as part of the container's component scanning process.

And, the @RestController is a specialization of @Controller for the RESTful web service. It not only combines the @ResponseBody and @Controller annotations, but it also gives more meaning to your controller class to clearly indicate that it deals with RESTful requests.

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

difference between controller and REST controller


4. When Do You Need @ResponseBody Annotation in Spring Mvc?

The @ResponseBody annotation can be put on a method to indicate 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 the @RestController annotation instead of the @Controller annotation. This will remove the need to using @ResponseBody because, as discussed in the previous answer, it comes automatically with the @RestController annotation.

5. What Does @PathVariable Do in Spring Mvc? Why It’s Useful in Rest with Spring?

This is one of the useful annotations from Spring MVC that allows you to read values from the URI, like query parameters. It’s particularly useful in the case of creating RESTful web service using Spring, because, in REST, resource identifiers are part of the URI. This question is normally asked by experienced Spring MVC developers with 4 to 6 years of experience.

For example, this URL can be helpful if you want to learn how to extract the id, then you can use the @PathVariable annotation of Spring MVC.

6. What Is the Difference between @Controller and @Restcontroller in Spring MVC?

There are many differences between them @Controller and @RestController annotations, as discussed in my earlier article (see the answer for more!), but the most important one is that with the @RestController you get the @ResponseBody annotation automatically, which means you don't need to separately annotate your handler methods with the @ResponseBody annotation.

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

7. What are the Advantages of the RestTemplate in Spring MVC?

The RestTemplate class is an implementation of the Template method pattern in the Spring framework. Similar to other popular template classes, like the 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, as shown in this RestTemplate example.

rest response code

8. 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 an XML configuration.

It enables support for the @Controller-annotated classes that use @RequestMapping to map incoming requests to handler methods that are not already familiar with Spring's support for Java configuration.

9. What is an HttpMessageConverter in Spring REST?

An HttpMessageConverteris 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 responses to various formats, for example, 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 that the 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 it to the client. 

10. How to Create a Custom Implementation of the HttpMessageConverter to Support a New Type of Request/Response?

You just need to create an implementation of the AbstractHttpMessageConverter and register it using the WebMvcConfigurerAdapter#extendMessageConverters() methods with the classes that generate a new type of request/response.

11. Do You Need Spring MVC in Your Classpath for Developing Restful Web Service? (answer)

This question is often asked by Java programmers with 1 to 2 years of experience in Spring. The short answer is: yes — you need Spring MVC in your Java application’s classpath to develop RESTful web services using the Spring framework.

It’s actually Spring MVC that provides all useful annotations, like @RestController, @ResponseCode , @ResponseBody, @RequestBody, and @PathVariable. Hence, you must use spring-mvc.jar the appropriate Maven entry in your pom.xml

There you have it — some of the frequently asked Spring MVC interview questions for beginners and experienced Java JEE developers. 

If are already preparing for your Spring Developer certification, and you need more such questions from the Spring certification perspective, you will find a lot of questions on this topic on David Mayer’s Core Spring Simulator, one of the best simulators to pass the Spring certification at the moment. Good luck with your interviews!

Opinions expressed by DZone contributors are their own.

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!