在本文中,读者将学习到如何使用Spring MVC框架和jQuery及Google Map,制作一个简单的根据IP位置查找应用。用户可以在页面中输入一个IP地址,然后通过Google Map显示该IP所在的大概地理位置(注:本文使用的数据库是GeoLite)。本教程完成后,其效果图如下:
在本教程中,用户将用到如下技术:
- Spring MVC frameworks
- jQuery(Ajax Request)
- GeoLite 数据库
- Google Map
其中用户的操作步骤如下:
- 用户输入IP地址,然后点提交按钮
- jQuery发出Ajax请求到Spring MVC中的控制器
- 在Spring MVC控制器中处理并返回JSON格式数据
- jQuery处理返回的json数据并通过Google Map展示给用户
1 项目结构
项目结构如下图,使用的是MAVEN工程
这里,我们要下载专门的地理数据库GeoLite,其中我们下载的是GeoLite格式的IP数据库,地址如下: http://dev.maxmind.com/geoip/legacy/geolite/,并放置在resource文件夹下。
2 MAVEN包依赖
在本项目的pom.xml中,加入如下的包依赖,如下:
- //...
- <properties>
- <spring.version>3.2.2.RELEASE</spring.version>
- <maxmind.geoip.version>1.2.10</maxmind.geoip.version>
- <jackson.version>1.9.10</jackson.version>
- </properties>
- <dependencies>
- <!-- Spring Core -->
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-core</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <!-- need this for @Configuration -->
- <dependency>
- <groupId>cglib</groupId>
- <artifactId>cglib</artifactId>
- <version>2.2.2</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-web</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <!-- ip to server location -->
- <dependency>
- <groupId>com.maxmind.geoip</groupId>
- <artifactId>geoip-api</artifactId>
- <version>${maxmind.geoip.version}</version>
- </dependency>
- <!-- Jackson -->
- <dependency>
- <groupId>org.codehaus.jackson</groupId>
- <artifactId>jackson-mapper-asl</artifactId>
- <version>${jackson.version}</version>
- </dependency>
- </dependencies>
- //...
#p#
3 Spring MVC+Geo Lite
下面首先编写根据IP查找地理位置的接口,命名为ServerLocationBo.java,代码为:
- package com.mkyong.web.location;
- ublic interface ServerLocationBo {
- ServerLocation getLocation(String ipAddress);
其实现类的代码为:
- package com.mkyong.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;
- }
- }
在上面的这个方法中,在getLocations方法中,加载了GeoLite格式的IP地址库文件GeoLiteCity.dat,并且调用getLocation方法进行 IP的查找,.在getLocation方法中,通过GeoLite创建一个LookupService类的实例,其中传入要查询的IP地址库文件,然后再调用其getLocation方法进行查询,这里查询出来的结果构造成serverLocation对象,下面来看下其serverlocation对象的代码:
- package com.mkyong.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 MVC框架中的Jackson对结果进行转换,转换为json,代码如下:
- package com.mkyong.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.mkyong.web.location.ServerLocation;
- import com.mkyong.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;
- }
- }
这对于熟悉Spring MVC的用户应该并不陌生。经过转换后的结果转换为字符串。
#p#
4 JSP+jQuery+Google Map展示最后的结果
最后我们在页面中,通过jQuery发送ajax请求调用Spring MVC控制层,然后将返回的结果展示在页面中,代码如下:
- <html>
- <head>
- <script src="http://maps.google.com/maps/api/js?sensor=true"></script>
- <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
- </head>
- <body>
- <h2>Spring MVC + jQuery + Google Map</h2>
- <div>
- <input type="text" placeholder="0.0.0.0" id="w-input-search" value="">
- <span>
- <button id="w-button-search" type="button">Search</button>
- </span>
- </div>
- <script>
- $(document).ready(function() {
- $("#w-button-search").click(function() {
- $.getJSON("${pageContext.request.contextPath}/getLocationByIpAddress",
- {
- ipAddress : $('#w-input-search').val()
- },
- function(data) {
- var data = JSON.stringify(data);
- var json = JSON.parse(data);
- showMap(json["latitude"],json["longitude"])
- $("#result").html(data)
- })
- .done(function() {
- })
- .fail(function() {
- })
- .complete(function() {
- });
- });
- var map;
- function showMap(latitude,longitude) {
- var googleLatandLong = new google.maps.LatLng(latitude,longitude);
- var mapOptions = {
- zoom: 5,
- center: googleLatandLong,
- mapTypeId: google.maps.MapTypeId.ROADMAP
- };
- var mapDiv = document.getElementById("map");
- map = new google.maps.Map(mapDiv, mapOptions);
- var title = "Server Location";
- addMarker(map, googleLatandLong, title, "");
- }
- function addMarker(map, latlong, title, content) {
- var markerOptions = {
- position: latlong,
- map: map,
- title: title,
- clickable: true
- };
- var marker = new google.maps.Marker(markerOptions);
- }
- });
- </script>
- <br/>
- <div id="result"></div>
- <br/>
- <div style="width:600px;height:400px" id="map"></div>
- </body>
- </html>
本文的代码可以通过如下地址下载:http://www.mkyong.com/wp-content/uploads/2013/10/SpringMvc-jQuery-GoogleMap.zip
原文链接:http://www.mkyong.com/spring-mvc/spring-mvc-find