BaseServlet(一个Servlet多个处理方法)

BaseServlet是用来作为其它Servlet父类的,它有如下两个优点:

一个Servlet多个处理方法

BaseServlet的作用是用来简化Servlet。通过我们需要为每个功能编写一个Servlet,例如用户注册写一个RegistServlet,用户登录写一个LoginServlet。如果使用BaseServlet,那么我们可以只写一个UserServlet,然后让UserServlet去继承BaseServlet,然后在UserServlet给出两个请求处理方法,一个方法叫regist(),一个叫login()。

BaseServlet来简化了Servlet中请求转发和重定向的代码。

简化了请求转发和重定向的代码

BaseServlet中的请求处理方法有一个String类型的返回值,返回值表示转发或重定向的目标页面。例如:

  • f:/index.jsp:其中f:表示转发,即forward的意思,/index.jsp表示转发到/index.jsp页面;
  • r:/index.jsp:其中r:表示重定向,即redirect的意思,/index.jsp表示重定向到/index.jsp页面。
  • null:表示不转发也不重定向;

因为BaseServlet中可以有多个请求处理方法,所以在访问BaseServlet时一定要给出名为method的参数来指定要请求的方法名称。

AServlet.java
public class AServlet extends BaseServlet {
    /**
     * 请求处理方法的参数都与doGet()和doPost()相同,即request和response
     * 但请求处理方法有String类型的返回值,而doGet()和doPost()没有返回值。
     * 在请求本方法时需要给出method=regist参数!
     */
//访问本方法的URL为http://localhost:8080/day01/AServlet?method=regist](HttpServletRequest req, HttpServletResponse resp)
    public String regist throws ServletException, IOException {
        System.out.println("AServlet regist()...");
        return "f:/index.jsp";//转发到/index.jsp页面
    }
    
    /**
     * 在请求本方法时需要给出method=login参数!
     */
//访问本方法的URL为http://localhost:8080/day01/AServlet?method=login](HttpServletRequest req, HttpServletResponse resp)
    public String login throws ServletException, IOException {
        System.out.println("AServlet login()...");
        return "r:/index.jsp";//重定向到/index.jsp
    }
}
posted @ 2017-05-10 08:05  _Nicole  阅读(1081)  评论(0编辑  收藏  举报