Servlets - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Servlet Annotation

Servlet Annotation

shape Description

Servlet Annotation, Annotations are used to reduce the code of an application and the main advantage of an annotation is that no need to write mapping file, Annotation tags will be represented with “@”, The following are the tags which will be used in the code. Servlet Annotation will carry meta data that will also be used in the code. ServletAnnotation is used to directly map to servlet program without the use of the web.xml. But these ServletAnnotation run in Tomcat7. Servlet Annotations will not run in previous versions. @WebServlet annotation is used to map servlet program. Name of jar for ServletAnnotation is Java. servlet-3.0.0. v201103241009. jar. Following are the different annotations are utilized in a servlet. The Java.servlet.annotation package will have more annotations that needs to be imported in the code.

Differences Between Web services and Servlets

Webservices like REST, SOAP which provides services which is made available for web application, as we know it can receives values as JSON, string, XML etc either by POST or GET and in the same way it can return data as JSON, string, XML etc. The same thing can be done via servlet, as servlet can receive data as string, JSON etc either by POST or GET and in the same way it can return data as JSON, string, XML etc.User need libraries based upon the web service user use, such as SOAP or REST, servlet libraries are almost in-built in it.

shape Example

Simple.java [java]package annotation; import java.io.IOException; import javax.servlet.*; import javax.servlet.annotation.*; @WebServlet(value="/hello", name="hello-servlet") public class Simple extends GenericServlet { public void service(ServletRequest req, ServletResponse res) throws IOException, ServletException { res.getWriter().println("Welcome to SPlessons"); } }[/java] Where used @WebServlet annotation and used URL also. Following are the attributes accepted by the @WebServlet.
Attribute Description
name The servlet name.
description The servlet description.
displayName The servlet display name.
smallIcon A small icon image for the servlet.
largeIcon A large icon image for the servlet.
initParams @WebInitParam can be used to pass servlet configuration parameters, these three attribute are optional attributes.
[java]@WebServlet(value="/hello", name="hello-servlet")[/java] res.getWrite() is used to get the response and that will be printed as follows. [java]res.getWriter().println("Welcome to SPlessons");[/java] Output Following is the result.

Summary

shape Key Points

  • Servlet Annotation - While using annotations developer no need to write web.xml page.
  • URL pattern also will be written in the annotation syntax only.
  • Servlet Annotation - Annotations will carry meta data.