评估HttpServletRequest是否是有效的方法调用

时间:2014-10-06 11:35:50

标签: java validation servlets

我认为在使用请求中的详细信息来调用方法时验证http请求是否有效会很有用。

我不知道任何apache库有一个方法我可以用来做这个但是如果有的话请告诉我,因为它会让事情变得容易多了。

这是我到目前为止的代码,但它确实很糟糕,也不完整。我在代码中留下了需要完成哪些部分的注释,但如果有什么可以改进,请告诉我如何。

package com.example.controller;

import java.io.IOException;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Test extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            System.out.println("has correct parameters: " + hasCorrectParameters(request));
            request.getRequestDispatcher("index.jsp").forward(request, response);
        } catch (Exception ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /*
     * This method will check if an HttpServletRequest has the correct parameters required to invoke a method
     * ------------------------------------------------
     * Potential problems and how they get resolved
     * ------------------------------------------------
     * 1. Too many parameters for any of the methods in the specified class
     * SOLUTION: throw new ExcessiveParametersException().
     * 2. Too few parameters for any of the methods in the specified class
     * SOLUTION: throw new InsufficientParametersException().
     * 3. Inappropriate method being called based on details provided
     * SOLUTION: throw new IncorrectDetailsException().
     * 4. No way of determining what will be returned and what's expected to be returned
     * SOLUTION: ??
     * 5. No way of determining which of the parameters in the request should be associated with which of the parameters in the method signature
     * SOLUTION: ??
     * 6. Parameters of the wrong type being passed to the method
     * SOLUTION: Try and use instanceof to determine what the type of the parameter is. If it's not correct then throw new IncorrectDetailsException().
     */
    public Boolean hasCorrectParameters(HttpServletRequest request) throws Exception {
        //Class information
        int methodWithMostParamsInSignature = 2;
        int methodWithLeastParamsInSignature = 0;

        //Request information
        int paramsInRequest = 0;

        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String param = (String) parameterNames.nextElement();
            System.out.println(param);
            paramsInRequest++;
        }

        /*
         * 1. Too many parameters for any of the methods in the specified class
         * SOLUTION: throw new ExcessiveParametersException().
         */
        if (paramsInRequest > methodWithMostParamsInSignature) {
            throw new Exception("Excessive Parameters");
        }

        /*
         * 2. Too few parameters for any of the methods in the specified class
         * SOLUTION: throw new InsufficientParametersException().
         */
        if (paramsInRequest < methodWithLeastParamsInSignature) {
            throw new Exception("Insufficient Parameters");
        }

        /*
         * 3. Inappropriate method being called based on details provided
         * SOLUTION: throw new IncorrectDetailsException().
         */
        if (request.getParameter("method") != null) {
            if (request.getParameter("method").equalsIgnoreCase("isWalking")) {
                if (paramsInRequest == 1) {
                    isWalking(Integer.parseInt(request.getParameter("speed")));
                }
                if (paramsInRequest == 2) {
                    if (request.getParameter("lastLocation") != null) {
                        isWalking(Integer.parseInt(request.getParameter("speed")), request.getParameter("lastLocation"));
                    }
                }
            }
        }

        /*
         * 4. No way of determining what will be returned and what's expected to be returned
         * SOLUTION: Not sure how to resolve
         */
        /*
         * 5. No way of determining which of the parameters in the request should be associated with which of the parameters in the method signature
         * SOLUTION: Not sure how to resolve
         */
        /*
         * 6. Parameters of the wrong type being passed to the method
         * SOLUTION: Try and use instanceof to determine what the type of the parameter is. If it's not correct then throw new IncorrectDetailsException().
         */
        //Parameters are always a String so I'm not sure how to check if it's a valid variable for the method signature
        return true;
    }

    public Boolean isWalking(Integer speed) {
        return speed == 2;
    }

    public Boolean isRunning(Integer speed) {
        return speed == 5;
    }

    public String isWalking(Integer speed, String lastLocation) {
        if ((speed == 2) && (lastLocation.equalsIgnoreCase("nearby"))) {
            return "Yup, you're walking";
        }
        return "";
    }

}

1 个答案:

答案 0 :(得分:0)

您应该使用反射来调用要调用的方法。当提供错误的参数量时,这将给出运行时异常。

定义:

java.lang.reflect.Method method;
try {
  method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..);
} catch (SecurityException e) {
  // ...
} catch (NoSuchMethodException e) {
  // ...
}

然后调用:

try {
  method.invoke(obj, arg1, arg2,...);
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {

方法的Api:http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Method.html