web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>TwoLink</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>Init</display-name>
<servlet-name>Init</servlet-name>
<servlet-class>com.cdsxt.link.init.Init</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet>
<description></description>
<display-name>TwoLinkController</display-name>
<servlet-name>TwoLinkController</servlet-name>
<servlet-class>com.cdsxt.link.controller.TwoLinkController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TwoLinkController</servlet-name>
<url-pattern>/twoLinkController</url-pattern>
</servlet-mapping>
</web-app>

 

 

Utils.js:

/**
* Created by Administrator on 16-1-6.
*/

(function(w){

function Utils(){}

Utils.prototype.getChilds = function(_selector){

};

Utils.prototype.getNextSibling = function(_selector){

};

Utils.prototype.getPrevSibling = function(_selector){

};


Utils.prototype.validate = function(_form){

};

Utils.prototype.checkdata = function(_input){
//得到 input里面的自定义的 正则表达式字段 用于动态构建正则表达式
var regex = _input.getAttribute("regex");
eval("regex = /"+regex+"/ig;");
var span = document.getElementById(_input.name+"-msg");
//如果没有值 则提示
if(_input.value){
if(regex.test(_input.value)){
span.innerHTML = "<font color='green'>"+_input.getAttribute("successmsg")+"</font>"
return true;
}else{
span.innerHTML = "<font color='red'>"+_input.getAttribute("errormsg")+"</font>"
return false;
}
}else{
span.innerHTML = "<font color='red'>"+_input.getAttribute("nullmsg")+"</font>";
return false;
}

};

/**
*
* @param config
*
* config{
* url:'testController',
* method:'get',
* data:{"name":"lisi","age":"20"}, //name=lisi&age=20
* async:true|false,
* success:function(){},
* error:function(){},
* loading:function(){}
* }
*
* $.ajax({
* url:'',
* success:function(data){
*
* //
* }
* });
*
*
*/
Utils.prototype.ajax = function(config){
// init config
config = config || {};
config['url'] = config['url'] || "";
config['method'] = config['method'] || "get";
config['data'] = config['data'] || {};
config['async'] = (String(config['async']) === 'false')?false:true;

var request = createRequest();
request.onreadystatechange = function(){
if(request.readyState == 4){
if(request.status == 200){
if(typeof config['success'] == 'function'){
config['success'](request.responseText);
}
}else{
if(typeof config['error'] == 'function'){
config['error'](request.responseText);
}
}
}else{
if(typeof config['loading'] == 'function'){
config['loading']();
}
}
}
//将json的参数解析为字符串
var params = parseParam(config['data']);
if(config['method'].toLowerCase() == 'get'){
if(config['url'] && params){
//有?号
config['url'] = config['url']+((config['url'].indexOf('?')!=-1)?"&":"?")+params;
}
//打开请求
request.open(config['method'],config['url'],config['async']);
request.send(null);
}else if(config['method'].toLowerCase() == 'post'){
//打开请求
request.open(config['method'],config['url'],config['async']);
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
request.send(params);
}else{
if(w.console){
console.log(config['method']+" 方法没有被实现!");
}
}
};

//create request
function createRequest(){
var request;
//创建 request对象
if(window.XMLHttpRequest){ //兼容性
request = new XMLHttpRequest();
}else if(window.ActiveXObject){ //针对IE
request = new ActiveXObject("Msxml2.XMLHTTP");
}
return request;
}

function parseParam(param){
var result = [];
for(var key in param){
result.push(key+"="+param[key]);
}

return result.join("&");
}

w.utils = w.$ = new Utils();

})(window);

 

Init.java

package com.huawei.link.init;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import com.cdsxt.link.po.Users;

/**
* Servlet implementation class Init
*/
public class Init extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public Init() {

}

@Override
public void init(ServletConfig config) throws ServletException {
System.out.println("init ...");
/**
* 构建数据 将数据存储在application中
*/
ServletContext application = config.getServletContext();

//关于用户 直接构建一个List
List<Users> users = new ArrayList<Users>();

users.add(new Users("1", "李四"));
users.add(new Users("2", "张三"));
users.add(new Users("3", "王武"));
users.add(new Users("4", "招六"));
users.add(new Users("5", "测试"));
users.add(new Users("6", "大浪"));

Map<String, String[]> favs = new HashMap<String, String[]>();

favs.put("1", new String[]{"游泳","上网"});
favs.put("2", new String[]{"游泳","游戏","美食"});
favs.put("3", new String[]{"跑步","上网","唱歌"});
favs.put("4", new String[]{"吹牛","麻将"});
favs.put("5", new String[]{"旅游","上网"});
favs.put("6", new String[]{"游泳","冒险","作死"});

application.setAttribute("users", users);
application.setAttribute("favs", favs);
}

}

 

Users.java

package com.huawei.link.po;

