Saturday, 22 March 2014

Servlets : Helloworld Example


Click here to watch in Youtube : https://www.youtube.com/watch?v=aZxsKLT4vBI

Click the below Image to Enlarge

Helloworld Project Dir Structure
Servlets : Helloworld Example
Helloworld.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// Extend HttpServlet class
public class HelloWorld extends HttpServlet
{

 private static final long serialVersionUID = 1L;
 private String message;

 public void init() throws ServletException
 {
  // Do required initialization
  message = "Hello World";
 }

 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
 {
  // Set response content type
  response.setContentType("text/html");

  // Actual logic goes here.
  PrintWriter out = response.getWriter();
  out.println("<h1>" + message + "</h1>");
 }

 public void destroy()
 {
  // do nothing.
 }
}


Web.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0"
  metadata-complete="true">

    <display-name>HelloWorld Application</display-name>
    <description>
        This is a simple web application with a source code organization
        based on the recommendations of the Application Developer's Guide.
    </description>

     <servlet>
        <servlet-name>HelloWorld</servlet-name>
        <servlet-class>HelloWorld</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>HelloWorld</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
    
</web-app>  

index.html
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<!DOCTYPE HTML><html lang="en"><head>
<meta charset="UTF-8">
<title>Helloworld Example</title>
</head>
<body>
<p>
<h3>Helloworld Example</H3>
<p></p>
<ul>
<li><a href="hello">Helloworld</a></li>

</ul>
</body></html>

To Download HelloworldApp Project Click the below link

https://sites.google.com/site/javaee4321/servlets/HelloworldApp.zip?attredirects=0&d=1

Environment Used:
JDK version :1.6.0_30
Tomcat version : 7.0.50

See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • No comments:

    Post a Comment