This laboratory exercise involves developing a Hello World servlet, step by step. It gets easier once you've worked out the process - your first servlet will be your hardest!
In theory, creating a Servlet is a complex process:
- Write the code
- Compile
- Lay out class files and other resources in a special directory structure
- Compress the directory structure using jar (this uses the zip file format), and rename the file to a ".war" extension.
- Deploy the ".war" file to the web application server (e.g., copy to a special folder).
However, NetBeans will do steps 2-5 for you, at the "click of a button".
Create a Servlet
- Create a new Project
- In the category "Java Web", select the "Web Application" project type
- Choose a name: Week2
- Ensure the Server is "GlassFish Server 4.1.1" and the Java EE Version is "Java EE 7 Web" (the context path is the address on the web-server that your application will be deployed to)
- Don't add any frameworks
- Create a new File
- Choose File... New File...
- In the "Web" category, select the "Servlet" file type
- Enter the class name "HelloWorld" and the package name "au.edu.uts.aip.week2
- Leave the URL Pattern as-is (i.e., "/HelloWorld")
The generated Servlet is quite complex, let's replace it with something simple. Delete the code and copy-and-paste this code in its place:
package au.edu.uts.aip.week2;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
@WebServlet("/HelloWorld")
public class HelloWorld extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>First Servlet</title>");
out.println("<body><p>Hello, World!</p></body>");
out.println("</html>");
}
}
Run the Servlet
Now, run the project (click the green play button). Your application will be compiled, GlassFish Server 4.1.1 and Java DB Database will be automatically started (this could take a while), your application will be deployed to the GlassFish server and a web browser will open.
Now, modify the address on your browser to the following address:
http://localhost:8080/Week2/HelloWorld
- http is the protocol
- localhost is the name of the server
- 8080 is the port the server is running on (normally web servers run on port 80 but development systems often run on port 8080)
- /Week2 is the context path from when we created the project
- /HelloWorld is the url pattern of the Servlet (i.e., the pattern inside the
@WebServlet("/HelloWorld")
)
The message, "Hello, World!" should appear!
See if you can edit the Java code to display some other message. Note that when you save the file, NetBeans will automatically compile and deploy your application -- you do not need to click the run button again.
Reflection
Can you explain each line of code in this Servlet?