BaseServlet
2015-11-02 13:43
288 查看
1. 目的:
将提升Servlet的处理请求的能力,而不只限于doGet()/doPost()等请求。
让其Servlet能够自己根据请求,从而触发相应的方法进行处理。
2. 具体代码实现:
3. BaseServlet的作用:
BaseServlet这个类的作用是为了让自己声明的Servlet赋予更多的功能,而不局限于只能处理doGet()/doPost()等这些功能。其中BaseServlet还顺便处理response的编码问题,所以,子类便可不用再处理response编码问题。
4. BaseServlet如何使用:
只需要让子类Servlet继承BaseServlet,然后让客户端的请求增加一个参数:method便可,method参数的值就是要请求处理的方法名。
如:http://localhost:8080/demo/user?method=login&username=admin&password=123
这个意思就是:向UserServlet的login(request,response)方法发送了请求~~
将提升Servlet的处理请求的能力,而不只限于doGet()/doPost()等请求。
让其Servlet能够自己根据请求,从而触发相应的方法进行处理。
2. 具体代码实现:
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 class BaseServlet extends HttpServlet { @Override public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); String methodName = request.getParameter("method"); Class c = this.getClass();//获取当前类 Method method = null; try { method = c.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class); } catch (Exception e){ throw new RuntimeException("您要调用的方法:" + methodName + "(HttpServletRequest,HttpServletResponse),它不存在!"); } try{ method.invoke(this,request, response); }catch(Exception e){ System.out.println("您调用的方法:" + methodName + ", 它内部抛出了异常!"); throw new RuntimeException(e); } } }
3. BaseServlet的作用:
BaseServlet这个类的作用是为了让自己声明的Servlet赋予更多的功能,而不局限于只能处理doGet()/doPost()等这些功能。其中BaseServlet还顺便处理response的编码问题,所以,子类便可不用再处理response编码问题。
4. BaseServlet如何使用:
只需要让子类Servlet继承BaseServlet,然后让客户端的请求增加一个参数:method便可,method参数的值就是要请求处理的方法名。
如:http://localhost:8080/demo/user?method=login&username=admin&password=123
这个意思就是:向UserServlet的login(request,response)方法发送了请求~~
相关文章推荐
- 3GPP TS 24.301 V12.4.0 中文版---5.1&5.2&5.3
- 100个小孩排成一圈,从第一个小孩开始1至3报数,凡报为3的小孩从圈中出来,,求最后出圈的小孩的顺序号是多少
- 证券数据接口 查询证券编码及基本上市信息
- 实现MySQL版的urlencode与urldecode函数
- C++基础——函数模板
- method_exchangeImplementations
- hibernate generator小结
- python 小记
- location.href 实现点击下载功能
- 阿里云双11绽放在即,1111元代金券天天送!
- AspectJ AOP切面编程(XML配置)
- fieldset legend
- c 语言 猜拳小游戏
- led灯点亮
- Linux切换账号
- KISSY整体架构流程
- 链表删除节点--算法复杂度o(1)
- leetcode之Find Median from Data Stream
- android从通讯录中选择联系人并读取号码
- JDBC:大数据量插入的三种方法比较