1. 程式人生 > >利用反射機制實現servlet的分派功能

利用反射機制實現servlet的分派功能

package com.iflytek.utils;


import java.io.IOException;
import java.lang.reflect.Method;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public abstract class BaseServlet extends HttpServlet {
/**

*/
private static final long serialVersionUID = 5887904330512273719L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
String cmd=request.getParameter("cmd");
if(cmd==null||"".equals(cmd.trim())){
//如果不指定請求的方法,預設為execute
cmd="execute";
}
//根據反射機制
@SuppressWarnings("rawtypes")
Class clazz=this.getClass();
System.err.println("clazz");
try {
//得到呼叫方法的指標
@SuppressWarnings("unchecked")
Method method=clazz.getDeclaredMethod(cmd, HttpServletRequest.class,HttpServletResponse.class);
//呼叫方法
method.invoke(this, request,response);
} catch (Exception e) {
e.printStackTrace();
}
}
public abstract String execute(HttpServletRequest request,HttpServletResponse respone);
}