【问题标题】:How to use annotations instead of web.xml in the servlet to specify url如何在servlet中使用注解而不是web.xml来指定url
【发布时间】:2013-06-18 16:09:57
【问题描述】:

如何在注解中为 web.XML 提供注解映射。我已经完成了 web.XML。一世 想试试注解映射,像这样:

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

【问题讨论】:

    标签: servlet-3.0


    【解决方案1】:

    一个简单的例子是:

    @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>");
           }
        }
    
    }
    

    【讨论】:

      【解决方案2】:

      Annotation 表示元数据。如果您使用注解,则不需要部署描述符(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>");
          }
      
      }
      

      【讨论】:

      • 我已经有了解决方案,如果你想回答,我已经发布了一个问题检查它。
      猜你喜欢
      • 2016-04-09
      • 2013-02-28
      • 1970-01-01
      • 2013-03-01
      • 2017-01-06
      • 2011-11-04
      • 2015-11-19
      • 2015-12-10
      相关资源
      最近更新 更多