Learn Java for Web Development

(Tina Meador) #1

70 CHAPTER 2: Building Web Applications Using Servlets and JSP


15.private static final long serialVersionUID = 1L;
16.



  1. /**



    • @see HttpServlet#HttpServlet()



  2. */

  3. public HelloWorld() {

  4. super();

  5. // TODO Auto-generated constructor stub

  6. }


  7. 25./**





    • @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)



  8. */
    28.protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
    ServletException, IOException {
    29.// TODO Auto-generated method stub
    30.}


  9. 32./**





    • @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)



  10. */
    35.protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
    ServletException, IOException {
    36.// TODO Auto-generated method stub
    37.}


  11. 39.}




   Line 13: This line shows the usage of the @WebServlet annotation. The
HelloWorld servlet is decorated with the @WebServlet annotation to specify
the name, URL pattern, initialization parameters, and other configuration items
usually specified in the web.xml deployment descriptor.
 Line 14: This line shows that the HelloWorld servlet extends the HTTPServlet.
 Lines 28 to 37: These lines show the doGet and doPost methods generated by
the IDE.

Add the code in Listing 2-13 to the doGet method of the HelloWorld servlet.


Listing 2-13. Printing “Hello World”


PrintWriter out = response.getWriter();
out.println("

Hello World !

");


You will have to import java.io.Printwriter. You can do this in Eclipse by selecting Source ➤
Add Import or by pressing Ctrl+Shift+M; now you can run the application on the server. Right-click
HelloWorld.java in the helloworld project in Eclipse and then select Run As ➤ Run on Server. The
server you are using in this case is Tomcat 7.0. Then use the following URL to access the application:


http://localhost:8080/helloworld/HelloWorld

Free download pdf