How to provide an annotation mapping for web.XML in annotation. I have done with web.XML. I want to try with Annotation mapping, like so:
<web-app>
<servlet-mapping>
</servlet-mapping>
</web-app>
The <servlet-mapping> element specifies a URL pattern and the name of a declared servlet to use for requests whose URL matches the pattern. The URL pattern can use an asterisk ( * ) at the beginning or end of the pattern to indicate zero or more of any character.
Use the @WebServlet annotation to define a servlet component in a web application. This annotation is specified on a class and contains metadata about the servlet being declared. The annotated servlet must specify at least one URL pattern. This is done by using the urlPatterns or value attribute on the annotation.
XML Still Needed Even, with all the features introduced in Servlet 3.0, there are some use cases where we'll still need a web. xml file, among them: We can't define the filter order with annotations – we still need the <filter-mapping> section if we have multiple filters that we need to be applied in a particular order.
No, there will be no need of web. xml for servlet based application if you are using servlet version >3.0 and tomcat 7 as it will not run in the previous versions of tomcat. Annotation represents the metadata. If you use annotation, deployment descriptor (web.
A simple example is :
@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>");
}
}
}
Annotation represents the metadata. If you use annotation, deployment descriptor (web.xml file) is not required. But you should have tomcat7 as it will not run in the previous versions of tomcat. @WebServlet annotation is used to map the servlet with the specified name.
@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>");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With