Spring MVC — получение информации об университете/колледже через REST API
Передача репрезентативного состояния (REST) — это архитектурный стиль, который определяет набор ограничений, используемых для создания веб-служб. REST API — это простой и гибкий способ доступа к веб-сервисам без какой-либо обработки. Spring MVC — это Web MVC Framework для создания веб-приложений. Это модуль spring, такой же, как spring boot, spring-security и т. д. Термин MVC означает архитектуру Model-View-Controller. В настоящее время вызовы REST API широко используются для получения различной информации, такой как погода, почтовый индекс, криптовалюта, информация об университете и т. д. В этой статье давайте попробуем получить информацию об университете/колледже через
http://universities.hipolabs.com/search?country=india&name=kamaraj
Соответствующий вывод JSON:
http://universities.hipolabs.com/search?country=india
Мы получим много значений для этого и давайте посмотрим образец
Используя Spring Framework, давайте реализуем и получим подробную информацию о колледже. Для простоты передадим в качестве параметров оба параметра, а именно страну и имя.
Пошаговая реализация
Структура проекта:
Это проект, управляемый maven. Следовательно, начнем с
пом.xml
XML
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 <modelVersion>4.0.0</modelVersion> <groupId>com.college.college_RestAPI</groupId> <artifactId>College_RestAPI</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>collegeRestAPI</name> <properties> <failOnMissingWebXml>false</failOnMissingWebXml> <spring-version>5.1.0.RELEASE</spring-version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring-version}</version> </dependency> <!-- JSTL Dependency --> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>javax.servlet.jsp.jstl-api</artifactId> <version>1.2.1</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <!-- Servlet Dependency --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!-- JSP Dependency --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.6</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>ROOT</finalName> <sourceDirectory>src/main/java</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <!-- This should be added to overcome Could not initialize class org.apache.maven.plugin.war.util.WebappStructureSerializer --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>3.3.2</version> </plugin> </plugins> </build></project> |
Давайте начнем со страниц JSP, которые представляют собой страницу, которая отображается в tomcat при запуске проекта.
index.jsp
HTML
<!DOCTYPE html><html lang="en"><head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Colleges</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <style type="text/css"> .main-form, .profile-area { width: 340px; } .main-form { margin: 50px auto 0px; } .profile-area { margin: 10px auto; } .main-form section, .profile-area section { margin-bottom: 15px; background: #f7f7f7; box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); } .main-form section { padding: 30px; } .profile-area section { padding: 30px 30px 30px; } .profile-area section > div { text-align: center; } .main-form h3 { margin: 0 0 15px; } .form-control, .btn { min-height: 38px; border-radius: 2px; } .btn { font-size: 15px; font-weight: bold; } .hideElement { display: none; } </style></head><body><div class="main-form" id="main-form"> <section> <div class="form-group"> <input id="searchString" type="text" class="form-control" placeholder="Enter college search name here..." required="required"> </div> <div class="form-group"> <input id="countryName" type="text" class="form-control" placeholder="Enter country name here..." required="required"> </div> <div class="form-group"> <button onclick="loadData()" class="btn btn-primary btn-block">Find College Details</button> </div> </section></div><div class="profile-area hideElement" id="profile-area"> <section> <div id="loader" class="hideElement"> <div class="spinner-border" role="status"> <span class="sr-only">Loading...</span> </div> </div> <div id="profile" class="hideElement"> <br><br> <p><strong>Colleges : </strong><span id="associatedcolleges"></span></p> <p><strong>Webpages : </strong><span id="associatedwebpages"></span></p> </div> </section></div></body><script> function loadData() { document.getElementById("profile-area").classList.remove("hideElement"); document.getElementById("loader").classList.remove("hideElement"); document.getElementById("profile").classList.add("hideElement"); var searchString = document.getElementById("searchString").value; var countryName = document.getElementById("countryName").value; if(searchString != "" && searchString != null && countryName != "" && countryName != null) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var jsonResponse = JSON.parse(this.responseText); document.getElementById("associatedcolleges").innerHTML = jsonResponse.associatedcolleges; document.getElementById("associatedwebpages").innerHTML = jsonResponse.associatedwebpages; document.getElementById("loader").classList.add("hideElement"); document.getElementById("profile").classList.remove("hideElement"); } }; xhttp.open("GET", "getCollegeDetailsBycountryNameAndSearchString?countryName="+ countryName + "&name=" + searchString, true); xhttp.send(); console.log("done"); } else { console.log("Enter country name and search string to check...") } }</script></html> |
Выход:
Процесс выполнения:
Со страницы JSP вызывается метод «GET» со строкой поиска, и он перенаправляется в класс Spring Controller, где URL REST API, http://universities.hipolabs.com/search?name=<collegename>&country =<countryname> вызывается, и он создаст массив JSON, как указано выше. Из этого мы берем только значения «name» и «web_pages».
Пример:
name: Madurai Kamaraj University web_pages: http://www.mkuhyd.com/
Чтобы получить подробности, нам нужно просмотреть важные файлы проекта.
AppConfig.java
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; }} |
SpringMvcDispatcherServletInitializer.java