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;
    }

猜你喜欢

转载自www.cnblogs.com/yuxiaole/p/9786193.html
今日推荐