前言:jar 包中的 servlet 必须可以处理前端发出的 ajax 请求,接收参数,并返回结果。

github地址:yuleGH github

这里有个约定,url 地址是 .json 结尾的,如果是 .json 结尾的则当成 ajax 访问, 如果不是,则当成查找普通文件处理。

处理 json 请求的异常处理方式:

        if (path.endsWith(".json")){
try{
//处理ajax请求
dealJsonService(request, response, path);
} catch (Exception e){
logger.error("访问querydb ajax报错!", e);
response.setStatus(500);
response.getWriter().write("服务器端未知错误:" + e.getMessage());
}
}

处理 json 请求的核心处理方法(通过反射设定参数并调用业务方法,然后返回 json 结果):

    /**
* 处理ajax的json请求
* @param request
* @param response
* @param path
* @throws IOException
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws InstantiationException
*/
private void dealJsonService(HttpServletRequest request, HttpServletResponse response, String path) throws IOException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
String methodName = path.substring(1, path.indexOf(".json")); final Method[] methods = DbComponentTopService.class.getMethods();
boolean flag = false;
for(Method method : methods){
if(method.getName().equals(methodName)){
flag = true;
Object objResult = getObjResultByMethod(request, response, method);
if(objResult != null){
Gson gson = new Gson();
response.getWriter().print(gson.toJson(objResult));
}
break;
}
} if(!flag){
logger.error("404-找不到地址:{}", path);
response.setStatus(404);
response.getWriter().write("404-找不到地址:" + path);
}
}

执行获取结果的方法(绑定参数,利用自定义注解和反射):

    /**
* 执行方法,获取结果值
* @param request
* @param response
* @param method
* @return
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws NoSuchMethodException
*/
private Object getObjResultByMethod(HttpServletRequest request, HttpServletResponse response, Method method) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
Object objResult = null; String methodName = method.getName();
DbComponentTopService dbComponentTopService = SpringContextHolder.getBean(DbComponentTopService.class);
//方法的参数类型
final Class<?>[] parameterTypes = method.getParameterTypes();
//存放方法的参数值
final Object[] parameterValues = new Object[parameterTypes.length];
int i = 0; if(CommonUtil.isNullOrBlock(parameterTypes)){
Method myMethod = DbComponentTopService.class.getMethod(methodName);
objResult = myMethod.invoke(dbComponentTopService);
}else{
//获取方法的参数注解
final Annotation[][] parameterAnnotations = method.getParameterAnnotations();
for (Annotation[] annotation1 : parameterAnnotations) {
for (Annotation annotation : annotation1) {
if (annotation instanceof MyParam) {
MyParam customAnnotation = (MyParam) annotation;
Class curParameterType = parameterTypes[i]; if("httpServletRequest".equals(customAnnotation.value())){
parameterValues[i++] = request;
}else if ("httpServletResponse".equals(customAnnotation.value())){
parameterValues[i++] = response;
}else if ("java.lang.Integer".equals(curParameterType.getName())){
parameterValues[i++] = Integer.parseInt(request.getParameter(customAnnotation.value()));
}else{
parameterValues[i++] = request.getParameter(customAnnotation.value());
}
}
}
} Method myMethod = DbComponentTopService.class.getMethod(methodName, parameterTypes);
objResult = myMethod.invoke(dbComponentTopService, parameterValues);
} return objResult;
}

