Ajax的简单实例

这个例子作用是:修正谷歌map在中国的偏移,页面输入真实GPS数据后,通过ajax传回,经过处理后页面无刷新返回偏移后的数据,以便在map中正确定位。

页面,index.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<head>
<title>EARTH</title>

<script type=”text/javascript”>
var xmlHttpReq;
function createXMLHttpRequest() {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlHttpReq = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlHttpReq = new ActiveXObject(“Microsoft.XMLHTTP”);
}
}

function sendRequest(url) {
//调用创建XMLHttpReqeust对象的函数
createXMLHttpRequest();
//alert(url);
xmlHttpReq.open(“GET”, url, true);
//调用回调函数(当状态发生改变时调用回调函数)
xmlHttpReq.onreadystatechange = proccessReqeust;
//发送请求
xmlHttpReq.send(null);
}

function proccessReqeust() {
//根据状态
//alert(“当前状态为:” + xmlHttpReq.readyState);
//判断对象状态
if (xmlHttpReq.readyState == 4) {
if (xmlHttpReq.status == 200) {
//以XML接收响应数据
document.getElementById(“offlon”).innerHTML = xmlHttpReq.responseXML
.getElementsByTagName(“offlon”)[0].firstChild.data;

document.getElementById(“offlat”).innerHTML = xmlHttpReq.responseXML
.getElementsByTagName(“offlat”)[0].firstChild.data;

//Add map point
var myLatlng = new google.maps.LatLng(parseFloat( xmlHttpReq.responseXML
.getElementsByTagName(“offlat”)[0].firstChild.data), parseFloat(xmlHttpReq.responseXML
.getElementsByTagName(“offlon”)[0].firstChild.data));
var marker = new google.maps.Marker({
position : myLatlng,
map : map,
title : “Hello World!”
});
//以文本方式接收返回数据
//var respInfomation = xmlHttpReq.responseText;
//alert(respInfomation);
} else {
alert(“响应异常”);
}
}
}

//得到表单信息
function sendInfo() {
var lon = form1.lon.value;
var lat = form1.lat.value;
sendRequest(‘offset?lat=’ + lat + ‘&lon=’ + lon);
}
</script>//以上是Ajax简单的例子

<script
src=”>
<script type=”text/javascript”
src=”http://maps.google.com/maps/api/js?sensor=false“>

</script>
<script>
google.load(“earth”, “1”);
var map;
var ge = null;
var placemark = null;
var geocoder;

function init() {
google.earth.createInstance(“map3d”, initCallback, failureCallback);

var myLatlng = new google.maps.LatLng(30.4419, 120.1419);
var myOptions = {
zoom : 12,
center : myLatlng,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById(“map”), myOptions);
}

function initCallback(object) {
ge = object;
ge.getWindow().setVisibility(true);

ge.getNavigationControl().setVisibility(ge.VISIBILITY_HIDE);

}

function failureCallback(object) {
}

function showBalloon() {
var balloon = ge.createFeatureBalloon(”);
balloon.setFeature(placemark);
balloon.setMinWidth(400);
ge.setBalloon(balloon);
}
function addp() {
var lat = form1.lat.value;
var lon = form1.lon.value;

// Create the placemark.
placemark = ge.createPlacemark(”);
placemark.setName(“TEST”);
placemark.setDescription(‘This is a description’);

// Set the placemark’s location.
var point = ge.createPoint(”);
point.setLatitude(parseFloat(lat));
point.setLongitude(parseFloat(lon));
placemark.setGeometry(point);

// Add the placemark to Earth.
ge.getFeatures().appendChild(placemark);

// Set the FlyTo speed
ge.getOptions().setFlyToSpeed(1);

// Move the camera.
var la = ge.createLookAt(”);
la.set(parseFloat(lat), parseFloat(lon), 0,
ge.ALTITUDE_RELATIVE_TO_GROUND, 0, 0, 20000);
ge.getView().setAbstractView(la);

}

function codeAddress() {
var address = document.getElementById(“address”).value;
geocoder.geocode({
‘address’ : address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map : map,
position : results[0].geometry.location
});
} else {
alert(“Geocode was not successful for the following reason: ”
+ status);
}
});
}
</script>//以上调用google API
</head>
<body onload=’init()’ id=’body’>
<form action=”offset” method=”post” name=”form1″>
纬度: <input type=”text” name=”lat” value=”30.278342″ /> 经度: <input
type=”text” name=”lon” value=”120.117099″ /> <input type=”button”
value=”offset” onClick=”sendInfo();addp()” />  <input type=”text”
id=”address” value=”Sydney, NSW” /><input type=”button” value=”解析地址”
onClick=”codeAddress()” /><br> <b> offlat:</b> <span
id=”offlat”></span> <b>offlon:</b> <span id=”offlon”></span>
</form>

