In this tutorial how to create a new project, how to create Hello World Program and how to execute the project in Advance Java (J2EE) is shown.
To Create a new J2EE Project in Netbeans IDE, follow the below mentioned steps:
- Go to File Menu
- Select New Project
- A new Dialog Box will appear
- In the Categories Select “Java Web” and in Projects Select “Web Application”
- Then click on Next Button
- Write the Project Name
- Set the path of the project if required
- Then click on Next Button
- Now select a Server
- And click on Finish Button
To create a new Servlet
- Right Click on “Web Pages” Folder
- In New, select Servlet
- A new Dialog Box will appear
- Enter the Class name, it should be same as the action attribute in <form> tag
- Then click on Next Button
- Now Select the checkbox for Add information to deployment descriptor (web.xml)
- Click on Finish Button
Code:
index.html
<html>
<head>
<title>My first hello world program</title>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
</head>
<body>
<form action=”HelloWorld” method=”POST”>
<input type=”submit” value=”Click Here”>
</form>
</body>
</html>
HelloWorld.java
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 {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(“text/html;charset=UTF-8”);
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println(“<!DOCTYPE html>”);
out.println(“<html>”);
out.println(“<head>”);
out.println(“<title>Servlet HelloWorld</title>”);
out.println(“</head>”);
out.println(“<body>”);
out.println(“<h1>” + “Hello World” + “</h1>”);
out.println(“</body>”);
out.println(“</html>”);
}
}
}
web.xml
<?xml version=”1.0″ encoding=”UTF-8″?>
<web-app version=”3.1″ xmlns=”http://xmlns.jcp.org/xml/ns/javaee” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd”>
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>