`

Spring MVC+JQuery+Google Map打造IP位置查找应用(1)

 
阅读更多

Mkyong.com is a weblog dedicated to Java/J2EE developers and Web Developers. We constantly publish useful tricks, tutorials on J2EE or web development.

All examples are simple, easy to read, and full source code available, and of course well tested in our development environment.

在本文中,读者将学习到如何使用Spring MVC框架和jQuery及Google Map,制作一个简单的根据IP位置查找应用。用户可以在页面中输入一个IP地址,然后通过Google Map显示该IP所在的大概地理位置(注:本文使用的数据库是GeoLite)

 

在本文中,读者将学习到如何使用Spring MVC框架和jQuery及Google Map,制作一个简单的根据IP位置查找应用。用户可以在页面中输入一个IP地址,然后通过Google Map显示该IP所在的大概地理位置(注:本文使用的数据库是GeoLite)。本教程完成后,其效果图如下:

在本教程中,用户将用到如下技术:

  1. Spring MVC frameworks
  2. jQuery(Ajax Request)
  3. GeoLite 数据库
  4. Google Map

其中用户的操作步骤如下:

  1. 用户输入IP地址,然后点提交按钮
  2. jQuery发出Ajax请求到Spring MVC中的控制器
  3. 在Spring MVC控制器中处理并返回JSON格式数据
  4. jQuery处理返回的json数据并通过Google Map展示给用户

1 项目结构

项目结构如下图,使用的是MAVEN工程

这里,我们要下载专门的地理数据库GeoLite,其中我们下载的是GeoLite格式的IP数据库,地址如下: http://dev.maxmind.com/geoip/legacy/geolite/,并放置在resource文件夹下。

2 MAVEN包依赖

在本项目的pom.xml中,加入如下的包依赖,如下:
 

  1. //... 
  2.     <properties> 
  3.         <spring.version>3.2.2.RELEASE</spring.version> 
  4.         <maxmind.geoip.version>1.2.10</maxmind.geoip.version> 
  5.         <jackson.version>1.9.10</jackson.version> 
  6.     </properties> 
  7.   
  8.     <dependencies> 
  9.   
  10.         <!-- Spring Core --> 
  11.         <dependency> 
  12.             <groupId>org.springframework</groupId> 
  13.             <artifactId>spring-core</artifactId> 
  14.             <version>${spring.version}</version> 
  15.         </dependency> 
  16.   
  17.         <!-- need this for @Configuration --> 
  18.         <dependency> 
  19.             <groupId>cglib</groupId> 
  20.             <artifactId>cglib</artifactId> 
  21.             <version>2.2.2</version> 
  22.         </dependency> 
  23.   
  24.         <dependency> 
  25.             <groupId>org.springframework</groupId> 
  26.             <artifactId>spring-web</artifactId> 
  27.             <version>${spring.version}</version> 
  28.         </dependency> 
  29.   
  30.         <dependency> 
  31.             <groupId>org.springframework</groupId> 
  32.             <artifactId>spring-webmvc</artifactId> 
  33.             <version>${spring.version}</version> 
  34.         </dependency> 
  35.   
  36.         <!-- ip to server location --> 
  37.         <dependency> 
  38.             <groupId>com.maxmind.geoip</groupId> 
  39.             <artifactId>geoip-api</artifactId> 
  40.             <version>${maxmind.geoip.version}</version> 
  41.         </dependency> 
  42.   
  43.         <!-- Jackson --> 
  44.         <dependency> 
  45.             <groupId>org.codehaus.jackson</groupId> 
  46.             <artifactId>jackson-mapper-asl</artifactId> 
  47.             <version>${jackson.version}</version> 
  48.         </dependency> 
  49.   
  50.     </dependencies> 
  51.     //... 

 

Spring MVC+JQuery+Google Map打造IP位置查找应用(2)

3 Spring MVC+Geo Lite

下面首先编写根据IP查找地理位置的接口,命名为ServerLocationBo.java,代码为:

  1. package com.mkyong.web.location; 
  2.  
  3. ublic interface ServerLocationBo { 
  4.  
  5. ServerLocation getLocation(String ipAddress); 

其实现类的代码为:

  1. package com.mkyong.web.location; 
  2.   
  3. import java.io.IOException; 
  4. import java.net.URL; 
  5. import org.springframework.stereotype.Component; 
  6. import com.maxmind.geoip.Location; 
  7. import com.maxmind.geoip.LookupService; 
  8. import com.maxmind.geoip.regionName; 
  9.   
  10. @Component 
  11. public class ServerLocationBoImpl implements ServerLocationBo { 
  12.   
  13.     @Override 
  14.     public ServerLocation getLocation(String ipAddress) { 
  15.   
  16.         String dataFile = "location/GeoLiteCity.dat"; 
  17.         return getLocation(ipAddress, dataFile); 
  18.   
  19.     } 
  20.   
  21.     private ServerLocation getLocation(String ipAddress, String locationDataFile) { 
  22.   
  23.       ServerLocation serverLocation = null; 
  24.   
  25.       URL url = getClass().getClassLoader().getResource(locationDataFile); 
  26.   
  27.       if (url == null) { 
  28.         System.err.println("location database is not found - " 
  29.             + locationDataFile); 
  30.       } else { 
  31.   
  32.       try { 
  33.   
  34.         serverLocation = new ServerLocation(); 
  35.   
  36.         LookupService lookup = new LookupService(url.getPath(), 
  37.                 LookupService.GEOIP_MEMORY_CACHE); 
  38.         Location locationServices = lookup.getLocation(ipAddress); 
  39.   
  40.         serverLocation.setCountryCode(locationServices.countryCode); 
  41.         serverLocation.setCountryName(locationServices.countryName); 
  42.         serverLocation.setRegion(locationServices.region); 
  43.         serverLocation.setRegionName(regionName.regionNameByCode( 
  44.             locationServices.countryCode, locationServices.region)); 
  45.         serverLocation.setCity(locationServices.city); 
  46.         serverLocation.setPostalCode(locationServices.postalCode); 
  47.         serverLocation.setLatitude( 
  48.                                 String.valueOf(locationServices.latitude)); 
  49.         serverLocation.setLongitude( 
  50.                                 String.valueOf(locationServices.longitude)); 
  51.   
  52.       } catch (IOException e) { 
  53.   
  54.         System.err.println(e.getMessage()); 
  55.   
  56.       } 
  57.   
  58.      } 
  59.   
  60.      return serverLocation; 
  61.   
  62.     } 

在上面的这个方法中,在getLocations方法中,加载了GeoLite格式的IP地址库文件GeoLiteCity.dat,并且调用getLocation方法进行IP的查找,.在getLocation方法中,通过GeoLite创建一个LookupService类的实例,其中传入要查询的IP地址库文件,然后再调用其getLocation方法进行查询,这里查询出来的结果构造成serverLocation对象,下面来看下其serverlocation对象的代码:

  1. package com.mkyong.web.location; 
  2.   
  3. public class ServerLocation { 
  4.   
  5.     private String countryCode; 
  6.     private String countryName; 
  7.     private String region; 
  8.     private String regionName; 
  9.     private String city; 
  10.     private String postalCode; 
  11.     private String latitude; 
  12.     private String longitude; 
  13.   
  14.     //getter and setter methods 
  15.   

然后我们使用Spring MVC框架中的Jackson对结果进行转换,转换为json,代码如下:

  1. package com.mkyong.web.controller; 
  2.   
  3. import org.codehaus.jackson.map.ObjectMapper; 
  4. import org.springframework.beans.factory.annotation.Autowired; 
  5. import org.springframework.stereotype.Controller; 
  6. import org.springframework.web.bind.annotation.RequestMapping; 
  7. import org.springframework.web.bind.annotation.RequestMethod; 
  8. import org.springframework.web.bind.annotation.RequestParam; 
  9. import org.springframework.web.bind.annotation.ResponseBody; 
  10. import org.springframework.web.servlet.ModelAndView; 
  11.   
  12. import com.mkyong.web.location.ServerLocation; 
  13. import com.mkyong.web.location.ServerLocationBo; 
  14.   
  15. @Controller 
  16. public class MapController { 
  17.   
  18.     @Autowired 
  19.     ServerLocationBo serverLocationBo; 
  20.   
  21.     @RequestMapping(value = "/", method = RequestMethod.GET) 
  22.     public ModelAndView getPages() { 
  23.   
  24.         ModelAndView model = new ModelAndView("map"); 
  25.         return model; 
  26.   
  27.     } 
  28.   
  29.     //return back json string 
  30.     @RequestMapping(value = "/getLocationByIpAddress", method = RequestMethod.GET) 
  31.     public @ResponseBody 
  32.     String getDomainInJsonFormat(@RequestParam String ipAddress) { 
  33.   
  34.         ObjectMapper mapper = new ObjectMapper(); 
  35.   
  36.         ServerLocation location = serverLocationBo.getLocation(ipAddress); 
  37.   
  38.         String result = ""; 
  39.   
  40.         try { 
  41.             result = mapper.writeValueAsString(location); 
  42.         } catch (Exception e) { 
  43.   
  44.             e.printStackTrace(); 
  45.         } 
  46.   
  47.         return result; 
  48.   
  49.     } 
  50.   

这对于熟悉Spring MVC的用户应该并不陌生。经过转换后的结果转换为字符串。

Spring MVC+JQuery+Google Map打造IP位置查找应用(3)

4 JSP+jQuery+Google Map展示最后的结果

最后我们在页面中,通过jQuery发送ajax请求调用Spring MVC控制层,然后将返回的结果展示在页面中,代码如下:

  1. <html> 
  2. <head> 
  3. <script src="http://maps.google.com/maps/api/js?sensor=true"></script> 
  4. <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
  5. </head> 
  6. <body> 
  7.   <h2>Spring MVC + jQuery + Google Map</h2> 
  8.   
  9.   <div> 
  10.     <input type="text" placeholder="0.0.0.0" id="w-input-search" value=""> 
  11.     <span> 
  12.         <button id="w-button-search" type="button">Search</button> 
  13.     </span> 
  14.   </div> 
  15.   
  16.   <script> 
  17.   $(document).ready(function() { 
  18.   
  19.     $("#w-button-search").click(function() { 
  20.   
  21.         $.getJSON("${pageContext.request.contextPath}/getLocationByIpAddress", 
  22.         { 
  23.             ipAddress : $('#w-input-search').val() 
  24.         },  
  25.         function(data) { 
  26.   
  27.             var data = JSON.stringify(data); 
  28.             var json = JSON.parse(data); 
  29.   
  30.             showMap(json["latitude"],json["longitude"]) 
  31.   
  32.             $("#result").html(data) 
  33.   
  34.         }) 
  35.         .done(function() {                           
  36.         }) 
  37.         .fail(function() {  
  38.         }) 
  39.         .complete(function() {           
  40.         }); 
  41.   
  42.     }); 
  43.   
  44.     var map; 
  45.   
  46.     function showMap(latitude,longitude) {  
  47.   
  48.         var googleLatandLong = new google.maps.LatLng(latitude,longitude); 
  49.   
  50.         var mapOptions = {  
  51.             zoom: 5, 
  52.             center: googleLatandLong, 
  53.             mapTypeId: google.maps.MapTypeId.ROADMAP  
  54.         }; 
  55.   
  56.         var mapDiv = document.getElementById("map"); 
  57.         map = new google.maps.Map(mapDiv, mapOptions); 
  58.   
  59.         var title = "Server Location";  
  60.         addMarker(map, googleLatandLong, title, ""); 
  61.   
  62.     } 
  63.   
  64.     function addMarker(map, latlong, title, content) {  
  65.   
  66.         var markerOptions = { 
  67.             position: latlong,  
  68.             map: map, 
  69.             title: title,  
  70.             clickable: true 
  71.         }; 
  72.         var marker = new google.maps.Marker(markerOptions);  
  73.     } 
  74.   
  75.   }); 
  76.   </script> 
  77.   <br/> 
  78.   <div id="result"></div> 
  79.   <br/> 
  80.   <div style="width:600px;height:400px" id="map"></div> 
  81.   
  82. </body> 
  83. </html> 

本文的代码可以通过如下地址下载:http://www.mkyong.com/wp-content/uploads/2013/10/SpringMvc-jQuery-GoogleMap.zip

原文链接:http://www.mkyong.com/spring-mvc/spring-mvc-find

【编辑推荐】

分享到:
评论

相关推荐

    基于Spring MVC和Mybatis的Java企业级应用设计源码

    本项目是基于Spring MVC和...该系统集成了Spring MVC、Mybatis和jQuery等框架,提供了企业级应用的开发解决方案。项目结构清晰,代码注释详尽,适合用于学习和研究Spring MVC和Mybatis在企业级应用开发中的应用。

    Spring MVC不能直接接收list类型参数的问题

    前端使用jquery向后台传递数组类型的参数,Java后台直接通过List类型接收,会发现无法取到参数。

    基于Spring Boot的个人在线理财系统设计源码

    本设计源码提供了一个基于...该系统采用了Spring Boot、MyBatis、Spring MVC、Bootstrap、jQuery和Thymeleaf等技术,适合用于学习和实践Java、HTML、JavaScript、CSS以及前端技术,以及开发个人在线理财相关的系统。

    基于SSM框架+Mysql的企业CRM客户关系管理系统项目源码+数据库+项目说明.zip

    Spring+SpringMVC+MyBatis+Thymeleaf+Vue+JS+Jquery+Axios+Json 服务器: Tomcat_9.0.60 数据库: MySQL_8.0.28 开发工具:IDEA_2021.3.3 页面:Bootstrap_3.3.0 ## 2️⃣已实现的功能 **:star: 账号登录** ...

    java面试宝典

    22、我们在web 应用开发过程中经常遇到输出某种编码的字符,如iso8859-1等,如何输出一个某种编码的字符串? 10 23、String 和StringBuffer 的区别? 10 24、String, StringBuffer StringBuilder 的区别。 10 25、...

    单点登录源码

    SpringMVC | MVC框架 | [http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc](http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc) ...

    java面试题

    Java 软件工程师面试资料大整合 1 Java 面霸 1 1. int 和 Integer 有什么区别? 8 2. String 和StringBuffer的区别 8 3. 运行时异常与一般异常有何异同? 8 4. 说出ArrayList,Vector,LinkedList的存储性能和特性 8 5...

    Java学习笔记-个人整理的

    \contentsline {chapter}{Contents}{2}{section*.1} {1}Java基础}{17}{chapter.1} {1.1}基本语法}{17}{section.1.1} {1.2}数字表达方式}{17}{section.1.2} {1.3}补码}{19}{section.1.3} {1.3.1}总结}{23}{...

    千方百计笔试题大全

    22、我们在web 应用开发过程中经常遇到输出某种编码的字符,如iso8859-1等,如何输出一个某种编码的字符串? 10 23、String 和StringBuffer 的区别? 10 24、String, StringBuffer StringBuilder 的区别。 10 25、...

Global site tag (gtag.js) - Google Analytics