<table style=”width: 1200px”>
<tr>
<td style=”width: 50%”>
<div id=’map3d’ style=’border: 1px solid silver; height: 600px;’></div>
</td>
<td style=”width: 50%”>
<div id=”map” style=”border: 1px solid #000; height: 600px;”></div>
</td>
</tr>
</table>
</body>
</html>

 

后台

package com.ant.ser;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @author Still
* @创建时间:2012-2-16 下午01:33:12
*/
public class OffsetServlet extends HttpServlet {

private static final long serialVersionUID = 6991271447420179202L;

@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 设置请求和响应的编码格式
request.setCharacterEncoding("UTF-8");
// 设置响应格式应为XML
response.setContentType("text/xml;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");

PrintWriter out = response.getWriter();
out.println("<respData>");

double lat = Double.valueOf(request.getParameter("lat"));
double lon = Double.valueOf(request.getParameter("lon"));

double lat_p=GoogleTest.latToPixel(lat, 18);//经纬度转像素
double lon_p=GoogleTest.lngToPixel(lon, 18);

Map offsetMap = new HashMap();
offsetMap = TestGoogleOffset.readOffsetData("d:/offset.dat", lon, lat);//此处调用偏移数据,查询偏移像素

double lat_s=GoogleTest.pixelToLat(lat_p+(Integer)offsetMap.get("offY"), 18);//此处将实际像素加上偏移像素再转经纬度
double lon_s=GoogleTest.pixelToLng(lon_p+(Integer)offsetMap.get("offX"), 18);
out.println("<offlat>" + lat_s + "</offlat>");
out.println("<offlon>" + lon_s + "</offlon>");
out.println("</respData>");
}

@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}

(from 当年的,已经不存在的,我的百度空间)

Android 图片的读取 缩放 保存

注意AndroidManifest配置权限:(在SD卡写入数据)

 

代码:

从另一个Activity 上传入byte型的数据,通过 bmp = BitmapFactory.decodeByteArray(txInfo, 0, txInfo.length);生成位图。

然后有用到ZoomControls图片缩放,最后可以保存图片到sd卡。

package com.login.main;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ZoomControls;

public class List_tx extends Activity {

private ImageView imageView1;
private ZoomControls zoom;
private Button saveButton;
private float scaleWidth = 1;
private float scaleHeight = 1;
private Bitmap bmp;
private int zooms = 0;
private ProgressDialog m_Dialog = null;
private Handler handler = new Handler();
private String xh = "";

@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.list_tx);
Bundle b = this.getIntent().getExtras();
byte[] txInfo = b.getByteArray("txInfo");
xh = b.getString("xh");

saveButton = (Button) findViewById(R.id.saveButton);
saveButton.setOnClickListener(saveClick);
imageView1 = (ImageView) findViewById(R.id.imageView1);
bmp = BitmapFactory.decodeByteArray(txInfo, 0, txInfo.length);// 生成位图
imageView1.setImageBitmap(bmp);

zoom = (ZoomControls) findViewById(R.id.zoomcontrol);
zoom.setIsZoomInEnabled(true);
zoom.setIsZoomOutEnabled(true);

// 图片放大
zoom.setOnZoomInClickListener(new OnClickListener() {
public void onClick(View v) {
zoom.setIsZoomOutEnabled(true);
int bmpWidth = bmp.getWidth();
int bmpHeight = bmp.getHeight();
// 设置图片放大但比例
double scale = 1.25;
// 计算这次要放大的比例
if (zooms >= -3 && zooms < 6) {
scaleWidth = (float) (scaleWidth * scale);
scaleHeight = (float) (scaleHeight * scale);
// 产生新的大小但Bitmap对象
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizeBmp = Bitmap.createBitmap(bmp, 0, 0, bmpWidth,
bmpHeight, matrix, true);
imageView1.setImageBitmap(resizeBmp);
zooms++;
} else
zoom.setIsZoomInEnabled(false);

}

});
// 图片减小
zoom.setOnZoomOutClickListener(new OnClickListener() {

public void onClick(View v) {
zoom.setIsZoomInEnabled(true);
int bmpWidth = bmp.getWidth();
int bmpHeight = bmp.getHeight();
// 设置图片放大但比例
double scale = 0.8;
// 计算这次要放大的比例
if (zooms > -3 && zooms <= 6) {
scaleWidth = (float) (scaleWidth * scale);
scaleHeight = (float) (scaleHeight * scale);
// 产生新的大小但Bitmap对象
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizeBmp = Bitmap.createBitmap(bmp, 0, 0, bmpWidth,
bmpHeight, matrix, true);
imageView1.setImageBitmap(resizeBmp);
zooms--;
} else
zoom.setIsZoomOutEnabled(false);
}

});

}

