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的 ...
随机推荐
- PKI信息安全知识点
1. 什么是X.509? X.509标准是ITU-T设计的PKI标准,他是为了解决X.500目录中的身份鉴别和访问控制问题设计的. 2. 数字证书 数字证书的意义在于回答公钥属于谁的问题,以帮助用户安 ...
- [HTML] 动态修改input placeholder的颜色
.invalid:-moz-placeholder { /* Mozilla Firefox 4 to 18 */ color: red; } .invalid::-moz-placeholder { ...
- mybatis 全局配置文件
传送门:mybatis XML 映射配置文件官方文档 配置文件中的标签顺序不能颠倒,否则会报错. <?xml version="1.0" encoding="UTF ...
- SQLServer 在Visual Studio的2种连接方法
一.Sql Server 在Visual Studio的连接有两种方法: (1)本地计算机连接; string s = "Data Source=计算机名称;initial Catalog= ...
- iOS-iOS9系统SEGV_ACCERR问题处理【v3.6.3的一些bug修复】
前言 最近APP不断地更新版本,却发现一些未知的错误导致崩溃,我把能测出来的错误,全部修复了,因为项目里集成了腾讯Bugly,看了下后台的崩溃,依旧千篇一律啊,然后就纠结了,很多SEGV_ACCERR ...
- 彻底弄懂“PKIX path building failed”问题
SSL的基础知识 SSL的全称是Secure Socket Layer.它的通信流程如下图所示,客户端与服务端会通过几次通信,通过非对称加密创建出一个加密密钥,用于以后的对称信息加密. 1,客户端明文 ...
- Vue2.5开发去哪儿网App 城市列表开发之 兄弟组件间联动及列表性能优化
一, 兄弟组件间联动 1. 点击城市字母,左侧对应显示 给遍历的 字母 添加一个点击事件: Alphabet.vue @click="handleLetterClick" ha ...
- 单点登录--CAS认证--web.xml配置详解
参考网址: https://blog.csdn.net/zhurhyme/article/details/29349543 https://blog.csdn.net/shzy1988/article ...
- pcm原始数据绘制
最近帮别人做了个东西,这里分享一下pcm原始数据绘图的思路 1.pcm数据采样位数,根据采样位数选取适合自己绘图的采样点的数量 2.计算出最大最小的的采样点的值差 3.根据要显示pcm数据的控件宽高, ...
- JSP -- 从甲骨文开始
1.Oracle10gForVistaX64下载地址:http://download.oracle.com/otn/nt/oracle10g/10204/10204_vista_w2k8_x64_pr ...