前言: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. 【hyperscan】编译hyperscan 4.0.0

    ref: http://01org.github.io/hyperscan/dev-reference/getting_started.html 1. 硬件需求 intel x86处理器 64-bit ...

  2. D3.js的基础部分之选择集的处理 过滤器、选择集的顺序、each()和call()的应用(v3版本)

    选择集的处理 : 过滤器 有时候需要根据绑定数据对某选择集的元素进行过滤,例如某公司,只对id大于100的员工进行奖励.某学校只选拔身高超过170cm的学生等.类似这样的问题,需要根据条件获取选择集的 ...

  3. 【xsy2194】Philosopher set+线段树合并

    题目大意:给你一个长度为$n$的序列,有$m$次操作,每次操作是以下两种之一: 对某个区间内的数按照升序/降序排序,询问某个区间内数的积在十进制下首位数字是多少. 数据范围:$n,m≤2\times ...

  4. Celery启动Django项目:Client sent AUTH, but no password is set 错误处理

    celery -A CeleryTest worker -l info [2017-02-22 07:26:52,666: ERROR/MainProcess] consumer: Cannot co ...

  5. Centos 7 安装 Redis 3.2

    环境: Centos 7 GCC            #未安装,使用yum install gcc安装 1.下载redis 官方下载网站:https://redis.io/download.请在页面 ...

  6. python应用

    GUI(图形用户界面) python是可以创建GUI的,使用第三方库一般是Tk.wxWidgets.Qt.GTK. 而python自带的是支持Tk的Tkinter,我们这里就来用Tkinter来实现G ...

  7. Java8-函数复合用法

    JDK8自带的函数式接口Function有两个默认方法andThen和compose,它们都返回Function的一个实例,可以用这两个方法把Function接口所代表的的Lambda表达式复合起来. ...

  8. 分享.NET 轻量级的ORM

    ORM https://github.com/StackExchange/dapper-dot-net http://fluentdata.codeplex.com/ https://github.c ...

  9. JVM Scan

    1.jmap -histo pid|head -100 2.jstat -gcutil pid cycle 3.jmap -heap pid

  10. php里use关键字与class_alias的作用域区别

    use可以用在命名空间下,也可以不用再命名空间下,他在两者中的作用是一致的,都是在编译的时候执行,不真正的加载类,因为是编译的时候执行,所以只能在全局环境使用,及不能使用在方法内部,条件判断内部. 引 ...