| Introduction to Java Server Pages |
| |
| Convenience of JSP Coding Versus Servlet Coding |
| |
| Combining Java code and Java calls into an HTML page is more convenient than using straight Java code in a servlet.
JSP syntax gives us a shortcut for coding dynamic Web pages, typically requiring much less code than Java servlet syntax
|
| |
| Following is an example contrasting servlet code and JSP code |
| |
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Hello extends HttpServlet
{
public void doGet(HttpServletRequest rq, HttpServletResponse rsp)
{
rsp.setContentType("text/html");
try {
PrintWriter out = rsp.getWriter();
out.println("("<HTML>");
out.println("<HEAD><TITLE>Welcome</TITLE></HEAD>");
out.println("("<BODY>");
out.println("("<H3>Welcome!</H3>");
out.println("("<P>Today is "+new java.util.Date()+".</P>");
out.println("("</BODY>");
out.println("("</HTML>");
} catch (IOException ioe)
{
// (error processing)
}
}
}
|
| |
| JSP Code |
<HTML>
<HEAD><TITLE>Welcome</TITLE></HEAD>
<BODY>
<H3>Welcome!</H3>
<P>Today is <%= new java.util.Date() %>.</P>
</BODY>
</HTML> |
| |
Note how much simpler JSP syntax is. Among other things, it
saves Java overhead such as package imports and try...catch blocks.
Additionally, the JSP translator automatically handles a significant amount of
servlet coding overhead for us in the .java file that it outputs, such as directly
or indirectly implementing the standard javax.servlet.jsp.HttpJspPage interface
and adding code to acquire an HTTP session.
Also note that because the HTML of a JSP page is not embedded within Java print
statements, as it is in servlet code, we can use HTML authoring tools to create JSP pages.
|
| |
| |
|
| |
| |