Professional Documents
Culture Documents
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.
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.
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.
I suggest you read a good book on REST API e.g. RESTful Web Services to learn more about
REST.
Similar to other popular template classes e.g. JdbcTemplate or JmsTempalte, it also simplifies
the interaction with RESTful Web Services on the client side.
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.
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.
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:
This means that class annotated with @Controller will also be automatically be detected by
Spring container as part of container's component scanning process.
Spring Framework may also use this annotation to provide some more useful features related
to REST API development in future.
This makes the development of RESTful web service easier using Spring.
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
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.
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:
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.
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.
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.
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 default handler is based on the @Controller and @RequestMapping annotations, offering a
wide range of flexible handling methods.
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.
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.
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.
If an application context hierarchy is not required, applications may return all configuration
via getRootConfigClasses() and return null from getServletConfigClasses().
Most applications should consider extending the Spring Java config subclass Abstract
Annotation Config Dispatcher Servlet Initializer.
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/*”)
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.
Annotation for mapping HTTP GET requests onto specific handler methods.
If specific packages are not defined, scanning will occur from the package of the class
that declares this annotation.
34.Use of @RestController
35. How do you declare request and response Media Types in spring MVC?
@RequestMapping(method=RequestMethod.GET, value="/fooBar")
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.
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.
In Spring MVC, unexpected exceptions might be thrown during execution of its controllers.
Spring provides two approaches for handling these exceptions:
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.
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.
@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.
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.
@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.
A controller method return value type for asynchronous request processing where one or more
objects are written to the response.
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
Non-blocking, reactive client to perform HTTP requests, exposing a fluent, reactive API over
underlying HTTP client libraries such as Reactor Netty.
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.
return "redirect:finalPage";
return "final";
49. How do you forward a request to another page using Spring MVC?
@RequestMapping("/myController/test")
return "forward:/someOtherUrl?reqParam="+reqParamValue;
or
@RequestMapping("/myController/test")
HttpServletRequest request) {
request.setAttribute("reqParam", reqParamValue);
return "forward:/someOtherUrl";
@RequestMapping(method = RequestMethod.POST)
BindingResult result) {
String returnVal = "successFile";
if (result.hasErrors()) {
returnVal = "file";
} else {
return returnVal;