servlet的优化即封装
servlet的封装
比如:用户操作相关servlet管理
Baseservlet
1 package cn.hoagn.servlet; 2 3 import javax.servlet.ServletException; 4 import javax.servlet.http.HttpServlet; 5 import javax.servlet.http.HttpServletRequest; 6 import javax.servlet.http.HttpServletResponse; 7 import java.io.IOException; 8 import java.lang.reflect.InvocationTargetException; 9 import java.lang.reflect.Method; 10 11 12 public class BaseServlet extends HttpServlet { 13 @Override 14 protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 15 // super.service(req, resp); 16 17 System.out.println("方法被执行了"); 18 19 // 获取路径 20 String requestURI = req.getRequestURI(); 21 StringBuffer requestURL = req.getRequestURL(); 22 System.out.println("requestURI:"+requestURI+" requestURL:"+requestURL); // requestURI:/user/da requestURL:http://localhost/user/da 23 // 截取 24 String methonName = requestURI.substring(requestURI.lastIndexOf("/")+1); // 25 System.out.println(methonName); // da 26 27 System.out.println(this); // cn.itcast.travel.servlet.UserServlet@3599a2d1 28 29 // 分发 30 31 try { 32 // 获取方法 33 Method declaredMethod = this.getClass().getMethod(methonName, HttpServletRequest.class, HttpServletResponse.class); 34 // 忽略访问权限修饰,获取方法 35 // Method declaredMethod = this.getClass().getDeclaredMethod(methonName, HttpServletRequest.class, HttpServletResponse.class); 36 //暴力反射 37 // declaredMethod.setAccessible(true); 38 39 // 执行方法 40 declaredMethod.invoke(this,req,resp); 41 42 } catch (NoSuchMethodException e) { 43 e.printStackTrace(); 44 } catch (IllegalAccessException e) { 45 e.printStackTrace(); 46 } catch (InvocationTargetException e) { 47 e.printStackTrace(); 48 } 49 50 51 } 52 }
UserServlet
package cn.hogan.servlet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/user/*") public class UserServlet extends BaseServlet { public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("执行了add方法"); } public void get(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("执行了get方法"); } }