Spring MVC Get University/College Details via REST API (original) (raw)
REST APIs are commonly used to retrieve data from external services and integrate it into web applications. Spring MVC provides a simple way to consume REST APIs, process JSON responses, and display the retrieved information on JSP pages.
- Spring MVC can invoke external REST APIs and retrieve data in JSON format.
- JSON responses can be parsed to extract specific information such as university names and website URLs.
- Retrieved data can be displayed dynamically on JSP pages using AJAX and the MVC architecture.
We will use the Hipolabs Universities REST API to fetch university or college details based on the country name and university name entered by the user.
**Example:
http://universities.hipolabs.com/search?country=india&name=kamaraj
Corresponding JSON Output:

We will get many values for this and let us see the sample

Steps to Implement Retrieving University/College Details Using REST API and Spring MVC
Follow these steps to fetch university details from an external REST API and display the data on a JSP page using Spring MVC.
Step 1: Create a Maven Project
- Open STS IDE.
- Click File - New - Maven Project.
- Select Create a simple project (Select archetype ) and click Next.
Then Enter the following details:
- **Group Id: com.gfg
- **Artifact Id: College_RestAPI
- **Packaging: war
Click Finish.
Step 2: Add Required Dependencies
Add the following maven dependencies and plugin to your pom.xml file.
XML `
4.0.0 com.college.college_RestAPI College_RestAPI war 0.0.1-SNAPSHOT collegeRestAPI http://maven.apache.org false 5.1.0.RELEASE org.springframework spring-webmvc ${spring-version} org.springframework spring-test ${spring-version} javax.servlet.jsp.jstl javax.servlet.jsp.jstl-api 1.2.1 taglibs standard 1.1.2 javax.servlet javax.servlet-api 3.1.0 provided javax.servlet.jsp javax.servlet.jsp-api 2.3.1 provided com.google.code.gson gson 2.8.6 commons-io commons-io 2.5 junit junit 4.12 test ROOT src/main/java maven-compiler-plugin 3.5.1 1.8 1.8 org.apache.maven.plugins maven-war-plugin 3.3.2
`
Step 3: Create JSP Page (index.jsp)
This page allows users to enter the university name and country name. An AJAX request is sent to the Spring MVC controller, and the returned data is displayed dynamically.
HTML `
CollegesColleges :
Webpages :
</div>
</section>`
Step 4: Configure Spring MVC
This configuration class enables Spring MVC and configures the JSP View Resolver.
Java `
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView;
@Configuration @EnableWebMvc @ComponentScan(basePackages = { "com.college.college_RestAPI" }) public class AppConfig { @Bean public InternalResourceViewResolver resolver() { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setViewClass(JstlView.class); resolver.setPrefix("/"); resolver.setSuffix(".jsp"); return resolver; } }
`
Step 5: Configure Dispatcher Servlet
This class initializes Spring MVC and routes all incoming requests through the DispatcherServlet.
Java `
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class SpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { AppConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}}
`
Step 6: Create Controller (CollegeController.java)
This controller receives the country name and university name from the JSP page, invokes the external REST API, parses the JSON response, and returns the required data back to the browser.
Java `
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject;
@Controller public class CollegeController {
@RequestMapping("/getCollegeDetailsBycountryNameAndSearchString")
public @ResponseBody
JsonObject getLocalityDetailsByZipCode(String countryName,String name) throws IOException {
JsonArray jsonArray = new JsonArray();
jsonArray = getCollegeDetailsByParams(countryName,name);
JsonObject finalJsonObject = new JsonObject();
// String country = jsonObject.get("country").toString();
// country = country.replaceAll("^\"|\"$", "");
ArrayList collegeList = new ArrayList();
ArrayList stateList = new ArrayList();
ArrayList webPageList = new ArrayList();
// ArrayList longitudeList = new ArrayList();
// jsonPlacesArray = jsonObject.get("places").getAsJsonArray();
Iterator<JsonElement> objectIterator = jsonArray.iterator();
while(objectIterator.hasNext()) {
JsonElement object = objectIterator.next();
JsonObject jObj = object.getAsJsonObject();
// System.out.println(jObj.get("place name").toString() + jObj.get("state").toString() );
collegeList.add(jObj.get("name").toString().replaceAll("^\"|\"$", ""));
stateList.add(jObj.get("state-province").toString().replaceAll("^\"|\"$", ""));
webPageList.add(jObj.get("web_pages").toString().replaceAll("^\"|\"$", ""));
}
// finalJsonObject.addProperty("country", country);
finalJsonObject.addProperty("associatedcolleges", collegeList.toString());
finalJsonObject.addProperty("associatedcollegesize", collegeList.size());
finalJsonObject.addProperty("state", stateList.toString());
finalJsonObject.addProperty("statename", stateList.get(0).toString());
finalJsonObject.addProperty("associatedwebpages", webPageList.toString());
finalJsonObject.addProperty("associatedwebpagesize", webPageList.size());
return finalJsonObject;
}
private JsonArray getCollegeDetailsByParams(String countryName,String name) throws IOException {
StringBuilder responseData = new StringBuilder();
JsonArray jsonArray = null;
URL url = null;
url = new URL("http://universities.hipolabs.com/search?name=" + name + "&country=" + countryName);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
// System.out.println("Response Code : " + responseCode);
try (BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String line;
while ((line = in.readLine()) != null) {
responseData.append(line);
}
jsonArray = new Gson().fromJson(responseData.toString(), JsonArray.class);
}
return jsonArray;
}}
`
Step 7: Run the Application
- Right Click Project.
- Select Run As - Run on Server.
- Choose Apache Tomcat Server.
- Click Finish.
Open the browser and access:
**Output:

Enter a valid university name and country name, then click Find College Details. The application displays the matching university names and their website URLs.

**Explanation:
- The user enters the university name and country name on the JSP page and submits the request.
- JavaScript sends a GET request to the Spring MVC controller, which invokes the Hipolabs Universities REST API.
- The REST API returns university details in JSON format, and Gson parses the required information such as university names and website URLs.
- Spring MVC returns the processed data as JSON, and JavaScript displays the university details dynamically on the JSP page.