偶遇错误405
在创建动态web工程时,我们要创建一个servlet类,这时虚拟机会给我们自动生成两个处理浏览器请求的方法——doGet(request,response)和doPost(request,response)。但是大家都知道,无论是get请求还是post请求,一个service(request,response)方法通通搞定,所以我们一般习惯于用service方法来处理浏览器与服务器的交互。
重写了service(request,response)方法后,我删除了doGet()与doPost()两个方法。
/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub//该方法被删除}/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub//该方法被删除}@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {// TODO Auto-generated method stubsuper.service(req, resp);}然后写了一些简单的代码测试浏览器与服务器的交互,页面跳转等问题。结果出乎意料,代码没有低级错误,却产生了错误“405——method_post_not_supported”,网页上则显示“HTTP Status 405 - HTTP method POST is not supported by this URL”方法不被允许,让人困惑!
自己写的代码没有逻辑上的错误,所以产生错误的地方八成在super.service(req, resp)上,打开父类HttpServlet的源码,找到service(rep,resp)方法,一下恍然大悟。第一,service(rep,resp)方法调用了几乎所有的处理浏览器与服务器交互的方法——doGet(),doPost(),doDelete()....;第二,doGet()和doPost()方法会产生405 error(resp.sendError(405, msg))
[size=medium] 由于我将两个重写的方法删除了,而没有删除对父类service()方法的调用(super.service(req, resp)),所以父类的service()方法调用doGet()或doPost()方法,子类没有这两个方法的重写,直接调用父类的方法,产生了405 error(还有一些内部的原因,不是很清楚)。
解决方案:删除super.service(req, resp)或重写doGet()与doPost()方法,也就是把之前删掉的两句加上。