标签:
1.删除了web.xml 文件
2. 在Servlet类上添加@WebServlet(urlPatterns={"/AServlet"})
3. 在Filter类上添加@WebFilter(urlPatterns="/AFilter")
4. 在Listener类上添加@WebListener
?
总结:
* 注解好处:配置信息少,使用很方便!
* 注解缺点:不方便修改!(如果需要修改,就要更改源码)
?
?
Aservlet.java文件
/* 原先servlet 在web.xml 文件中需要配置大量的信息: <servlet> <servlet-name>AServlet</servlet-name> <servlet-class>cn.itcast.web.servlet.AServlet</servlet-class> <init-param> <param-name>p1</param-name> <param-value>v1</param-value> </init-param> <init-param> <param-name>p2</param-name> <param-value>v2</param-value> </init-param> <load-on-startup>1<load-on-startup> </servlet> <servlet-mapping> <servlet-name>AServlet</servlet-name> <url-pattern>/AServlet</url-pattern> <url-pattern>/AAServlet</url-pattern> </servlet-mapping> ? */ ? /* * 但是现在使用 注解,就方便多了 */ @WebServlet(urlPatterns="/AServlet", ????initParams={ ????????@WebInitParam(name="p1", value="v1"), ????????@WebInitParam(name="p2", value="v2") ????}, ????loadOnStartup=1 ) public class AServlet extends HttpServlet { ????public void doGet(HttpServletRequest req, HttpServletResponse resp) ????????????throws ServletException, IOException { ????????System.out.println("hello servlet3.0!"); ????????resp.getWriter().print("hello servlet3.0!!"); ????} } |
?
Afilter.java 文件:演示 过滤器的 注解使用
//(urlPatterns="/*") 表示 : 过滤所有的路径 @WebFilter(urlPatterns="/*") public class AFilter implements Filter { ? ????@Override ????public void destroy() { ????????// TODO Auto-generated method stub ???????? ????} ? ????@Override ????public void doFilter(ServletRequest request, ServletResponse repsonse, ????????????FilterChain chain) throws IOException, ServletException { ????????System.out.println("哈哈~,你看到我没有!"); ????????chain.doFilter(request, repsonse);//放行 ????} ? ????@Override ????public void init(FilterConfig arg0) throws ServletException { ????????// TODO Auto-generated method stub ???????? ????} ? } |
?
Alistener.java 文件: 演示 监听器的注解使用
import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; //监听器的注解 @WebListener public class AListener implements ServletContextListener { ? ????@Override ????public void contextDestroyed(ServletContextEvent arg0) { ????????System.out.println("死掉了"); ? ????} ? ????@Override ????public void contextInitialized(ServletContextEvent arg0) { ????????System.out.println("出生了"); ? ????} ? } |
servlet3.0 的新特性之二注解代替了web.xml配置文件
标签:
原文地址:http://www.cnblogs.com/Prozhu/p/5452675.html