JSP Tutorial - JSP HelloWorld








Setting up Java Development Kit

First, download Java Software Development Kit (JDK) from Oracle's Java site and setting up PATH environment variable appropriately.

Install and configure the JDK and set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively.

For example,

set PATH=C:\jdk1.8\bin;%PATH%
set JAVA_HOME=C:\jdk1.8

On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.8 and you use the C shell, you would put the following into your .cshrc file.

setenv PATH /usr/local/jdk1.8/bin:$PATH
setenv JAVA_HOME /usr/local/jdk1.8




Setting up Web Server: Tomcat

Apache Tomcat is an open source software implementation of the JavaServer Pages and Servlet technologies.

Download latest version of Tomcat from http://tomcat.apache.org/.

Unpack the binary distribution.

Tomcat can be started by executing the following commands on windows machine:

C:\apache-tomcat-8\bin\startup.bat

After a successful startup, the default web applications will be available by visiting http://localhost:8080/.

Tomcat can be stopped by executing the following commands on windows machine:

C:\apache-tomcat-8\bin\shutdown

JSP Life Cycle

A JSP life cycle are listed as follows.

  • Compilation

  • Initialization

  • Execution

  • Cleanup

When a browser requests a JSP from the JSP engine, the JSP engine first checks to see whether it needs to compile the page.

If the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page.





Example

Suppose your Apache Tomcat is installed in C:\apache-tomcat.

Save the code below in JSP file hello.jsp and put this file in C:\apache-tomcat\webapps\ROOT directory and try to browse it by giving URL http://localhost:8080/hello.jsp in your browser address bar.

<html>
<head><title>Hello World</title></head>
<body>
Hello World!<br/>
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
</body>
</html>

Date Formatting using SimpleDateFormat

SimpleDateFormat can format and parse dates in a locale-sensitive manner.

The following code shows how to output current time.

<%@ page import="java.io.*,java.util.*" %>
<%@ page import="javax.servlet.*,java.text.*" %>
<html>
<body>
<%
   Date dNow = new Date();
   SimpleDateFormat ft = new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
   out.print( "<h2 align=\"center\">" + ft.format(dNow) + "</h2>");
%>
</body>
</html>