6

如何在注解中为 web.XML 提供注解映射。我已经完成了 web.XML。我想尝试使用注释映射,如下所示:

<web-app> 
  <servlet-mapping> 
  </servlet-mapping> 
</web-app>
4

2 回答 2

13

一个简单的例子是:

@WebServlet(value="/hello")
public class HelloServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request,HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();

    // then write the data of the response
    String username = request.getParameter("username");
    if (username != null && username.length() > 0) {
        out.println("<h2>Hello, " + username + "!</h2>");
       }
    }

}
于 2013-07-25T16:23:09.457 回答
5

注释表示元数据。如果您使用注解,则不需要部署描述符(web.xml 文件)。但是你应该有 tomcat7,因为它不会在以前版本的 tomcat 中运行。@WebServlet 注解用于映射具有指定名称的 servlet。

@WebServlet("/Simple")
public class Simple extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        response.setContentType("text/html");
        PrintWriter out=response.getWriter();

        out.print("<html><body>");
        out.print("<h3>Hello Servlet</h3>");
        out.print("</body></html>");
    }

}
于 2013-07-25T16:52:51.910 回答