servlet 中处理 json 请求,并访问 service 类,返回处理结果的更多相关文章

  1. 在Servlet中使用JSON

    在Servlet中使用JSON,和上篇的使用相同,只不过多了配置web.xml的内容 servlet代码如下: import java.io.IOException; import java.io.P ...

  2. 提取日志中的json请求发送到另外一台机器

    将日志中的json请求提取,并且发送到另外一个机器上: for i in ` cat impression.log.2016-04-08-10 |awk -F"\t" ' {pri ...

  3. servlet中的doGet()与doPost()以及service()的用法

    doget和dopost的区别 get和post是http协议的两种方法,另外还有head, delete等 1.这两种方法有本质的区别,get只有一个流,参数附加在url后,大小个数有严格限制且只能 ...

  4. Servlet中获取POST请求的参数

    在servlet.filter等中获取POST请求的参数 form表单形式提交post方式,可以直接从 request 的 getParameterMap 方法中获取到参数 JSON形式提交post方 ...

  5. 在JavaScript中使用json.js:访问JSON编码的某个值

    演示: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3. ...

  6. servlet中请求转发(forword)与重定向(sendredirect)的区别

    摘自:http://www.cnblogs.com/CodeGuy/archive/2012/02/13/2349970.html 通俗易懂 servlet请求转发与重定向的区别: request.s ...

  7. struts2中的json

    这里放一个转载的struts2中json的详细应用和范例, http://yshjava.iteye.com/blog/1333104,这是个人在网上看到的很用心也很详细的一份关于struts2中js ...

  8. Spring对JSON请求加解密

    Spring中处理JSON请求通常使用@RequestBody和@ResponseBody注解,针对JSON请求加解密和过滤字符串,Spring提供了RequestBodyAdvice和Respons ...

  9. servlet中的“/”代表当前项目,html中的“/”代表当前服务器

    servlet中重定向或请求转发的路径如果用“/”开头,代表当前项目下的路径,浏览器转发这条路径时会自动加上当前项目的路径前缀,如果这个路径不是以“/”开头,那么代表这个路径和当前所在servlet的 ...

随机推荐

  1. Fiddler工具使用介绍三

    我们知道Fiddler是位于客户端和服务器之间的代理,它能够记录客户端和服务器之间的所有 HTTP请求,可以针对特定的HTTP请求,分析请求数据.设置断点.调试web应用.修改请求的数据,甚至可以修改 ...

  2. [Objective-C语言教程]字符串(16)

    Objective-C编程语言中的字符串使用NSString表示,其子类NSMutableString提供了几种创建字符串对象的方法. 创建字符串对象的最简单方法是使用Objective-C的标识符: ...

  3. 01_python_初始python

    一.初始python python是一门解释型语言,弱类型语言 / python解释器最为常用的是cpython(官方) 弱类型语言:   a = 1 a = 'alex'   #说明变量a既可以是整 ...

  4. Flash 0day漏洞(CVE-2018-4878)复现

    该漏洞影响 Flash Player 当前最新版本28.0.0.137以及之前的所有版本,而Adobe公司计划在当地时间2月5日紧急发布更新来修复此漏洞. 本文作者:i春秋作家——F0rmat 前言 ...

  5. Swift5 语言参考(七) 属性

    属性提供有关声明或类型的更多信息.Swift中有两种属性,即适用于声明的属性和适用于类型的属性. 您可以通过编写@符号后跟属性的名称以及属性接受的任何参数来指定属性: @attribute name ...

  6. Swift 里 Set(四)Testing for Membership

    即contains操作 /// - Parameter member: An element to look for in the set. /// - Returns: `true` if `mem ...

  7. 优化openfire服务器提升xmpp 效率的15个方法(原创)

    1.禁用原生xmpp搜索,使组织架构.人员数据本地化保存,并使客户端数据同步服务器,降低原生xmpp搜索的iq消耗,因为搜索是im应用的频繁操作: 2.禁用roster花名册.禁用presence包通 ...

  8. xamarin 安卓输出中文错误 乱码解决

    在编译设置附加参数 -J-Duser.language=en 这个错误信息是来自javac 编译产生的 而中文乱码问题是 GBK 和UTF8 的问题 解决的办法就是让javac 输出英文错误信息 也可 ...

  9. 剑指offer六之求旋转数组的最小数字

    一.题目 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转. 输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素. 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个 ...

  10. Git使用(3)

    1.查看本地和远程分支 git branch -a 删除本地分支 git branch -D branchName(D要大写) 删除远程分支 git push origin :branchName 2 ...