0A Servlet+JSP Review
0A Servlet+JSP Review
0A Servlet+JSP Review
A Servlet’s Job
• Read explicit data sent by client (form data)
• Read implicit data sent by client
(request headers)
• Generate the results
• Send the explicit data back to client (HTML)
• Send the implicit data to client
(status codes and response headers)
A Packageless Servlet
Packaging Servlets:
HelloServlet2 (Code)
package coreservlets;
JSP Scripting:
Uses of JSP Constructs
Simple • Scripting elements calling servlet
Application code directly
• Scripting elements calling servlet
code indirectly (by means of utility
classes)
• Beans
• Servlet/JSP combo (MVC)
Complex
• MVC with JSP expression language
Application • Custom tags
JSP Expressions
• Format
– <%= Java Expression %>
• Result
– Expression evaluated, converted to String, and placed
into HTML page at the place it occurred in JSP page
– That is, expression placed in _jspService inside out.print
• Examples
– Current time: <%= new java.util.Date() %>
– Your hostname: <%= request.getRemoteHost() %>
• XML-compatible syntax
– <jsp:expression>Java Expression</jsp:expression>
– You cannot mix versions within a single page. You must
19 use XML for entire page if you use jsp:expression.
J2EE training: http://courses.coreservlets.com
Predefined Variables
• request
– The HttpServletRequest (1st argument to service/doGet)
• response
– The HttpServletResponse (2nd arg to service/doGet)
• out
– The Writer (a buffered version of type JspWriter) used to
send output to the client
• session
– The HttpSession associated with the request (unless
disabled with the session attribute of the page directive)
• application
– The ServletContext (for sharing data) as obtained via
20
getServletContext(). J2EE training: http://courses.coreservlets.com
JSP Scriptlets
• Format
– <% Java Code %>
• Result
– Code is inserted verbatim into servlet's _jspService
• Example
– <%
String queryData = request.getQueryString();
out.println("Attached GET data: " + queryData);
%>
– <% response.setContentType("text/plain"); %>
• XML-compatible syntax
– <jsp:scriptlet>Java Code</jsp:scriptlet>
21 J2EE training: http://courses.coreservlets.com
JSP Declarations
• Format
– <%! Java Code %>
• Result
– Code is inserted verbatim into servlet's class definition,
outside of any existing methods
• Examples
– <%! private int someField = 5; %>
– <%! private void someMethod(...) {...} %>
• Design consideration
– Fields are clearly useful. For methods, it is usually better
to define the method in a separate Java class.
• XML-compatible syntax
22 – <jsp:declaration>Java Code</jsp:declaration>
J2EE training: http://courses.coreservlets.com
Questions?