Spring MVC — получите вероятность пола, указав имя с помощью REST API
Многие забавные вызовы REST API доступны с открытым исходным кодом. Предположим, если мы хотим сохранить имя для наших близких и родных, мы можем просто проверить это с помощью вызова REST API и получить пол, какова вероятность того, что это пол, и сколько раз он приходит с ним? Соответствующий вызов REST API
https://api.genderize.io?name=<Provide your desired name here>
Пример:
https://api.genderize.io?name=rachel
Результирующий вывод JSON:
Давайте получим эти сведения с помощью проекта Spring MVC, который обращается к вызову REST API, получает ответ JSON, анализирует данные и выдает результат так, как мы хотим. Давайте также проверим тестовый пример JUNIT. Для этого мы будем использовать «org.springframework.test.web.servlet.MockMvc».
Реализация
Структура проекта:
Это проект, управляемый maven.
пом.xml
XML
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 <modelVersion>4.0.0</modelVersion> <groupId>com.findGender.findGender_Rest_API</groupId> <artifactId>genderFind_Rest_API</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>profileGenerator</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>GenderFinding</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, который отправляет имя в файл контроллера, который обращается к вызову REST API и получает детали, анализирует и отображает их на экране.
findGender.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>Finding Gender</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: 500px; } .main-form { margin: 50px auto 0px; } .profile-area { margin: 10px auto; } .main-form section, .profile-area section { margin-bottom: 15px; background: #33FF7A; 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> <h5 class="text-center">Enter a name to find Gender</h5> <div class="form-group"> <input id="genderName" type="text" class="form-control" placeholder="Enter a name to find Gender..." required="required"> </div> <div class="form-group"> <button onclick="loadData()" class="btn btn-primary btn-block">Find Gender 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>Entered Name : <span id="name"></span></strong></p> <p><strong>Gender : <span id="gender"></span></strong></p> <p><strong>Probability : <span id="probability"></span></strong></p> <p><strong>Count : <span id="count"></span></strong></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 genderName = document.getElementById("genderName").value; var otherCurrency1,otherCurrency2; if(genderName != "" && genderName != null) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var jsonResponse = JSON.parse(this.responseText); document.getElementById("name").innerHTML = jsonResponse.name; document.getElementById("gender").innerHTML = jsonResponse.gender; document.getElementById("probability").innerHTML = jsonResponse.probability; document.getElementById("count").innerHTML = jsonResponse.count; document.getElementById("loader").classList.add("hideElement"); document.getElementById("profile").classList.remove("hideElement"); } }; xhttp.open("GET", "getGenderDetails?genderName=" + genderName, true); xhttp.send(); console.log("done"); } else { console.log("Enter genderName...") } }</script></html> |
При выполнении файла мы получим это
Выход:
Тестовый случай 1:
Давайте проверим правильность отображаемого вывода, выполнив вызов программы и MockMVC. Давайте посмотрим на java-файл для этого.
FindingGenderControllerTest.java
Java
import static org.junit.Assert.assertEquals;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import com.findGender.findGender_Rest_API.controller.FindingGenderController;import com.google.gson.Gson;import com.google.gson.JsonArray;import com.google.gson.JsonObject;import java.io.BufferedReader;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import java.util.StringTokenizer;import org.junit.Before;import org.junit.Test;import org.springframework.test.web.servlet.MockMvc;import org.springframework.test.web.servlet.MvcResult;import org.springframework.test.web.servlet.setup.MockMvcBuilders;import org.springframework.util.StringUtils; public class FindingGenderControllerTest { private MockMvc mockMvc; @Before public void setup() { this.mockMvc = MockMvcBuilders <
РЕКОМЕНДУЕМЫЕ СТАТЬИ |