1. 程式人生 > >Java中如何自定義HTTPServlet中的請求方式?

Java中如何自定義HTTPServlet中的請求方式?

自定義HTTPServlet中的請求方式:

本Markdown編輯器使用[StackEdit][6]修改而來,用它寫部落格,將會帶來全新的體驗哦:

  • 應用中的所有對Servlet的請求都需要新增method=xxx的請求引數
  • 在應用的Servlet類中, 只需要定義處理請求的方法:
  • public void xxx(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException { }

抽象類程式碼塊

public abstract class BaseServlet extends
HttpServlet {
private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); String methodName = req.getParameter("method"); try
{ Method method = this.getClass().getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class); method.invoke(this, req, resp); } catch (Exception e) { //e.printStackTrace(); Throwable cause = e.getCause(); if(cause instanceof
DBException) { throw new DBException(cause); } } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }