Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write hello world servlet Example

Tags:

java

servlets

javaclass

package com.example;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class
public class Helloworld extends HttpServlet {
    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

<servlet>
        <servlet-name>HelloForm</servlet-name>
        <servlet-class>HelloForm</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>HelloForm</servlet-name>
        <url-pattern>/HelloForm</url-pattern>
    </servlet-mapping>

Give is code But i run the Project There is no Output comes 404 Error is comes in web Page . we need create Jsp Page also for servlet? I am really new in Servlet Please help how to write hello world is Servlet .

like image 750
user2782773 Avatar asked Dec 04 '22 09:12

user2782773


2 Answers

You have created servlet class like this:

public class Helloworld extends HttpServlet

But in web.xml you have mapping like this:

<servlet-class>HelloForm</servlet-class>

You need to have same name, so you're getting 404 error. Change either your servlet name to HelloForm or change <servlet-class> to HelloWorldin web.xml

like image 164
Pradeep Simha Avatar answered Feb 02 '23 20:02

Pradeep Simha


Your class resides in com.example

So servlet-class should,

<servlet-class>com.example.Helloworld</servlet-class>
like image 23
Himanshu Bhardwaj Avatar answered Feb 02 '23 20:02

Himanshu Bhardwaj