A Beginner’s Guide To Spring [Part 2]

This is a continuation of my previous article of the article on Spring which is accessible from here:-

Now, creating a real application in Spring requires few additions, changes, and modulation of the existing code. The code as per the previous article is:-

Here, we’ll be only using our post and get methods as the other two methods aren’t of much concern as of now. As of now, we’ll try to build a full-stack application where we will be entering data into the dB via the POST request and returning the data via the same method. Technically, we should have used GET method also put ut’s a very simple application and doesn’t need to be complex.

First things first, we need to change our backend to receive data. After changing the POST method, our createUser method will look like:-

  1. createUser method must accept any type of data which comes in i.e.- Either JSON or XML. In order to do so, we add the following code to the PostMapping annotation.

consumes={ MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE }, produces= { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE })

As self-explanatory as the code is, the consumes part makes sure that the method can consume/take either of the XML or JSON data coming in via the specified Url path whereas the produces part makes sure that the method can produce any kind of needed format.

Now, the data coming in the form of JSON or XML must be received by a class so that the extraction of fields can be done from the incoming data. For this very purpose, we use the class UserDetailsRequestModel which has the following fields in it:-

This class has 4 fields which can be seen as above. In order to put and extract data from these variables only via using getters and setters. This class is mainly needed to pull the data out of the HTTP we are receiving.

2. The @RequestBody annotation maps the HttpRequest body to a transfer or domain object, enabling automatic deserialization of the inbound HttpRequest body onto a Java object. (here the object of UserDetailsRequestModel Class).

3. The extracted data inside the above class can be processed in multiple ways. Here, we’ll be transferring this data into a different class so that we can access our dB.

For using dB code, we’ll create a class called UserRest. Like the above class, this class also had 4 fields, one each to complement the incoming data. Again, getters and setters are generated for each field. Then we set each value from the values with the help of setters.

At the end of setPassword function, we have a function call calljdbc(). This function of ours invokes the jdbc code. The Spring database can be integrated with different types of databases such as MongoDB, SQL, etc. Spring also has some in-built databases like Hibernate, JPA, etc. The simplest of all the databases is SQL which here, is connected using JDBC API.

For each new database like JPA or Hibernate etc, we need to add dependencies into our pom.xml file. Also, we need MySQL connector into the reference libraries into order to provide a driver for our JDBC and SQL dB.

Returning values from the Controller class:-

Notice the uid field in the above class. This uid wasn’t present in the original data yet we’re using it as our main return value or simply it’s the value which we fetch based on the query we write for our SQL <we find the uid of a person with matching name, password, etc>.

After finding the uid value, we use setUid method to set the value of uid field.

4. ResponseEntity<> is a generic way of representing HTTP responses via Spring. We can send any POJO or a custom made class along with any HTTP response code. It has a constructor that allows us to do so. In image 1, ResponseEntity<> is of type ResponseEntity<UserRest> as it returns an object of type UserRest along with an HTTP request code of 200, i.e. OK.

Now, there are many ways to return a value from a Spring method. It can be via using POJO like Maps, lists, HashTables or via custom made classes like above. Instead of ResponseEntity<>we could have returned Map<Type,type> or List<type,type>. It’s a matter of usage and preference.

NOTE:- This method isn’t the most efficient method of using Spring. Generally, we need to have Entity then it’s members, etc. But JDBC is the simplest way of using Java for SQL. There are better Databases and easier and better methods of doing this but being the closest to core Java, we have used this. Refer Spring docs for the same.

This is everything we have need from the backend.

Modifying the Front-end

In order to generate an HTTP request, we need to use Javascript and the concept of XMLHttpRequest(). We require 4 form like elements on an HTML page. On click of the submit button, a JS function should be called which generates the HTTP request and sends the data stored into the fields to the back-end.

→ createStudent is the function call which happens when a user presses the submit button. studentName is the variable which gets the info contained in the code field <it’s the field which takes in the first name of user>. Similarly, we need three more variables which takes in the rest of the fields.

→ XMLHttpRequest is used to create objects to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing.

→Object of XMLHttpRequest, xhr is then used to send the request to the local host via the line:-

xhr.open(“POST”, “http://localhost:8080/send");

A post request is generated and the data is sent to localhost 8080.

→ setRequestHeader() sets the value of an HTTP request header. The other parameter makes sure that data is in the form of JSON. We can make XML to make it XML instead.

→ The most important part of this code is xhr.send. It sends the data to the localhost. Stringify changes the data into a string. Here the mapping of keys and values is important. Moreover, the keys should match with the variables we have chosen inside our UserDetailsRequestModel class else we’ll get an error.

→ Ok, so sending the data is done. What about receiving it? Well, we have already taken care of that. The code:-

xhr.addEventListener(“readystatechange”, function () {

if (this.readyState === 4) {

let response = this.responseText;

let anime = JSON.parse(response);

}):

So, on any change in the HTTP request, the xhr object will catch the change and stores it into a variable called response. The responsetext is the main variable that has the incoming data from the server. Printing the response text alone will give you the result from the server. Although using JSON.parse(response) will convert the incoming data into JavaScript Object allowing us to parse the data using keys() and object() methods.

Lastly, if you run the above code it will definitely not work. This is because your Spring application isn’t configured to the cross-origin request coming from the browser say chrome or opera etc. So just add the annotation:-

@CrossOrigin(origins=”*”)

before the @RestController and you are good to go!

And here, we have successfully build a full-stack web-based application using Spring. I know this isn’t the best or the most efficient application this is actually how the API calls used in the in-built dB of Spring like JPA etc works .

Hope you found the article useful. Thanks for reading. !!

A tech enthusiast who loves to read and write about new technologies and trends.