日期:2014-05-16  浏览次数:20740 次

ajax struts实现在线查询功能
   我用的是ajax 和struts实现的一个在线查询功能,原理很简单。
首先解析网址 根据输入的内容得到一个相关文本内容,我用的网站是百度mp3
public static List<String> onlineSearch(String singer) throws IOException {
// if (singer == null)
// singer = "爱";
String name = "a";
String path = "http://nssug.baidu.com/su?wd="
+ URLEncoder.encode(singer, "UTF-8")
+ "&prod=mp3&oe=utf-8&callback=undefined";

System.out.println("path = " + path);
double fileLength = 0.0;
File parent = new File("D:\\path");
if (!parent.exists()) {
parent.mkdirs();
}
File mp3File = new File(parent, name);
System.out.println(mp3File);
OutputStream os = null;
InputStream is = null;
URL url = new URL(path);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// 此处必须伪造referer,否则会自动返回首页.分析后,与cookie无关
con.setRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon;)");
con.setRequestProperty("Accept-Encoding", "deflate");
con.setRequestProperty("referer", "http://nssug.baidu.com");
con.setDoInput(true);
con.connect();
if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
is = con.getInputStream();
byte[] b = new byte[1024 * 5];
int length = -1;
os = new FileOutputStream(mp3File);
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}

os.flush();
}

BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(mp3File), "gbk"));
String tmp = reader.readLine();
reader.close();
Pattern p = Pattern.compile("\\(.*?\\)");
Matcher m = p.matcher(tmp);
String result="";
while (m.find()) {
result+=m.group();
}
result = result.replaceAll("\\(", "");
result = result.replaceAll("\\)", "");
Gson gson  = new Gson();
HashMap object = (HashMap) gson.fromJson(result, Object.class);

ArrayList list = (ArrayList) object.get("s");

return list;
}
这是解析网站反馈给我的文本 把内容放在一个list里面 然后action调用方法
@SuppressWarnings("static-access")
public String execute() throws Exception {
// 将要返回的user实体对象进行json处理
JSONObject jo = JSONObject.fromObject(this.user);

// 打印一下,格式如下

// {"name":"风达","age":23}
        System.out.println(result);
        List<String> list = new ArrayList<String>();
     list= onlineSearch(result);
        for(int i=0; i<list.size();i++) {
        System.out.println(list.get(i));
        this.result += "<li>"+list.get(i)+"</li>";
        }
        System.out.println(result);
return this.SUCCESS;

}
接下来就是页面,
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Google Maps JavaScript API Example</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/jquery-1.4.2.min.js" />
<script type="text/javascript">

</script>
<script type="text/javascript">
function lookup(inputString) {
if (inputString.length == 0) {
// Hide the suggestion box.
$('#suggestions').hide();
} else {
$.post("jsonAction.acti