java Web第三章学习内容(Servlet及过滤器)
来源:尔游网
学习内容:
1.Servlet
2.过滤器
一.Servlet
1. Servlet的生命周期:
实例化-----Servlet容器创建Servlet的实例
初始化-----容器调用init()方法
服务-----客户端请求Servlet,则调用其下的方法
摧毁-----摧毁前调用destroy()方法
2. 创建Servlet
右键new有个Servlet选项新建,一般自动继承HttpServlet类
注:doget方法很少使用,注册都是dopost形式处理,所以可以在doget直接调用dopost
例:doPost(request,response);
创建好后参考代码:
public class Servlet extends HttpServlet {
public Servlet() {
super();
}
public void destroy() {
System.out.println("生命周期结束时");
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void init() throws ServletException {
System.out.println("生命周期初始化");
System.out.println();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
}
3.通过xml文件查看跳转页面和Servlet路径属性
可以在web.xml中添加变量和属性
注:测试Servlet只要在客户端请求的时候才会触发,如需要测试可以直接通过URL地址访问获取测试结果
注意:获取值