一,前台js部分代码
/**
* bean参数格式:类全限定名.方法名 opt参数格式:键值对 handleResponse:会function类型参数包含一个参数data,为后台返回json数据
* 方法返回值不能为null; 返回数据类型为map {data:Object}
*/
function ajax(bean, opt, handleResponse) {
$.ajax({
url : window.location.href.split("/")[3]+"/ajax/ajax.action?bean="+bean+changeParamer(opt),
type : 'get',
processData : false,
//data : opt,
cache : false,
dataType : 'json',
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert('请求出错:'+ XMLHttpRequest.status + " " + textStatus + " " + errorThrown)
},
success : handleResponse
});
}
/**
* 将ajax中的参数转化,否则后台不能去到数据(post方式提交没有测试是否可以)
*/
function changeParamer(opt){
var temp="";
for(var o in opt){
temp += "&" + o+"="+opt[o];
}
return temp;
}
二,后台java部分
/**
*servlet部分,没有包申明和导入
*/
@MultipartConfig
@WebServlet(name="/Ajax", urlPatterns = {"/Ajax"})
public class Ajax extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
AjaxRequest ajaxRequest=new AjaxRequest(request,response);
ajaxRequest.manager();
}
}
public class AjaxRequest {
/**
* 处理Ajax请求
*/
HttpServletRequest request;
HttpServletResponse response;
public AjaxRequest(HttpServletRequest request, HttpServletResponse response){
this.request=request;
this.response=response;
}
/**
* 从请求中获取所有参数,以map的形式返回
* @return
*/
private Map<String, String> getParameterMap() {
Map<String, String[]> map = request.getParameterMap();//获取请求路径中的所有参数,并返回Map值
Map<String, String> params = new HashMap<String, String>();
String[] keys = (String[]) map.keySet().toArray(new String[0]);//获取map中的键
for (String key : keys) {
if ("bean".equals(key))
continue;
String value = getValue(key);
params.put(key, value);
}
return params;
}
/**
* 从map中或去key所对应的值,以String形式返回对应值
* @param key 需要从map中获取值的key名称
* @return
*/
private String getValue(String key) {
String[] values = this.request.getParameterValues(key);
if ((values != null) && (values.length > 1)) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < values.length; ++i) {
if (i > 0)
sb.append(",");
sb.append(values[i]);
}
return sb.toString();
}
String value = this.request.getParameter(key);
return value;
}
/**
* 通过反射的方式,根据类名获取对象后调用对应的方法,并返回值
* @return
* @throws Exception
*/
public void manager() throws Exception{
String className=request.getParameter("managerName");
String methodName=request.getParameter("methodName");
//String map=request.getParameter("data");
Map<String, String> map=getParameterMap();
Class<?> requestClass=null;
Object value=null;
ReadFile.getItemPath();//需修改为在tomcat启动时就初始化,不在调用getItemPath();方法
/*if(ReadFile.pathMap.isEmpty()){
System.err.println("请创建所需模块代码");
return;
}*/
String classPath=ReadFile.pathMap.get(className)+className;
requestClass=Class.forName(classPath);
Method method = requestClass.getMethod(methodName, Map.class);
//通过反射创建对象,通过对象执行类中的方法 manager和dao中的构造方法不同,限制只能调用manager???
Constructor<?> constructor = requestClass.getDeclaredConstructor(new Class[]{HttpServletRequest.class,HttpServletResponse.class});
Object object = constructor.newInstance(new Object[]{request,response});
value=method.invoke(object, map);
response.getWriter().print(value);
}
}
注:前台调用的后台方法参数类型必须为map类型(用了反射调用方法,参数类型设置为map),