前言: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. Ubuntu修改apt-get源

    1.背景 服务器上安装了最新的Ubuntu Server 17.04,代号为zesty.使用apt-get命令安装软件时,有时候速度比较慢,有时候会失败.因此考虑用国内的镜像源更换下apt-get的默 ...

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

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

  3. vue项目在IE9下报错 “requestAnimationFrame”未定义

    在main.js里面添加: (function () { var lastTime = 0; var vendors = ['ms', 'moz', 'webkit', 'o']; for (var ...

  4. 线性表java实现

    顺序表 public class SequenceList { /* * content,节点内容 * location,节点在表中的位置(序号) * */ private String conten ...

  5. 56.storm 之 hello world (集群模式)

    回顾 在上一小节,我们在PWTopology1 这一个java类中注解掉了集群模式,使用本地模式大概了解一下storm的工作流程.这一节我们注解掉本地模式相关的代码,放开集群模式相关代码,并且将项目打 ...

  6. (转)通过 Javacore 诊断线程挂起等性能问题

    原文:https://www.ibm.com/developerworks/cn/websphere/library/techarticles/1406_tuzy_javacore/1406_tuzy ...

  7. Redis笔记(2)单机数据库实现

    1.前言 上节总结了一下redis的数据结构和对象构成,本章介绍redis数据库一个基本面貌,是如何设计的. 2.数据库 服务器结构redisServer: redisDb *db: 一个数组,保存服 ...

  8. 在Postgresql中添加新角色(Role)

    Postgresql安装完成之后,默认会创建名为postgres的用户.角色(Role)和数据库(Database).而使用你自己原有的用户运行psql时会提示错误. bob@localhost:~$ ...

  9. 微信web开发者工具、破解文件、开发文档和开发Demo下载

    关注,QQ群,微信应用号社区 511389428 下载: Win: https://pan.baidu.com/s/1bHJGEa Mac: https://pan.baidu.com/s/1slhD ...

  10. 编写自己的SpringBoot-starter

    前言 我们都知道可以使用SpringBoot快速的开发基于Spring框架的项目.由于围绕SpringBoot存在很多开箱即用的Starter依赖,使得我们在开发业务代码时能够非常方便的.不需要过多关 ...