// 保存
OnClickListener saveClick = new OnClickListener() {

public void onClick(final View v) {
m_Dialog = ProgressDialog.show(List_tx.this, "请稍后...", "图像保存中...",
true);

new Thread(new Runnable() {

public void run() {
File file = new File("/sdcard/" + xh + ".jpeg");
try {
FileOutputStream out = new FileOutputStream(file);
if (bmp.compress(Bitmap.CompressFormat.JPEG, 100, out)) {
out.flush();
out.close();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("FileNotFoundException");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("FileNotFoundException");
e.printStackTrace();
}

// 更新界面
handler.post(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),
"头像保存在" + "/sdcard/" + xh + ".jpeg",
Toast.LENGTH_SHORT).show();
}
});
m_Dialog.dismiss();
}
}).start();
}

};

}

(from 当年的,已经不存在的,我的百度空间)

Android 再按一次退出 的实现


private static Boolean isExit = false;

private static Boolean hasTask = false;

Timer tExit = new Timer();

TimerTask task = new TimerTask() {
public void run() {

isExit = false;

hasTask = true;

}

};

@Override

public boolean onKeyDown(int keyCode, KeyEvent event) {

if (keyCode == KeyEvent.KEYCODE_BACK

&& event.getAction() == KeyEvent.ACTION_DOWN) {

if (isExit == false) {

isExit = true;
Toast.makeText(getApplicationContext(), "再按一次退出程序",

Toast.LENGTH_SHORT).show();

if (!hasTask) {

tExit.schedule(task, 2000);

}

} else {

finish();

System.exit(0);

}

return false;

}

return super.onKeyDown(keyCode, event);

}
(from 当年的,已经不存在的,我的百度空间)

Android隐藏状态栏和标题栏

方法1:
修改AndroidManifest.xml
隐藏标题栏:android:theme=”@android:style/Theme.NoTitleBar”.

隐藏状态栏(全屏):android:theme=”@android:style/Theme.NoTitleBar.Fullscreen”.

方法2:
修改代码(setContentView(R.layout.main); 之前)

super.onCreate(savedInstanceState);
//隐藏标题栏

requestWindowFeature(Window.FEATURE_NO_TITLE);
//隐藏状态栏(全屏)

getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN , WindowManager.LayoutParams. FLAG_FULLSCREEN);

setContentView(R.layout.main);

注:
建议使用方法1,方法2会在开始时候短暂的显示标题栏。

(from 当年的,已经不存在的,我的百度空间)

查询网易邮箱注册时间(年 月 日)

网易邮箱的 自助查询 只能查询邮箱注册的年份,偶然想知道具体日期,刚好在网上看到这个方法。
具体是查看页面原代码,可能不太好找到具体有注册日期的源文件,建议用Chrome浏览器按F12打开 开发者工具,在resources页面,

直接搜索 ‘user_creation_date’:new Date ,
找到’user_creation_date’:new Date(*,*,*),

(*,*,*)就是你的注册年月日。
不过JavaScript表示月份是从0开始的 所以真实月份还要+1。

(from 当年的,已经不存在的,我的百度空间)

James配置以及发送外网邮件配置

1.服务器安装:
第一步:安装JDK,配置好环境变量等;
第二步:从http://james.apache.org/下载James,并解压,如apache-james-2.3.2.zip;
第三步:运行解压目录下的/james/bin/run.bat,若环境变量正确,将提示如下:

Using PHOENIX_HOME:   D:\james-2.3.2

Using PHOENIX_TMPDIR: D:\james-2.3.2\temp

Using JAVA_HOME:      D:\Program Files\Java\jdk1.6.0_24

 

Phoenix 4.2

 

James Mail Server 2.3.2

Remote Manager Service started plain:4555

POP3 Service started plain:110

SMTP Service started plain:25

NNTP Service started plain:119

FetchMail Disabled
这样服务器就基本配置成功了。

2.配置:

