通过前端获取客户端ip和所在城市,并在后端获得这些值

时间:2022-08-28 13:11:34

一:jsp的代码:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<body>
    <div id="allmap"></div>
</body>
<html>
  <head>
    <script language="javascript" src="http://www.codefans.net/ajaxjs/jquery1.3.2.js"></script>
    <script type="text/javascript" src="/js/jquery-1.8.3.min.js"></script>
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=7hofO0Vu1ecpKW4O3pvsXc39"></script>
    <title>获取IP和当前城市</title>
    <script type="text/javascript"> // 百度地图API功能 var map = new BMap.Map("allmap"); var city=null; function myFun(result){ var cityName = result.name; map.setCenter(cityName); document.getElementById('city').value=cityName; city = cityName; return cityName; } var myCity = new BMap.LocalCity(); myCity.get(myFun); </script>
    <script language="javascript"> jQuery(function($){ var url = 'http://chaxun.1616.net/s.php?type=ip&output=json&callback=?&_='+Math.random(); $.getJSON(url, function(data){ document.getElementById("ip").value=data.Ip ip = document.getElementById("ip").value; myCity.get(myFun); $.post("address_getIpAddress.action", { ip:data.Ip, city:city }, function(data,status){ //alert("Data: " + data + "\nStatus: " + status); }); }); }) </script>



  </head>

  <body>
    <form action="address_getIpAddress.action" method="post">
        你的ip:<input type="text" id="ip" name ="ip" class="ip">
        你的位置:<input type="text" id="city" name ="city" class="city">
        <input type="submit" >
    </form>
  </body>
</html>

二:后台的代码:

package com.jfl.web;

import java.io.PrintStream;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.deploy.ContextService;
import org.apache.jasper.tagplugins.jstl.core.Out;
import org.apache.struts2.ServletActionContext;

import com.jfl.util.Utli;
import com.opensymphony.xwork2.ActionSupport;

public class CommonAction extends ActionSupport{

    public String getIpAddress() throws Exception{
        HttpServletRequest request = ServletActionContext.getRequest();
        String ipp = request.getParameter("ip");
        String city = request.getParameter("city");
        System.out.println(ipp);
        System.out.println(city);
        HttpServletResponse response = ServletActionContext.getResponse();
        PrintWriter out = response.getWriter();
        out.printf("jfl");
        return null;
    }   
}

三:运行的结果:
①页面结果:
通过前端获取客户端ip和所在城市,并在后端获得这些值
②控制台输出结果:
通过前端获取客户端ip和所在城市,并在后端获得这些值