Spring MVC to build web applications and REST APIs
What is Spring MVC?
Spring MVC allows you to create web applications and REST APIs using the same Spring application model and dependency injection concepts.
What is the Scope in Spring?
The core of spring framework is it’s bean factory and mechanisms to create and manage such beans inside Spring container. The beans in spring container can be created in five scopes i.e. singleton, prototype, request, session and global-session. They are called spring bean scopes.
Singleton – Scopes a single bean to a single object instance per Spring IoC container.
Prototype – Scopes a single bean definition to any number of object instances.
Request – Scopes a single bean definition to the lifecycle of a single HTTP request
Session – Scopes a single bean definition to the lifecycle of an HTTP Session.
Global-session – Scopes a single bean definition to the lifecycle of a global HTTP Session.
What is Dependency Injection and how would you achieve that in Spring?
Dependency injection is a pattern used to create instances of objects that other objects rely on. This leads to code being loosely coupled. Two ways of achieving it include:
Constructor-Based Dependency Injection
Setter-Based Dependency Injection
What is Inversion of Control and autowiring?
Inversion of Control is a principle in software engineering by which the control of objects or portions of a program is transferred to a container or framework instead of the programmer.
Autowiring feature of spring framework enables you to inject the object dependency implicitly. It internally uses setter or constructor injection. Essentially, it allows dependency injection.
How do you start a regular spring application?
To build a java app with Spring, you can use different build tools like maven, cradle ant.
Example: Create a maven project, add spring dependency.
Write all layers, controller, services, repository etc.
What are the ways to create beans in spring?
Declaring a bean in XML configuration file
Using @Component annotation
Using @Configuration annotation
Why do we need Spring Boot?
Spring Boot is a Java-based framework used to quickly build production ready spring applications.
How is Spring different from Spring Boot?
Spring framework is used to write enterprise java applications. Spring required a lot of configuration to get it to be production ready.
Spring boot offers that ability to quickly create a Spring application with features to lessen the configuration required through a combination of Auto Configuration and Starter Projects.
What dependency do you need to add to a Spring Boot Project? What about for a database?
Spring Boot offers several starter dependencies which can account for all dependencies needed for any given task. For example, if you wanted to make a web application using the Spring MVC you could use spring-boot-starter-web dependency
If you wanted to use JDBC in your project, you can use the starter dependency of spring-boot-starter-jdbc.
What is a Servlet?
Servlets are Java classes which are used to handle requests, process them and reply back with a response. Simply a way to generate dynamic web pages.
To become a servlet, your class must extend HTTPServlet and you should configure your details in your Deployment Descriptor web.xml OR use the annotation @WebServlet(“/html”).
How to perform testing in SpringBoot?
There are a variety of tests you can write and use in Spring Boot to make sure your application is doing what its meant to do. To do any of this testing, you have to make sure you have the starter dependency for testing in your pom.xml file which is spring-boot-starter-test.
Integration Testing with @DataJpaTest
Mocking with @MockBean
Unit Testing with @WebMvcTest
Integration Testing with @SpringBootTest
Auto-Configured Tests
How to reverse a string in Spring Boot?
Using the get request, retrieve the string data
In the service class, include the String builder class and insert the string in the reverse method
Post the string using the http post method in the controller
How do you persist/retrieve data with spring boot?
Add JPA 2 and Hibernate to our project
Add required annotated entity we want persisted and add an id
Create a repository
Create a class or service to use the repository
What are annotations used for?
Use of annotations provide us capabilities in how we configure the behaviors of the Spring Framework. Annotations are metadata or data about data. An annotation indicates that the declared element should be processed in some special way by a compiler, development tool, deployment tool, or during runtime.
Rest API
What is a REST API?
A RESTful API is an application program interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data.
A RESTful API — also referred to as a RESTful web service — is based on representational state transfer (REST) technology, an architectural style and approach to communications often used in web services development.
Tell me about the conditions of a RESTful webservice?
Client-Server
A RESTful API will have a client-server architecture. The client requests resources while not being concerned with data storage. The server on the other hand holds the resources while not being concerned with the user interface or state. They can work independently of each other. This improves the portability of the UI across platforms as well as improving scalability by simplifying the server components.
Stateless
Session state is kept entirely on the client because every request must contain all needed information to understand the request. It cannot take advantage of any stored context on the server.
Cacheable
Every response will include information on if the response is cacheable or not and for how long the client can reuse that response data. This helps to eliminate some client-server interactions which improves availability and performance and will keep your data up to date a majority of the time.
Uniform Interface
There is a uniform way of interacting with the server, regardless of the kind of application that’s trying to access it–a key constraint between a RESTful API and a non-RESTful API. This is achieved by following its own set of guidelines
Resource-Based
Manipulation of Resources Through Representations
Self-descriptive Messages
Hypermedia as the Engine of Application State (HATEOAS)
Layered System
Architecture is composed of several hierarchical layers with the caveat that each component doesn’t know about any of the other layers with the exception of the immediate layer it is interacting with.
Code on Demand (optional)
Servers can provide executable code in the form of scripts or applets to the client. It reduces the number of features that need to be pre-implemented.
How do you conduct content negotiation in REST API?
Content negotiation allows a user to determine which media types they prefer to receive from the server
One way to pass content type information to server, client may use specific extension in resource URIs. For example, a client can ask for details using:
Step 4: Create JPA Data Repository & Service layer.
Step 5: Create Rest Controllers and map API requests.
Step 6: Create Unit Testing for API requests and run the unit testing.
Step 7: Build and run the Project.
What methods would you write in your Controller?
Controller methods annotated with http request mapping, these methods will handle http request on the specified url. You should have controller methods to handle CRUD operation request.
The job of @Controller is to create a Map of model object and find a view
What is a RestController?
@RestController simply return the object and object data is directly written into HTTP response as JSON or XML
What is the difference between @RestController and @Controller?
While the @RestController is a special annotation for RESTful webservices, returns the object and object data that was converted into a HTTP response as JSON or XML, the @Controller simply marks a class as a Spring MVC controller.
What annotations do you use in your rest controller?
@RestController would be used to annotate the class while @GetMapping, @PostMapping, @PutMapping and @DeleteMapping would be used to annotate methods written to do those corresponding CRUD requests. You could also use @RequestMapping instead to pass it the correct parameter to tell it if it’s a GET, PUT, POST or DELETE crud operation. @RequestParam can also be used to pass query parameters and form parameters.
How would you return status 201 from a REST API?
HTTP convey the results of a client’s request. 2xx: are in the Success Category. Indicates that the client’s request was accepted successfully. 201(created) A rest API responds with the 201 status code whenever a resource is created inside a collection.
What would a ResponseEntity consist of?
A ResponseEntity represents the HTTP response, so it consists of the headers, body, and status code.
Can a REST API provide both JSON and XML response?
Yes, but you cannot provide both JSON and XML at the same time.
What is CORS?
CORS stands for cross-origin resource sharing, which allows restricted resources to be accessed by domains outside of the domain which is serving the resource.
How do you fix a CORS?
In the server, you specify both the domain you want to allow as well as the REST methods you want allow.
How would you receive and reverse a string using a Rest API?
In the controller class we have post-mapping , handles post requests . So we send a JSON object that contains a string and then to reverse it we go to service and we create a method that will reverse that string such as stringBuilder reverse(). method. to send a string to the API , and reverse it there .