打开../james/apps/james/SAR-INF/config.xml文件,
1. 找到<servernames autodetect=”true” autodetectIP=”true”> 设成 <servernames
autodetect=”false” autodetectIP=”false”> autodetct设为true会自动侦测你的主机名,
设成false会用你指定的server name. autodetectIP设为true会为你的servername加上ip.
2. 设置servername 将默认的为localhost改成你的server名字 如king.cn, 然后打开
C:/WINDOWS/system32/drivers/etc/hosts文件,添加 127.0.0.1   king.cn
3. 注释掉
<mailet match=”RemoteAddrNotInNetwork=127.0.0.1″ class=”ToProcessor>
<processor> relay-denied </processor>
<notice>550 – Requested action not taken: relaying denied</notice>
</mailet>
4. 配置DNS Server
在cmd中用ipconfig /all 命令查看你的dns server ip
添加如下:
<dnsserver>
<servers>
<server>DNS1</server>
<server>DNS2</server>
同时设置autodiscover为false

到这里就可以向外网发送邮件了,本人测试发送到QQ、163邮箱正常。

3.  帐号管理
James的账号管理是通过telnet完成的,登录命令为:
telnet [你设置的servername] 4555
其中servername也可以换成IP,4555是端口号。登录时需要用户名和密码,初始的用户名和密码均为root。若登录成功,提示如下:

JAMES Remote Administration Tool 2.3.2

Please enter your login and password

Login id:

root

Password:

root

Welcome root. HELP for a list of commands

输入help,将出现命令的帮助,信息如下:

Currently implemented commands:

help                                    display this help

listusers                               display existing accounts

countusers                              display the number of existing accounts

adduser [username] [password]           add a new user

verify [username]                       verify if specified user exist

deluser [username]                      delete existing user

setpassword [username] [password]       sets a user’s password

setalias [user] [alias]                 locally forwards all email for ‘user’ to

‘alias’

showalias [username]                    shows a user’s current email alias

unsetalias [user]                       unsets an alias for ‘user’

setforwarding [username] [emailaddress] forwards a user’s email to another email

address

showforwarding [username]               shows a user’s current email forwarding

unsetforwarding [username]              removes a forward

user [repositoryname]                   change to another user repository

shutdown                                kills the current JVM (convenient when J

ames is run as a daemon)

quit                                    close connection

其中添加用户为adduser,例如:adduser holen 123456。

4.代码:


public void sendEmail() {

Properties props = new Properties();

// Setup mail server
props.put(“mail.smtp.host”, host);
props.put(“mail.smtp.auth”, “true”); // 这样才能通过验证

// Get session
Session session = Session.getDefaultInstance(props);
// watch the mail commands go by to the mail server
session.setDebug(isTrue);// 记录日志打开

 

// Define message

MimeMessage message = new MimeMessage(session);
MimeBodyPart mbp = new MimeBodyPart();
MimeMultipart mmp = new MimeMultipart();

try {

mbp.setContent(text, “text/plain; charset=GBK”);
mmp.addBodyPart(mbp);
if (fileAttachment != null && fileAttachment != “”) {

// System.out.println(“————————–\n”+fileAttachment+”\n————————–“);

DataSource source = new FileDataSource(fileAttachment);
String name = source.getName();
mbp = new MimeBodyPart();
mbp.setDataHandler(new DataHandler(source));
mbp.setFileName(name);
mmp.addBodyPart(mbp);

}
message.setSubject(subject);
message.setContent(mmp);

 

message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
to));
// message.setText(text);
// Send message
message.saveChanges();
Transport transport = session.getTransport(“smtp”);
transport.connect(host, username, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (Exception e) {
e.printStackTrace();
}
}

主要的发送方法,可以发送附件

(from 当年的,已经不存在的,我的百度空间)

谷歌纵横 wifi定位方式

最近登录latitude,发现我在学校和家之间飘来飘去,本来在家的,确每天都有些时候定位在学校,而且是在同一点,非常的不可思议。
现在回到学校了,发现我又经常定位在家里了,也总是定位在同一点。。
突然想起来我把家里和学校的无线路由给交换了(新买的带回家了),这个似乎可以解释的通。
我猜测,谷歌有一个庞大的数据库,用于存储用户wifi热点位置,而每个wifi热点的id应该是无线路由的mac地址,因为我交换路由后所有信息都发生了变化当然包括IP。当首次用户接连热点,并通过GPS或者基站定位后,google就把位置信息和热点MAC地址传回存储,便于下次快速定位(因为热点移动的概率不是很大)。
但是出现我这种情况,我不知道google是依据什么来更新无线热点的最新位置的,我这种情况显然更新滞后了。
总结,谷歌纵横在wifi下优先是通过已有数据通过热点本身定位的。

纯无聊下。。

(from 当年的,已经不存在的,我的百度空间)