BaseServlet
作者:互联网
通过反射调用方法,以简化Servlet数量。
class BashServlet
package com.demo.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
/* as superclass for all sub-class*/
public class BaseServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
try {
String key = req.getParameter("key");
Class<? extends BaseServlet> clazz = this.getClass();
// key is the method name
Method method = clazz.getMethod(key, HttpServletRequest.class, HttpServletResponse.class);
method.invoke(this,req,resp);
} catch (Exception e) {
e.printStackTrace();
}
}
}
XServlet
package com.demo.servlet;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/x")
public class XServlet extends BaseServlet{
public void methodA(HttpServletRequest request,
HttpServletResponse response)throws Exception{
// some codes
}
}
测试
you can use this url to test http message.
url path: contextname/servletname?key=methodname
此处就是:contextname/x?key=methodA。
标签:BaseServlet,http,class,key,import,servlet,javax 来源: https://www.cnblogs.com/1river/p/14873541.html