使用@WebServlet注解来开发Servlet

如果你不喜欢使用xml配置而喜欢注解的话,没关系,Servlets API同样提供了一些注解接口给你。你可以像下面的例子一样使用 @WebServlet 注解并且不需要在web.xml里为Servlet注册任何信息。容器会自动注册你的Servlet到运行环境,并且像往常一样处理它。

package com.howtodoinjava.servlets;
 
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
@WebServlet (name = "MyFirstServlet" , urlPatterns = { "/MyFirstServlet" })
public class MyFirstServlet extends HttpServlet {
 
     private static final long serialVersionUID = -1915463532411657451L;
 
     @Override
     protected void doGet(HttpServletRequest request,
             HttpServletResponse response) throws ServletException, IOException
     {
         //Do some work
     }
 
     @Override
     protected void doPost(HttpServletRequest request,
             HttpServletResponse response) throws ServletException, IOException {
         //Do some other work
     }
}

你可能感兴趣的:(JAVA)