最近在实验一个Servlet有多个请求处理的方法
package com.ymh.servlet;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @author cobblepot.ymh on 2017/10/5 下午9:47.
*
* 在这里给出多个请求处理的方法,
* 请求处理方法:除了名称以外,都与service方法相同
*/
@WebServlet("/AServlet")
public class AServlet extends javax.servlet.http.HttpServlet {
protected void doPost(HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
}
protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
}
public void addUser(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
System.out.println("adduser");
}
public void editUser(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
System.out.println("edituser");
}
protected void service(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
String methodName = request.getParameter("method");
if(methodName == null || methodName.trim().isEmpty()){
throw new RuntimeException("没有传递参数");
}
Class c = this.getClass();
Method method = null;
try {
method = c.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
} catch (NoSuchMethodException e) {
throw new RuntimeException( methodName + "方法不存在");
}
try {
method.invoke(this, request, response);
} catch (Exception e) {
throw new RuntimeException(methodName + "方法不存在");
}
}
}
出现了异常
里面的c.getMethod()只能找到public的方法
而getDeclaredMethod 可以调用所有方法