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的 ...
随机推荐
- 防止sql注入的小函数 以及一些小验证
function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialch ...
- C#导出HTML到PDF组件 Pechkin
C#导出PDF功能是开发中经常遇到的功能,我们采用第三方的组件,比如 iTextSharp, aspose等,还能搜到一些开源的类库, 但是对于一些内容复杂样式丰富的PDF,我们希望通过传入一个URL ...
- Shell - 简明Shell入门01 - 第一个脚本(HelloShell)
示例脚本及注释 #!/bin/bash echo "hello shell!" # 打印字符串"hello shell!" echo "Date: & ...
- CentOS的ssh sftp配置及权限设置[转载-验证可用]
从技术角度来分析,几个要求:1.从安全方面看,sftp会更安全一点2.线上服务器提供在线服务,对用户需要控制,只能让用户在自己的home目录下活动3.用户只能使用sftp,不能ssh到机器进行操作 提 ...
- opencv2.4.13.7的resize函数使用(c++)
先来看一下resize函数的原型,如下. C++: void resize(InputArray src, OutputArray dst, Size dsize, double fx=0, doub ...
- PyCharm下载与激活
1.集成开发环境(IDE:Integrated Development Environment)PyCharm下载地址:https://www.jetbrains.com/pycharm/downlo ...
- hive中解决中文乱码
一.个人初始开发环境的基本情况以及Hive元数据库说明 ①hive的元数据库改成了mysql(安装完mysql之后也没有进行其它别的设置) ②hive-site.xml中设置元数据库对应的配置为 j ...
- configure: error: You need a C++ compiler for C++ support.[系统缺少c++环境]
一.错误configure: error: You need a C++ compiler for C++ support.二.安装c++ compiler情况1.当您的服务器能链接网络时候[联网安装 ...
- JAVA面试精选【Java算法与编程一】
在面试中,算法题目是必须的,通过算法能够看出一个程序员的编程思维,考察对复杂问题的设计与分析能力,对问题的严谨性都能够体现出来.算法是一系列解决问题的清晰指令,也就是说,能够对一定规范的输入,在有限时 ...
- ASP.NET MVC 与NLog的使用
NLog是一个.NET 下一个完善的日志工具,个人已经在项目中使用很久,与ELMAH相比,可能EAMAH更侧重 APS.NET MVC 包括调试路由,性能等方面,而NLog则更简洁. github: ...