Servlet Hello World

Servlet Hello World

This tutorial is the standard Hello World program using Java Servlet

Using an IDE is the best choice to do development. It will help to increase the productivity. 

If you are in the early days of learning, like in college or school then you can use a simple text editor like Notepad++. 

My IDE of choice is Eclipse, but this tutorial is not tied with it. These are just my suggestions and you can go with any editors.

Web Application Structure

First lets start with a shell project structure and we should have directories created as shown below:

Web-Application-Structure

Note the webapps that’s where the application should be deployed in tomcat.

  • webapps – Folder of Tomcat where the project should be put to run.
  • hello-world – Application root folder. It can contain all the static files and other resources like images, css created in this. In real time will have lots of CSS, image etc and those should be create separate folder under this root.
  • WEB-INF – will contain the web.xml file
  • classes – will contain the servlet classes.
  • lib – will contain the dependent jar files.

Hello World Servlet

package com.javapapers.servlet.introduction;

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;

public class HelloWorld extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		res.setContentType("text/html");
		PrintWriter out = res.getWriter();
		out.println("<html><body>");
		out.println("Hello World!");
		out.println("</body></html>");
		out.close();
	}
}

web.xml

In this web.xml we have defined Servlet mapping. Go through this linked tutorial to know about servlet mapping.

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">
    <display-name>Servlet Hello World</display-name>    
    
    <servlet>
        <servlet-name>helloWorldServlet</servlet-name>
        <servlet-class>com.javapapers.servlet.introduction.HelloWorld</servlet-class>
    </servlet>

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

This Servlet Hello World web application contains only the above two files. Download the complete project

Hello-World-Servlet-Output

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值