jquery ajax再次封装,前台调用后台java方法直接返回数据
2017-06-19 17:54
691 查看
一,前台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),
/**
* 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),
相关文章推荐
- [置顶] 动态grid java 后台封装json数据返回到前台解析并展示
- jquery ajax调用后台方法返回json数据转自http://www.cnblogs.com/xiaoxi/archive/2011/03/31/2000803.html
- Ajax前台返回JSON数据后再Controller中直接转换成类型使用,后台接收json转成实体的方法
- java后台返回json数据前台接收并解析(json)
- 使用jquery Ajax的post方法或直接使用jqery ajax请求action 得到返回的json数据
- 前台JS(jquery ajax)调用后台方法实现无刷新级联菜单示例
- java 后台返回json数据给前台
- Java调用.NET XML Web Services返回的数据集合的方法
- 封装好的Android对话框Dialog,包含了丰富的dialog样式、点击事件数据回传接口。直接调用封装好的方法即可操作dialog
- jquery ajax中 php前台后台文件中编辑都是uft-8,返回数据还是乱码
- jQuery Ajax 调用aspx后台方法返回DataTable 的例子
- Java后台使用get方式远程跨域请求,返回数据为中文乱码解决方法
- 前台调用后台方法(返回字符串)
- java 直接返回Date类型数据给前端,前端的处理方法
- asp.net如何在前台利用jquery Ajax调用后台方法
- 前台调用后台方法,无刷新更新数据
- struts2 + ajax(由前台的form提交数据到后台,再根据form所调用返回获取的后台json格式的数据返回到前端,然后前端用jquery对json数据进行解析)==》》涉及文件上传的部分
- jQuery Ajax 调用 WebService 返回数据表(DataTable)的方法
- ajax 同步调用 返回字符串 java例子(全)及 从后台返回中文乱码解决方法
- Jquery Ajax学习实例3 向WebService发出请求,调用方法返回数据