Servlets and JSP
Servlets
A simple “HelloWorld” servlet, that also prints the current date.
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<HTML>"); out.println("<HEAD><TITLE>Hello World</TITLE></HEAD>"); out.println("<BODY>"); out.println("<H1>Hello World</H1>"); out.println("Today is: " + (new java.util.Date().toString()) ); out.println("</BODY></HTML>"); } // doGet } // HelloWorld
In order to run it, do the following:
- Place it in a file, HelloWorld.java
- Compile it.
- Place the resulting HelloWorld.class file in the “servlets” directory.
- Run it by pointing browser to: http://server.address/servlets/HelloWorld
JSP
The same page as above using JSP looks as shown below:
<HTML> <HEAD> <TITLE>Hello World</TITLE> </HEAD> <BODY> <H1>Hello World</H1> Today is: <%= new java.util.Date().toString() %> </BODY> </HTML>
In order to run it, do the following:
- Place it in a file, HelloWorld.jsp in the same directory as your .html files
- Run it by pointing browser to: http://server.address/~youraccount/HelloWorld.jsp