servlet3.0
1、之前我们创建的项目是servlet2.5,之前的版本,servlet、filter、listener需要配置web.xml
在servlet3.0的时候,没有web.xml,提供注解开发。
servlet注解:@WebServlet(name = "ServletDemo",urlPatterns ={"/demo1","/demo21"})
filter注解:@WebFilter(urlPatterns = "/demo1")
listener注解:@WebListener()
例子:
1 package jd.com.test; 2 3 import javax.servlet.ServletException; 4 import javax.servlet.annotation.WebServlet; 5 import javax.servlet.http.HttpServlet; 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 import java.io.IOException; 9 10 @WebServlet(name = "ServletDemo",urlPatterns ={"/demo1","/demo21"} ) 11 public class ServletDemo extends HttpServlet { 12 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 13 doGet(request,response); 14 } 15 16 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 17 System.out.println("访问demo1了。"); 18 } 19 }
1 package jd.com.test; 2 3 import javax.servlet.*; 4 import javax.servlet.annotation.WebFilter; 5 import java.io.IOException; 6 7 8 @WebFilter(urlPatterns = "/demo1") 9 public class MyFilter implements Filter { 10 11 @Override 12 public void init(FilterConfig filterConfig) throws ServletException { 13 14 } 15 16 @Override 17 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { 18 System.out.println("来到Myfilter"); 19 filterChain.doFilter(servletRequest,servletResponse); 20 } 21 22 @Override 23 public void destroy() { 24 25 } 26 }
学习是一种态度,坚持是质变的利器!