一个简单的Servlet工具

以前老师在项目中用过一个Sevlet的工具,就是在请求Servlet的时候带一个参数,该参数决定要执行Servlet中的方法,

public class ServletUtils extends HttpServlet{

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(req,resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//1 获得要执行的方法的名称
String methodName = req.getParameter("method");

//反射本对象,查出是否包含与上述方法名一致的方法
Class clazz = this.getClass();
Method[] methods = clazz.getMethods();
for(Method method:methods){
String methodN = method.getName();
if(methodN.equals(methodName)){
try {
String result = (String)method.invoke(this, req,resp);

if(result.startsWith("f://")){ // 转发
String uri_r = result.substring(4);
req.getRequestDispatcher(uri_r).forward(req, resp);
}
if(result.startsWith("r://")){ //重定向
String uri_f = result.substring(4);
resp.sendRedirect(uri_f);
}

} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}

}

Servlet的定义是这样的

public class demo extends ServletUtils {

public String demo007(ServletRequest req,ServletResponse resp){
String message = req.getParameter("message");
req.setAttribute("message", message);
return "f://demo.jsp";
}

public String demo008(ServletRequest req,ServletResponse resp){
return "f://index.jsp";
}
}

请求格式是这样的

http://localhost/ServletStu/demo?method=demo007&message=tyyfuckyou

上一篇:XML代码生成器——XMLFACTORY 简介(一)


下一篇:visual studio code(vscode) 调试php