在我们使用Servlet是,因为xml中每增加一个Servlet就要增加新的配置,会导致后期xml文件中配置冗杂,所以我们这个时候就是可以使用Servlet的注解开发
1.导入配置,Servlet必须要是3.0以上的版本
<dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency>
如果你的IDEA是2021版本以上的话,那么你再创建Servlet项目的时候,就已经用了
2,点击包名,点击New,然后往下滑,找到servlet ,点击创建就完成了,然后出现的画面是:
@WebServlet(name = "AnnotationServlet", value = "/AnnotationServlet") public class AnnotationServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println(" jiandan "); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
这里/Annotation就是我们的url地址,而我们主要是在doGet方法中写代码。我们这样就可以不用配置xml文件了,大大提高了开发速度