servlet 中处理 json 请求,并访问 service 类,返回处理结果
前言: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 类,返回处理结果的更多相关文章
- 在Servlet中使用JSON
在Servlet中使用JSON,和上篇的使用相同,只不过多了配置web.xml的内容 servlet代码如下: import java.io.IOException; import java.io.P ...
- 提取日志中的json请求发送到另外一台机器
将日志中的json请求提取,并且发送到另外一个机器上: for i in ` cat impression.log.2016-04-08-10 |awk -F"\t" ' {pri ...
- servlet中的doGet()与doPost()以及service()的用法
doget和dopost的区别 get和post是http协议的两种方法,另外还有head, delete等 1.这两种方法有本质的区别,get只有一个流,参数附加在url后,大小个数有严格限制且只能 ...
- Servlet中获取POST请求的参数
在servlet.filter等中获取POST请求的参数 form表单形式提交post方式,可以直接从 request 的 getParameterMap 方法中获取到参数 JSON形式提交post方 ...
- 在JavaScript中使用json.js:访问JSON编码的某个值
演示: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3. ...
- servlet中请求转发(forword)与重定向(sendredirect)的区别
摘自:http://www.cnblogs.com/CodeGuy/archive/2012/02/13/2349970.html 通俗易懂 servlet请求转发与重定向的区别: request.s ...
- struts2中的json
这里放一个转载的struts2中json的详细应用和范例, http://yshjava.iteye.com/blog/1333104,这是个人在网上看到的很用心也很详细的一份关于struts2中js ...
- Spring对JSON请求加解密
Spring中处理JSON请求通常使用@RequestBody和@ResponseBody注解,针对JSON请求加解密和过滤字符串,Spring提供了RequestBodyAdvice和Respons ...
- servlet中的“/”代表当前项目,html中的“/”代表当前服务器
servlet中重定向或请求转发的路径如果用“/”开头,代表当前项目下的路径,浏览器转发这条路径时会自动加上当前项目的路径前缀,如果这个路径不是以“/”开头,那么代表这个路径和当前所在servlet的 ...
随机推荐
- A*与IDA*
谨以此文向人工智能先驱,\(A\)*算法发明者\(Nils\ Nilsson\)致敬 推一篇深入研究的博客,而本文更多是粗略理解和习题吧. \(A\)*算法是什么?它是启发式搜索的一种,即广度搜索算法 ...
- AC1000纪念
- jQuery基础(4)- 位置信息、事件流、事件对象、事件代理、jquery事件
一.jQuery的位置信息 jQuery的位置信是JS的client系列.offset系列.scroll系列封装好的一些简便api. 1.宽度和高度 a.获取宽度和高度,例如: .width() // ...
- Web安全测试学习手册-业务逻辑测试
i春秋作家:Vulkey_Chen 首先感谢朋友倾璇的邀请 http://payloads.online/archivers/2018-03-21/1 ,参与了<web安全测试学习手册>的 ...
- Stack&&Queue
特殊的容器:容器适配器 stack queue priority_queue:vector+堆算法---->优先级队列 stack: 1.栈的概念:特殊的线性结构,只允许 ...
- vmworkstation安装unbuntu server 网络配置:NAT模式
之前安装虚拟机测试环境的时候,习惯了使用桥接模式或者仅主机模式:今天偶然发现,其实NAT 模式的网络配置还是挺方便的. 在新建虚拟机的时候,选择网络模式为NAT,虚拟机创建完成之后,在vmworkst ...
- RESTful API后台系统架构设计(Java)
最近设计和实现了一个JAVA的RESTful API的后台业务系统架构,主要基于Java平台.设计要求是: 性能:平均响应时间(RESTful API)小于2s(平均负载的情况下),并发访问200个以 ...
- ES6基础教程一 学习笔记
一.变量的声明 1.var 声明全局变量 在ES6中var用来声明全局变量. 2.let 声明局部变量 3.const 声明常量 二.变量的解构赋值 //1.数组赋值 let [a,b,c]=[1,2 ...
- 哨兵/sentinel:在算法设计中的应用
哨兵(sentinel)昨天看算法导论里对哨兵的描述后,觉得这是一种很有意思的编程思想.哨兵是一个哑对象.一般哨兵不存放任何数据,但其结构体与其他有用的元素一致.正如其字面意思,哨兵是在边界保卫祖国的 ...
- 使用 GMap.NET 实现添加标注、移动标注功能。(WPF版)
前言 在WPF嵌入地图,有两种方式: 浏览器方式:控件方式. 1)浏览器方式就是使用浏览器控件WebBrowser,设置好网址就行了.这种方式与地图的交互不太直接,需要懂html.javascript ...