前言:jar 包中的 servlet 必须可以处理前端发出的 ajax 请求,接收参数,并返回结果。

github地址:yuleGH github

这里有个约定,url 地址是 .json 结尾的,如果是 .json 结尾的则当成 ajax 访问, 如果不是,则当成查找普通文件处理。

处理 json 请求的异常处理方式:

  1. if (path.endsWith(".json")){
  2. try{
  3. //处理ajax请求
  4. dealJsonService(request, response, path);
  5. } catch (Exception e){
  6. logger.error("访问querydb ajax报错!", e);
  7. response.setStatus(500);
  8. response.getWriter().write("服务器端未知错误:" + e.getMessage());
  9. }
  10. }

处理 json 请求的核心处理方法(通过反射设定参数并调用业务方法,然后返回 json 结果):

  1. /**
  2. * 处理ajax的json请求
  3. * @param request
  4. * @param response
  5. * @param path
  6. * @throws IOException
  7. * @throws NoSuchMethodException
  8. * @throws InvocationTargetException
  9. * @throws IllegalAccessException
  10. * @throws InstantiationException
  11. */
  12. private void dealJsonService(HttpServletRequest request, HttpServletResponse response, String path) throws IOException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
  13. String methodName = path.substring(1, path.indexOf(".json"));
  14.  
  15. final Method[] methods = DbComponentTopService.class.getMethods();
  16. boolean flag = false;
  17. for(Method method : methods){
  18. if(method.getName().equals(methodName)){
  19. flag = true;
  20. Object objResult = getObjResultByMethod(request, response, method);
  21. if(objResult != null){
  22. Gson gson = new Gson();
  23. response.getWriter().print(gson.toJson(objResult));
  24. }
  25. break;
  26. }
  27. }
  28.  
  29. if(!flag){
  30. logger.error("404-找不到地址:{}", path);
  31. response.setStatus(404);
  32. response.getWriter().write("404-找不到地址:" + path);
  33. }
  34. }

执行获取结果的方法(绑定参数,利用自定义注解和反射):

  1. /**
  2. * 执行方法,获取结果值
  3. * @param request
  4. * @param response
  5. * @param method
  6. * @return
  7. * @throws InvocationTargetException
  8. * @throws IllegalAccessException
  9. * @throws NoSuchMethodException
  10. */
  11. private Object getObjResultByMethod(HttpServletRequest request, HttpServletResponse response, Method method) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
  12. Object objResult = null;
  13.  
  14. String methodName = method.getName();
  15. DbComponentTopService dbComponentTopService = SpringContextHolder.getBean(DbComponentTopService.class);
  16. //方法的参数类型
  17. final Class<?>[] parameterTypes = method.getParameterTypes();
  18. //存放方法的参数值
  19. final Object[] parameterValues = new Object[parameterTypes.length];
  20. int i = 0;
  21.  
  22. if(CommonUtil.isNullOrBlock(parameterTypes)){
  23. Method myMethod = DbComponentTopService.class.getMethod(methodName);
  24. objResult = myMethod.invoke(dbComponentTopService);
  25. }else{
  26. //获取方法的参数注解
  27. final Annotation[][] parameterAnnotations = method.getParameterAnnotations();
  28. for (Annotation[] annotation1 : parameterAnnotations) {
  29. for (Annotation annotation : annotation1) {
  30. if (annotation instanceof MyParam) {
  31. MyParam customAnnotation = (MyParam) annotation;
  32. Class curParameterType = parameterTypes[i];
  33.  
  34. if("httpServletRequest".equals(customAnnotation.value())){
  35. parameterValues[i++] = request;
  36. }else if ("httpServletResponse".equals(customAnnotation.value())){
  37. parameterValues[i++] = response;
  38. }else if ("java.lang.Integer".equals(curParameterType.getName())){
  39. parameterValues[i++] = Integer.parseInt(request.getParameter(customAnnotation.value()));
  40. }else{
  41. parameterValues[i++] = request.getParameter(customAnnotation.value());
  42. }
  43. }
  44. }
  45. }
  46.  
  47. Method myMethod = DbComponentTopService.class.getMethod(methodName, parameterTypes);
  48. objResult = myMethod.invoke(dbComponentTopService, parameterValues);
  49. }
  50.  
  51. return objResult;
  52. }

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. 防止sql注入的小函数 以及一些小验证

    function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialch ...

  2. C#导出HTML到PDF组件 Pechkin

    C#导出PDF功能是开发中经常遇到的功能,我们采用第三方的组件,比如 iTextSharp, aspose等,还能搜到一些开源的类库, 但是对于一些内容复杂样式丰富的PDF,我们希望通过传入一个URL ...

  3. Shell - 简明Shell入门01 - 第一个脚本(HelloShell)

    示例脚本及注释 #!/bin/bash echo "hello shell!" # 打印字符串"hello shell!" echo "Date: & ...

  4. CentOS的ssh sftp配置及权限设置[转载-验证可用]

    从技术角度来分析,几个要求:1.从安全方面看,sftp会更安全一点2.线上服务器提供在线服务,对用户需要控制,只能让用户在自己的home目录下活动3.用户只能使用sftp,不能ssh到机器进行操作 提 ...

  5. opencv2.4.13.7的resize函数使用(c++)

    先来看一下resize函数的原型,如下. C++: void resize(InputArray src, OutputArray dst, Size dsize, double fx=0, doub ...

  6. PyCharm下载与激活

    1.集成开发环境(IDE:Integrated Development Environment)PyCharm下载地址:https://www.jetbrains.com/pycharm/downlo ...

  7. hive中解决中文乱码

    一.个人初始开发环境的基本情况以及Hive元数据库说明 ①hive的元数据库改成了mysql(安装完mysql之后也没有进行其它别的设置) ②hive-site.xml中设置元数据库对应的配置为  j ...

  8. configure: error: You need a C++ compiler for C++ support.[系统缺少c++环境]

    一.错误configure: error: You need a C++ compiler for C++ support.二.安装c++ compiler情况1.当您的服务器能链接网络时候[联网安装 ...

  9. JAVA面试精选【Java算法与编程一】

    在面试中,算法题目是必须的,通过算法能够看出一个程序员的编程思维,考察对复杂问题的设计与分析能力,对问题的严谨性都能够体现出来.算法是一系列解决问题的清晰指令,也就是说,能够对一定规范的输入,在有限时 ...

  10. ASP.NET MVC 与NLog的使用

    NLog是一个.NET 下一个完善的日志工具,个人已经在项目中使用很久,与ELMAH相比,可能EAMAH更侧重 APS.NET MVC 包括调试路由,性能等方面,而NLog则更简洁. github: ...