{{theTime}}

Search This Blog

Total Pageviews

@webservlet annotation to simplify deployment of servlets

Servlet 3.0, which is supported by Tomcat 7, introduces the @WebServlet annotation, which greatly simplifies the deployment of servlets. You no longer need to write the deployment descriptor in "web.xml". Instead, you can use the @WebServlet annotation to specify the url mapping. For example, let us write a new servlet called HelloAgainServlet.java, by modifying the HelloServlet.java written earlier, with url mapping of "sayhi". // To save as "\webapps\hello\WEB-INF\classes\AnotherHelloServlet.java" import java.io.*; import javax.servlet.*; import javax.servlet.annotation.*; import javax.servlet.http.*; @WebServlet("/sayhi") public class AnotherHelloServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Set the response MIME type response.setContentType("text/html;charset=UTF-8"); // Allocate a output writer to write the response message into the network socket PrintWriter out = response.getWriter(); // Write the response message, in an HTML page try { out.println(""); out.println("Hello, World"); out.println(""); out.println("

Hello world, again!

"); // says Hello // Echo client's request information out.println("

Request URI: " + request.getRequestURI() + "

"); out.println("

Protocol: " + request.getProtocol() + "

"); out.println("

PathInfo: " + request.getPathInfo() + "

"); out.println("

Remote Address: " + request.getRemoteAddr() + "

"); // Generate a random number upon each request out.println("

A Random Number: " + Math.random() + "

"); out.println(""); } finally { out.close(); // Always close the output writer } } } In Line 7, the annotation @WebServlet("/sayhi") is used to declare the url mapping for this servlet, i.e., http://localhost:9999/hello/sayhi. There is no need to provide any more configuration in "web.xml"!

No comments:

Best Client Optimized Programming Language for Mobile Development?

Use Google's Dart language, which is Object-oriented, class-based and garbage-collected language with C-Style.  Dart can compile to eith...