Servlet生命周期的各个阶段
- 实例化 -->Servlet容器创建Servlet的实例
- 初始化 -->该容器调用init()方法
- 服务 -->如果请求Servlet,则容器调用service()方法
- 销毁 -->销毁实例之前调用destroy()方法
监听处理过程有doGet,doPost。
一般只处理一个,在一个中调用另一个即可,如doGet方法:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response); //转调用doPost
}
doPost(request, response); //转调用doPost
}
具体doPost干活:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//转码,防止乱码request.setCharacterEncoding("utf-8");//请求转码
response.setContentType("text/html;charset=utf-8");//响应转码,注意charset小写
//接受参数,举例...
String username = request.getParameter("username");
String passwd = request.getParameter("passwd");
//具体方法
//...
//跳转if ("admin".equals(username) && "admin".equals(passwd))
{
response.sendRedirect("index.jsp");
}
else
{
response.sendRedirect("login.jsp");
}