JSPA “Hello World” servlet (from the Tomcat installation documentation)ServletsHow JSP worksJSP scripting elementsExample JSPVariablesScriptletsThe case against scriptletsDeclarationsDirectivesThe include directiveActionsJSP in XMLCommentsThe EndJan 13, 2019JSPJava Server PagesReference: http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-JSP.html2A “Hello World” servlet(from the Tomcat installation documentation)public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n"; out.println(docType + "<HTML>\n" + "<HEAD><TITLE>Hello</TITLE></HEAD>\n" + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1>Hello World</H1>\n" + "</BODY></HTML>"); }}This is mostly Java with a little HTML mixed in3ServletsThe purpose of a servlet is to create a Web page in response to a client requestServlets are written in Java, with a little HTML mixed inThe HTML is enclosed in out.println( ) statementsJSP (Java Server Pages) is an alternate way of creating servletsJSP is written as ordinary HTML, with a little Java mixed inThe Java is enclosed in special tags, such as <% ... %>The HTML is known as the template textJSP files must have the extension .jspJSP is translated into a Java servlet, which is then compiledServlets are run in the usual wayThe browser or other client sees only the resultant HTML, as usualTomcat knows how to handle servlets and JSP pages4How JSP worksWhen Tomcat needs to use a JSP page, it:Translates the JSP into a Java servletCompiles the servletCreates one instance of the JSP servletExecutes the servlet as normal Java codeHence, when you are writing JSP, you are writing “higher-level” Java codeEach call to the JSP servlet is executed in a new ThreadSince there is only one JSP object, you have to use synchronization if you use any instance variables of the servletYou have two basic choices when using JSP:Let the JSP do all the work of a servletWrite a servlet that does the work and passes the results to JSP to create the resultant HTML pageThis works because a servlet can call another servletBottom line: JSP is just a convenient way of writing Java code!5JSP scripting elementsThere is more than one type of JSP “tag,” depending on what you want done with the Java<%=He xpressionH%> The e xpression is evaluated and the result is inserted into the HTML page<%HcodeH%>The co de is inserted into the servlet's service methodIf code contains declarations, they become local variables of the service methodThis construction is called a scriptlet <%!HdeclarationsH%>The de c larations are inserted into the servlet class, not into a methodHence, declarations made here become instance variables6Example JSP<HTML><BODY>Hello!H The time is now <%= new java.util.Date() %></BODY></HTML>Notes:The <%= ... %> tag is used, because we are computing a value and inserting it into the HTMLThe fully qualified name (java.util.Date) is used, instead of the short name (Date), because we haven’t yet talked about how to do import declarations7VariablesYou can declare your own variables, as usualJSP provides several predefined variablesrequest : The HttpServletRequest parameterresponse : The HttpServletResponse parametersession : The HttpSession associated with the request, or null if there is noneout : A JspWriter (like a PrintWriter) used to send output to the clientExample:Your hostname: <%= request.getRemoteHost() %>8ScriptletsScriptlets are enclosed in <% ... %> tagsScriptlets are executable code and do not directly affect the HTMLScriptlets may write into the HTML with out.print(v alue ) and out.println(value)Example:<% String queryData = request.getQueryString(); out.println("Attached GET data: " + queryData); %>Scriptlets are inserted into the servlet exactly as written, and are not compiled until the entire servlet is compiledExample:<% if (Math.random() < 0.5) { %> Have a <B>nice</B> day!<% } else { %> Have a <B>lousy</B> day!<% } %>9The case against scriptletsOne of the principle motivations for JSP is to allow Web designers who are not Java programmers to get some of the features of Java into their pagesHence, in some cases it is desirable to put as little actual Java into your JSP as possibleWhere this is a goal, a better approach is to provide the necessary Java functionality via methods in a class that is loaded along with the servlet10DeclarationsUse <%! ... %> for declarations to be added to your servlet class, not to any particular methodCaution: Servlets are multithreaded, so nonlocal variables must be handled with extreme careIf declared with <% ... %>, variables are local and OKIf declared with <%! ... %>, variables may need to be synchronizedData can also safely be put in the request or session objectsExample:<%! private int accessCount = 0; %> Accesses to page since server reboot: <%= ++accessCount %>You can use <%! ... %> to declare methods as easily as to declare variables11DirectivesDirectives affect the servlet class itselfA directive has the form: <%@ dir ec tive attribute="value" %>or <%@ direc t i ve attribute1="val ue1" attribute2="value2" ... attributeN="valueN" %>The most useful directive is page, which lets you import packagesExample: <%@ page import="java.util.*" %>12The include directiveThe include directive inserts another file into the file being parsedThe included file is treated as just more JSP, hence it can include static HTML, scripting elements, actions, and directivesSyntax: <%@ include file="URL " %>The URL is treated as relative to the JSP pageIf the URL begins with a slash, it is treated as relative to the home directory of the Web serverThe include directive is especially useful for inserting things like navigation bars13ActionsActions are XML-syntax tags used to control the servlet engine<jsp:include page="URL " flush="true" />Inserts the indicated relative URL at execution time (not at compile time, like the include directive does)This is great for rapidly changing data<jsp:forward
View Full Document