Spring MVC - найти местоположение с помощью IP-адреса (jQuery + Google Map)
В этом руководстве мы покажем вам, как найти местоположение с помощью IP-адреса, используя следующие технологии:
-
Spring MVC Frameworkы.
-
JQuery (Ajax Request).
-
База данных GeoLite.
-
Google Map.
Просмотрите потоки учебника
-
Страница с вводом текста и кнопкой.
-
Введите IP-адрес и нажмите на кнопку.
-
jQuery запускает Ajax-запрос к Spring Controller.
-
Spring контролирует процесс и возвращает обратно строку json.
-
jQuery обрабатывает возвращенный json и отображает местоположение на Google Map.
1. Каталог проектов
Просмотрите окончательную структуру каталогов проекта, стандартный проект Maven.
Note
Загрузите бесплатные бесплатные базы данных GeoLite -GeoLiteCity.dat и поместите их в папкуresources
.
2. Зависимости проекта
Объявляет Spring-фреймворки, зависимости Джексона и geoip-api.
pom.xml
//...3.2.2.RELEASE 1.2.10 1.9.10 //... org.springframework spring-core ${spring.version} cglib cglib 2.2.2 org.springframework spring-web ${spring.version} org.springframework spring-webmvc ${spring.version} com.maxmind.geoip geoip-api ${maxmind.geoip.version} org.codehaus.jackson jackson-mapper-asl ${jackson.version}
3. Spring MVC + GeoLite
Получить местоположение с базой данных GeoLite.
ServerLocationBo.java
package com.example.web.location; public interface ServerLocationBo { ServerLocation getLocation(String ipAddress); }
ServerLocationBoImpl.java
package com.example.web.location; import java.io.IOException; import java.net.URL; import org.springframework.stereotype.Component; import com.maxmind.geoip.Location; import com.maxmind.geoip.LookupService; import com.maxmind.geoip.regionName; @Component public class ServerLocationBoImpl implements ServerLocationBo { @Override public ServerLocation getLocation(String ipAddress) { String dataFile = "location/GeoLiteCity.dat"; return getLocation(ipAddress, dataFile); } private ServerLocation getLocation(String ipAddress, String locationDataFile) { ServerLocation serverLocation = null; URL url = getClass().getClassLoader().getResource(locationDataFile); if (url == null) { System.err.println("location database is not found - " + locationDataFile); } else { try { serverLocation = new ServerLocation(); LookupService lookup = new LookupService(url.getPath(), LookupService.GEOIP_MEMORY_CACHE); Location locationServices = lookup.getLocation(ipAddress); serverLocation.setCountryCode(locationServices.countryCode); serverLocation.setCountryName(locationServices.countryName); serverLocation.setRegion(locationServices.region); serverLocation.setRegionName(regionName.regionNameByCode( locationServices.countryCode, locationServices.region)); serverLocation.setCity(locationServices.city); serverLocation.setPostalCode(locationServices.postalCode); serverLocation.setLatitude( String.valueOf(locationServices.latitude)); serverLocation.setLongitude( String.valueOf(locationServices.longitude)); } catch (IOException e) { System.err.println(e.getMessage()); } } return serverLocation; } }
ServerLocation.java
package com.example.web.location; public class ServerLocation { private String countryCode; private String countryName; private String region; private String regionName; private String city; private String postalCode; private String latitude; private String longitude; //getter and setter methods }
Контроллер Spring, преобразуйтеServerLocation
с библиотекойJackson
и верните обратно строку json.
MapController.java
package com.example.web.controller; import org.codehaus.jackson.map.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.example.web.location.ServerLocation; import com.example.web.location.ServerLocationBo; @Controller public class MapController { @Autowired ServerLocationBo serverLocationBo; @RequestMapping(value = "/", method = RequestMethod.GET) public ModelAndView getPages() { ModelAndView model = new ModelAndView("map"); return model; } //return back json string @RequestMapping(value = "/getLocationByIpAddress", method = RequestMethod.GET) public @ResponseBody String getDomainInJsonFormat(@RequestParam String ipAddress) { ObjectMapper mapper = new ObjectMapper(); ServerLocation location = serverLocationBo.getLocation(ipAddress); String result = ""; try { result = mapper.writeValueAsString(location); } catch (Exception e) { e.printStackTrace(); } return result; } }
4. JSP + jQuery + Google Map
Когда нажата кнопка поиска, jQuery запускает запрос Ajax, обрабатывает данные и обновляет карту Google.
map.jsp
Spring MVC + jQuery + Google Map
5. Demo
IP-адрес: 74.125.135.102
IP-адрес: 183.81.166.110
Скачать исходный код
Скачать -SpringMvc-jQuery-GoogleMap (18 КБ)