评估HttpServlet请求是否是一个有效的方法调用



我认为在使用请求中的详细信息调用方法时,验证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 "";
    }
}

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

定义:

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

相关内容

最新更新