









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
This is an Introductory course of Java Web Programming focusing on writing maintainable extensible code, methods of debugging, logging and profiling. The Java Technology used is J2EE an Enterprise Application Development tool. This lecture includes: JSP, Servlet, Java, Architecture, Static, Dynamic, Content, Request, Execution, Generation
Typology: Slides
1 / 16
This page cannot be seen from the preview
Don't miss anything!










2 cs420 Fall 2009-
JSP ~ Basics JSP Lifecycle ` JSP scope objects
` JavaBeans for JSP
` Reference: www.javapassion.com/j2ee
JSP & Servlet in Java EE Architecture
Java Servlet A Java program that extends the functionality of a Web server, generating dynamic content and interacting with Web clients using a request-response paradigm.
An extensible Web technology that uses template data, custom elements, scripting languages, and server-side Java objects to return dynamic content to a client. Typically the template data is HTML or XML elements. The client is often a Web browser.
An extensible Web technology that uses template data, custom elements, scripting languages, and server-side Java objects to return dynamic content to a client. Typically the template data is HTML or XML elements. The client is often a Web browser.
This picture describes what roles JSP and Servlet plays in J2EE architecture. Servlet is a program that extends the functionality of a web server by generating dynamic contents and interacting with web clients using request‐response paradigm. JSP is an extensible web technology that uses template data, custom elements, string languages, and server‐side Java objects to return dynamic contents to a client. Typically the template data or static data is HTML or XML elements. Slide 4
` HTML, XML, Text
Java code Displaying properties of JavaBeans
So what is a JSP page? JSP page is simply a text‐based document capable of returning both static and dynamic content to a client browser. And the static and dynamic content are typically intermixed. Static content can be made of HTML tags, XML tags, or plain Text content while dynamic content can be generated by Java code, displaying properties of JavaBeans or invoking business logic defined in custom tags. Typically a JSP page is made of static template usually in the form HTML page in which Java code, JavaBeans, custom tags are used for dynamic contents generation.
Slide 5
JSP Benefits Content and display logic are separated Simplify web application development with JSP, JavaBeans and custom tags Supports software reuse through the use of components (JavaBeans, Custom tags) Automatic deployment **Recompile automatically when changes are made to JSP pages** Æ / Easier to author web pages ` Platform-independent
So just recap the benefits of using JSP... First, under JSP architecture, contents and display logic(or presentation logic) are separated. Consequently using JSP, web application development can be simplified because business logic is captured in the form of JavaBeans or custom tags while presentation logic is captured in the form of HTML template.. Because the business logic is captured in component forms, they can be reused in other Web applications. Most web containers will automatically recompile newly modified JSP pages. And again for web page authors, dealing with JSP page is a lot easier than writing Java code. And just like Servlet technology, JSP technology runs over many different platforms. Slide 8
Public class OrderServlet…{ public void doGet(…){ if(isOrderValid(req)){saveOrder(req); out.println(“”);out.println(“”); private void isOrderValid (….){…… ……} private void saveOrder(….){…… } } isOrderValid( )
JSP ** …..
**
Pure Servlet
saveOrder( )
JavaBeans
Servlet Public class OrderServlet …{ public void doGet(…){ ……if(bean.isOrderValid (..)){ bean.saveOrder(….); } forward(“conf. jsp”); }
Request processing
presentation
Servlet is used for controlling and Business logic dispatching while JSP page is used for displaying
I mentioned several times already that one of the distinguished features of JSP is the separation of contents generation logic from presentation logic. Here the contents generation includes business logic processing. I also mentioned that in a typical production environment, both servlet and JSP are used together in which servlet is used for controlling and dispatching while JSP page is used for displaying. This slide shows exactly that scenario. On the left, you have a pure servlet based design where contents generation and presentation logic are all handled within a servlet. Now on the right side of the picture where servlet and JSP are used together, servlet performs controlling and dispatching while JSP is used for displaying. How does servlet select which JSP pages to be displayed? It uses forward() method in which a JSP page is specified as a page to be displayed. And that is what is shown in the servlet code on the top box of the right hand side.
` Servlets can do a lot of things, but it is pain to:
Jus to summarize the reason of usage of JSP over Servlet. In servlet, in order to create HTML pages, you have to use println()statements which is really a pain. Also because servlet is Java program, whenever you make a change, you have to recompile and redeploy, which is not really convenient. And JSP correct both of these problems of Servlet.
Slide 10
File Changed ?
Execute Servlet
Create Source
Compile
User Request
Server
YES^ JSP
NO
When a HTTP request is mapped to a JSP page, it is handled by a special built‐in servlet (that is provided by a container) that first checks whether the JSP page's servlet is older than the JSP page. If it is, the container translates the JSP page into a servlet Java code and compiles the servlet code into servlet class. And this is done automatically by the container. This is one of the advantages of using JSP over servlet from deployment standpoint.
Translation/Compilation Phase Static Template data is transformed into code that will emit data into the stream JSP elements are treated differently **Directives** are used to control how Web container translates and executes JSP page Scripting elements are inserted into JSP page's servlet class ` Elements of the form are converted into method calls to JavaBeans components
Now how does translation work? During the translation phase, each type of data in a JSP page is treated differently. That is, static data will be treated differently from dynamic contents generation elements. Static data (this is sometimes called as template data) is transformed into Java code that will emit the data into the output stream which returns data to the client. However, JSP elements, which are typically used for dynamic contents generation,are treated as follows:
JSP Lifecycle Methods during Execution Phase
Once the page has been translated and compiled, the JSP page's servlet for the most part follows the servlet life cycle as following:
If the container needs to remove the JSP page's servlet, it calls the jspDestroy() method. Slide 15
<%@ page import="database." %> <%@ page errorPage="errorpage.jsp" %> <%-- Declare initialization and finalization methods using JSP declaration --%> <%! private BookDBAO bookDBAO; public void jspInit() { // retrieve database access object, which was set once per web application bookDBAO = (BookDBAO)getServletContext().getAttribute("bookDB"); if (bookDBAO == null) System.out.println("Couldn't get database."); } public void jspDestroy() { bookDBAO = null; } %>*
The bookstore example page initdestroy.jsp defines the jspInit() method in which a database access object called BookDBAO is retrieved from the ServletContext object and then uses it to access the bookstore database. When the JSP page is to be removed, the jspDestroy() method releases the BookDBAO variable. In this example, you probably have noticed that the jspInit() method does not create itself a connection to database. Instead it tries to get a reference to a previously created database connection object, which we call database access object here. The reason is since the database access object is shared among all the JSP pages and Servlets in a single Web application, it should be initialized when the application gets started, instead of in each JSP page. Java Servlet technology provides application life‐cycle event and listener classes for this purpose. (Please see how the database.BookDBAO has been set in \tutorial\examples\web\bookstore2\src\listeners\ContextListener.java.)þ
Slide 16
16 cs420 Fall 2009-
GreetingServlet.java (3)
public String getServletInfo() { return "The Hello servlet says hello."; } }
Slide 20
greeting.jsp
** Hello
My name is Duke. What is yours?**
**
**
**<% String username = request.getParameter("username"); if ( username != null && username.length() > 0 ) { %> <%@include file="response.jsp" %> <% } %>
**
Now this is the Hello web application this time using JSP. As you can see, JSP includes HTML tags so you are not creating HTML response in your Java code, instead they are part of JSP page. Then some dynamic contents are created through embedded Java code within the JSP page. By the way, as we will see later on, inserting Java code as part of JSP page is not really a recommended way of performing dynamic contents generation. I am just showing this example to make a point.
ResponseServlet.java
import java.io.; import java.util.; import java.sql.; import javax.servlet.; import javax.servlet.http.; // This is a simple example of an HTTP Servlet. It responds to the GET // method of the HTTP protocol. public class ResponseServlet extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ PrintWriter out = response.getWriter(); // then write the data of the response String username = request.getParameter("username"); if ( username != null && username.length() > 0 ) out.println("Hello, " + username + "!"); } public String getServletInfo() { return "The Response servlet says hello."; } }*
This is the web component, ResponseServlet, that was dispatched from the GreetingServlet.
JSP is “Servlet”
JSP pages get translated into servlet Tomcat translates greeting.jsp into greeting$jsp.java Scriptlet (Java code) within JSP page ends up being inserted into jspService() method of resulting servlet Implicit objects for servlet are also available to JSP page designers, JavaBeans developers, custom tag designers
Just to reiterate how JSP and Servlet are closely related, I would say that JSP is in fact Servlet. First JSP pages get translated into servlet class when they get deployed. Second, the scriptlet which is Java code within JSP page ends up being directly inserted into the jspService() method of the resulting servlet class without any modification. Third, the implicit objects that are available to servlet programmers such as HttpSession object, ServletContext objects are also available to JSP page designers, JavaBeans developers, custom tag designers. Slide 25
greeting$jsp.java (1)
package org.apache.jsp; import javax.servlet.; import javax.servlet.http.; import javax.servlet.jsp.; import org.apache.jasper.runtime.;**
public class greeting$jsp extends HttpJspBase { static { } public greeting$jsp( ) { } private static boolean _jspx_inited = false;
public final void _jspx_init() throws org.apache.jasper.runtime.JspException { }
So this is the greeting.jsp's corresponding servlet class that was created by the container.
greeting$jsp.java (2)
public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException {
JspFactory _jspxFactory = null; PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; String _value = null;
This is continuation of translated code. Please note that there are variables that contain the references to servlet related objects such as pageContext object, HttpSession object, ServletContext object, ServletConfig object and output stream object.
Slide 27
greeting$jsp.java (3)
try {
if (_jspx_inited == false) { synchronized (this) { if (_jspx_inited == false) { _jspx_init(); _jspx_inited = true; } } } _jspxFactory = JspFactory.getDefaultFactory(); response.setContentType("text/html;charset=ISO-8859-1"); pageContext = _jspxFactory.getPageContext(this, request, response,"", true, 8192, true);
application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut();
And in this code, those variables are initialized.
Dynamic Content Generation Techniques in JSP
OK, by now I hope you got the sense on what the dynamic contents is and how it is generated. Now let's talk about the dynamic contents generation techniques in a bit more detail. Slide 31
Various techniques can be chosen depending on the following factors size and complexity of the project Requirements on re usability of code, maintainability, degree of robustness Simple to incrementally complex techniques are available
There are several dynamic contents generation techniques you can use. And you choose these techniques depending on the size and complexity of your project. And these techniques provide different levels of code reusability, maintainability, and robustness.