如何在注释中为web.XML提供注释映射。我已经完成了web.XML。一世 想尝试使用注释映射,如下所示:
<web-app>
<servlet-mapping>
</servlet-mapping>
</web-app>
答案 0 :(得分:12)
一个简单的例子是:
@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>");
}
}
}
答案 1 :(得分:5)
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>");
}
}