public class Users {
private String id;
private String username;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Users(String id, String username) {
super();
this.id = id;
this.username = username;
}
public Users() {
super();
// TODO Auto-generated constructor stub
}

}

 

TwoLinkController.java

package com.huawei.link.controller;

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

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

import com.google.gson.Gson;

/**
* Servlet implementation class TwoLinkController
*/
public class TwoLinkController extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public TwoLinkController() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doPost(request, response);
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");

String _method = request.getParameter("_method");
if("getFav".equals(_method)){
this.getFav(request, response);
return ;
}
this.getAllUsers(request, response);
return ;

}
protected void getAllUsers(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Gson gson = new Gson();
response.getWriter().write(gson.toJson(this.getServletContext().getAttribute("users")));
}
@SuppressWarnings("unchecked")
protected void getFav(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
try {
Thread.currentThread().sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Gson gson = new Gson();
Map<String, String[]> favs = (Map<String, String[]>) this.getServletContext().getAttribute("favs");
response.getWriter().write(gson.toJson(favs.get(id)));
}

}

 

index.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">
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">

<title>This is my JSP page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

</head>

<body>
用户:<select id="user" onchange="getFav(this)">
<option value="">请选择</option>
</select>
爱好:<select id="fav">
<option value="">请选择</option>
</select>
</body>
<script type="text/javascript">

(function(){

var request;
if(window.XMLHttpRequest){
request = new XMLHttpRequest();
}else if(window.ActiveXObject){
request = new ActiveXObject("Msxml2.XMLHTTP");
}

request.onreadystatechange = function(){
if(request.readyState == 4){
if(request.status == 200){
var data = request.responseText;
var user_select = document.getElementById("user");
eval("data = "+data);
//遍历数据
for(var i in data){
var user = data[i];
var opt = new Option();
opt.value = user.id;
opt.text = user.username;
user_select.appendChild(opt);
}
}
}
};

request.open("get", "twoLinkController?d="+new Date().getTime());
request.send(null);

})();

function getFav(_select){
//得到id
var value = _select.value;
if(value){
ajaxutil("get", "twoLinkController?d="+new Date().getTime(), "_method=getFav&id="+value, true, function(data){
var fav_select = document.getElementById("fav");
fav_select.options.length = 1;
eval("data = "+data);
//遍历数据
for(var i in data){
var opt = new Option(data[i],"");
fav_select.appendChild(opt);
}
});
}

//alert(123);
}


function ajaxutil(method,url,param,async,success,handler404,handler500,loading){
method = method || "get";
param = param || "";
var request;
if(window.XMLHttpRequest){
request = new XMLHttpRequest();
}else if(window.ActiveXObject){
request = new ActiveXObject("Msxml2.XMLHTTP");
}

request.onreadystatechange = function(){
if(request.readyState == 4){
if(request.status == 200){
if(typeof success == 'function'){
success(request.responseText);
}
}
if(request.status == 404){
if(typeof success == 'function'){
handler404(request.responseText);
}
}
if(request.status == 500){
if(typeof success == 'function'){
handler500(request.responseText);
}
}
}else{
//回调函数
if(typeof loading == 'function'){
loading();
}
}
};

if(method.toLowerCase()=="get"){
//当传入的地址有?号的时候
//testControler?a=123
//testControler
//param name=lisi

//testController?a=123&name=lisi
//testController?name=lisi
if(url && param){
if(url.indexOf('?')!=-1){
url = url + "&"+param;
}else{
url = url + "?"+param;
}
}
request.open(method, url, async);
request.send(null);
}else if(method.toLowerCase()=="post"){
request.open(method,url,async);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.send(param);
}


}
</script>
</html>

 

 

testajax.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">
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">

<title>This is my JSP page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript" src="Utils.js"></script>

</head>

<body>
用户:<select id="user" onchange="getFav(this)">
<option value="">请选择</option>
</select>
爱好:<select id="fav">
<option value="">请选择</option>
</select>
</body>
<script type="text/javascript">
(function(){

$.ajax({
url:'twoLinkController',
method:'get',
data:{"d":new Date().getTime()},
success:function(data){
var user_select = document.getElementById("user");
eval("data = "+data);
//遍历数据
for(var i in data){
var user = data[i];
var opt = new Option();
opt.value = user.id;
opt.text = user.username;
user_select.appendChild(opt);
}
}
});
})();

function getFav(_select){
//得到id
var value = _select.value;
if(value){
$.ajax({
url:'twoLinkController',
data:{"d":new Date().getTime(),"_method":"getFav","id":value},
success:function(data){
var fav_select = document.getElementById("fav");
fav_select.options.length = 1;
eval("data = "+data);
//遍历数据
for(var i in data){
var opt = new Option(data[i],"");
fav_select.appendChild(opt);
}
}
});
}

//alert(123);
}

</script>
</html>