0% found this document useful (0 votes)
69 views44 pages

Web Components: Technology Consulting

The document discusses servlets and Java Server Pages (JSP) technology. It covers what servlets are, the servlet class hierarchy, the servlet lifecycle, and using sessions and filters with servlets. It then discusses JSP technology, how JSP pages work, and JSP elements like directives, actions, and scripting elements.

Uploaded by

sandhu554
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views44 pages

Web Components: Technology Consulting

The document discusses servlets and Java Server Pages (JSP) technology. It covers what servlets are, the servlet class hierarchy, the servlet lifecycle, and using sessions and filters with servlets. It then discusses JSP technology, how JSP pages work, and JSP elements like directives, actions, and scripting elements.

Uploaded by

sandhu554
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 44

Web Components

Technology Consulting
Pramati Technologies
Agenda
• Servlets
• Java Server Pages (JSP)
• Tags and Tag Libraries
What’s a Servlet?
• Java’s answer to CGI programming
• Program runs on Web server and builds pages on the fly
• When would you use servlets?
– Page is based on user-submitted data e.g search engines
– Data changes frequently e.g. weather-reports
– Page uses information from databases e.g. on-line stores
Servlet Class Hierarchy
• javax.servlet.Servlet
– Defines methods that all servlets must implement
• init()
• service()
• destroy()

• javax.servlet.GenericServlet
– Defines a generic, protocol-independent servlet
• javax.servlet.http.HttpServlet
– To write an HTTP servlet for use on the Web
• doGet()
• doPost()
Servlet Class Hierarchy…
• javax.servlet.ServletConfig
– A servlet configuration object
– Passes information to a servlet during initialization
• Servlet.getServletConfig()

• javax.servlet.ServletContext
– To communicate with the servlet container
– Contained within the ServletConfig object
• ServletConfig.getServletContext()

• javax.servlet.ServletRequest
– Provides client request information to a servlet
• javax.servlet.ServletResponse
– Sending a response to the client
Basic Servlet Structure
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SomeServlet extends HttpServlet {


// Handle get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// request – access incoming HTTP headers and HTML form data
// response - specify the HTTP response line and headers
// (e.g. specifying the content type, setting cookies).
PrintWriter out = response.getWriter(); //out - send content to browser
}
}
A Simple Servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello World");
}
}
Servlet Life Cycle
• Loading and Instantiation
• Initialization
• Request Handling
• End of Service
Role of the Container
HelloServlet
2. Load and
Instantiate

1. Request
HelloServlet
3.
init(ServletConfig)
4.
Client Servlet Engine Initialization

6. Response

5. service(ServletRequest,
ServletResponse) Initialized
HelloServlet
Another Simple Servlet
public class HelloWWW extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
 response.setContentType("text/html");
PrintWriter out = response.getWriter();
 out.println("<HTML>\n" +
"<HEAD><TITLE>HelloWWW</TITLE></HEAD>\n" +
"<BODY>\n" + "<H1>Hello WWW</H1>\n" +
"</BODY></HTML>");
}
}
Form Example
HTML Post Form
<FORM ACTION=“/servlet/hall.ThreeParams”
METHOD=“POST”>
First Parameter: <INPUT TYPE="TEXT" NAME="param1"><BR>
Second Parameter: <INPUT TYPE="TEXT" NAME="param2"><BR>
Third Parameter: <INPUT TYPE="TEXT" NAME="param3"><BR>
<CENTER>
<INPUT TYPE="SUBMIT">
</CENTER>
</FORM>
Reading Parameters
public class ThreeParams extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(… +"<UL>\n" +
"<LI>param1: " + request.getParameter("param1") + "\n" +
"<LI>param2: " + request.getParameter("param2") + "\n" +
"<LI>param3: " + request.getParameter("param3") + "\n" +
"</UL>\n" + …);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request, response);
}
}
Servlet Output
Reading All Params
• Enumeration paramNames = request.getParameterNames();
– parameter names in unspecified order

• String[] paramVals =
request.getParameterValues(paramName);
– Array of param values associated with paramName
Session Tracking
• Typical scenario – shopping cart in online store
• Necessary because HTTP is a "stateless" protocol
• Session Tracking API allows you to
– look up session object associated with current request
– create a new session object when necessary
– look up information associated with a session
– store information in a session
– discard completed or abandoned sessions
Session Tracking API - I
• Looking up a session object
– HttpSession session = request.getSession(true);

– Pass true to create a new session if one does not exist

• Associating information with session


– session.setAttribute(“user”,request.getParameter(“name”))

– Session attributes can be of any type

• Looking up session information


– String name = (String) session.getAttribute(“user”)
Session Tracking API - II
• getId
– the unique identifier generated for the session
• isNew
– true if the client (browser) has never seen the session
• getCreationTime
– time in milliseconds since session was made
• getLastAccessedTime
– time in milliseconds since the session was last sent from client
• getMaxInactiveInterval
– # of seconds session should go without access before being invalidated
– negative value indicates that session should never timeout
Filters
• Code that can transform the content of HTTP requests, responses, and header
information
• Implement javax.servlet.Filter
• Example filters
– Authentication filters
– Logging and auditing filters
– Image conversion filters
– Data compression filters
– Encryption filters
– Tokenizing filters
– Filters that trigger resource access events
– XSL/T filters that transform XML content
– Caching filters
Summary
• What is a Servlet
• Class Hierarchy
• Life Cycle
• Managing Sessions
• Filters
Java Server Pages (JSP)
Why JSP Technology?
• Servlets are good at running logic
– Not so good at producing large amounts of output
– out.write() is ugly

• JSP pages are great at producing lots of


textual output
– Not so good at lots of logic
– <% %> is ugly
How does it Work
• “JSP page”
– Mixture of text, Script and directives
– Text could be text/ html, text/ xml or text/ plain
• “JSP engine”
– ‘Compiles’ page to servlet
– Executes servlet’s service() method
• Sends text back to caller
• Page is
– Compiled once
– Executed many times
A Simple JSP Page
Producing Output
• Any text on a page is written automatically
<book name= 'JSP' />
– Produces
out. write("< book name= 'JSP' />");
• Scriptlets can use ‘out’ intrinsic directly
<% out. write(" Homer Rules"); %>
• Can also use expressions to produce text output
<value> value is <%= b. getValue() %></ value>
– Produces
out. print("< value> value is " + b. getValue() + "</ value>")
Anatomy of a JSP
<%@ page language=“java” contentType=“text/html” %>
<html>
<body bgcolor=“white”>
<jsp:useBean id=“greeting” class=“com.pramati.jsp.beans.GreetingBean”>
<jsp:setProperty name=“greeting” property=“*”/>
</jsp:userBean>

The following information was saved:


User Name:

<jsp:getProperty name=“greeting” property=“userName”/>

Welcome!
</body>
</html>
Role of the Container
Hello.jsp
2. Read

Translation
phase
1. Request
Hello.jsp
HelloServlet.java
Server with
Client JSP Container 3. Generate
6. Response
4. Compile

5. Execute

Request
HelloServlet.class
Processing
phase
JSP Elements
• Directive Elements
– Info about the page
– Remains same between requests
– E.g., scripting language used

• Action Elements
– Take action based on info required at request-time
• Standard
• Custom (Tags and Tag Libraries)

• Scripting Elements
– Add pieces of code to generate output based on conditions
Directives
• Global information used by the “JSP engine”
• Of form <%@ directive attr_ list %>
• Or <jsp: directive. directive attr_ list />
– Directive could be
• Page
• Include
• Taglib
– E. g.,
• <%@ page info=“ written by DevelopMentor” %>
• <jsp: directive. page import=“ java. sql.*” />
• <%@ include file=“\ somefile. txt” %>
• <%@ taglib uri= tags prefix=“ foo” %>
Actions Within a JSP Page
• Specifies an action to be carried out by the “JSP engine”
• Standard or custom
– Standard must be implemented by all engines
– Custom defined in tag libraries
• Standard actions ‘scoped’ by ‘jsp’ namespace
• Have name and attributes
<jsp: useBean id=“ clock” class=“ java.util.Date” />
<ul> The current date at the server is:
<li> Date: <jsp: getProperty name=“clock” property=“date” />
<li> Month: <jsp: getProperty name=“clock” property=“month” />
</ul>
Standard JSP Actions
• jsp:useBean
• jsp:getProperty
• jsp:setProperty
• jsp:include
• jsp:forward
• jsp:param
• jsp:plugin
Scriptlets
• Of form <% /* code goes here*/ %>
– Gets copied into _ jspService method of generated servlet

• Any valid Java code can go here

CODE: OUTPUT:
<% int j; %> <value> 0</ value>
<% for (j = 0; j < 3; j++) {%> <value> 1</ value>
<value> <value> 2</ value>
<% out. write(""+ j); %>
</ value><% } %>
Declarations (<%! … %>)
• Used to declare class scope variables or methods
<%! int j = 0; %>
• Gets declared at class- level scope in the generated servlet

public class SomeJSP extends HttpServlet implements HttpJspPage {



int j = 0;
void _jspService(…) {}
}
JSP to Servlet Translation
<%@ page import="javax.ejb.*,javax.naming.*,java.rmi.* ,java.util.*" %>
<HTML><HEAD><TITLE>Hello.jsp</TITLE></HEAD><BODY>
<% String checking = null;
String name = null;
checking = request.getParameter("catch");
if (checking != null) {
name = request.getParameter("name");%>
<b> Hello <%=name%>
<% } %>
<FORM METHOD='POST' action="Hello.jsp">
<table width="500" cellspacing="0" cellpadding="3" border="0">
<caption>Enter your name</caption>
<tr><td><b>Name</b></td><td><INPUT size="20" maxlength="20" TYPE="text" NAME="name"></td></tr>
</table>
<INPUT TYPE='SUBMIT' NAME='Submit' VALUE='Submit'>
<INPUT TYPE='hidden' NAME='catch' VALUE='yes'>
</FORM></BODY></HTML>
Generated Servlet…
public void _jspService(HttpServletRequest request ,
HttpServletResponse response)
throws ServletException ,IOException {
out.write("<HTML><HEAD><TITLE>Hello.jsp</TITLE></HEAD><BODY>" );
String checking = null;
String name = null;
checking = request.getParameter("catch");
if (checking != null) {
name = request.getParameter("name");
out.write("\r\n\t\t<b> Hello " );
out.print(name);
out.write("\r\n\t\t" );
}
out.write("\r\n\t\t<FORM METHOD='POST' action="
+"\"Hello.jsp\">\r\n\t\t\t<table width=\"500\" cell“……………………………..
}
}
Tags & Tag Libraries
What Is a Tag Library?
• JSP technology has a set of pre- defined tags
– <jsp: useBean …/>
• These are HTML like but…
• … have limited functionality
• Can define new tags
– Look like HTML
– Can be used by page authors
– “Java code” is executed when tag is encountered
– Allow us to keep Java code off the page
• Better separation of content and logic
May Have Tags To…
• Process an SQL command
• Parse XML and output HTML
• Automatically call into an “EJB component” (EJB ™
technology- based component)
• Get called on every request to initialize script variables
• Iterate over a ResultSet and display the output in an HTML
table
Primary Tag Classes (javax.servlet.jsp.tagext.Tag)

implements
Tag TagSupport
Interface class

extends extends

implements
BodyTag BodyTagSupport
Interface class
Simple Tag Example
<%@
<%@ taglib
taglib uri=“/WEB-INF/mylib.tld”
uri=“/WEB-INF/mylib.tld” prefix=“test”
prefix=“test” %>
%>
<html><body
<html><body bgcolor=“white”>
bgcolor=“white”>
<test:hello
<test:hello name=“Robert”
name=“Robert” />
/>
</body>
</body> </html>
</html>

public class HelloTag extends TagSupport {


private String name = “World”;
public void setName(String name) { this.name = name; }
public int doEndTag() { pageContext.getOut().println(“Hello “ + name); }
}

mylib.tld
<taglib> ……
<tag><name>hello</name>
<tagclass>com.pramati.HelloTag</tagclass>
<bodycontent>empty</bodycontent>
<attribute><name>name</name></attribute>
</tag>
</taglib>
How Tag Handler methods are
invoked
<prefix:tagName
attr1=“value1” ------------ setAttr1(“value1”)
attr2=“value2” ------------ setAttr2(“value2”)
> ------------ doStartTag()
This tags's body
</ prefix:tagName>------------ doEndTag()

• Implementation of JSP page will use the tag handler for


each ‘action’ on page
Summary
• The JSP specification is a powerful system for creating
structured web content
• JSP technology allows non- programmers to develop
dynamic web pages
• JSP technology allows collaboration between programmers
and page designers when building web applications
• JSP technology uses the Java programming language as the
script language
• The generated servlet can be managed by directives
Summary
• JSP components can be used as the view in the
MVC architecture
• Authors using JSP technology are not necessarily
programmers using Java technology
• Want to keep “Java code” off a “JSP Page”
• Custom actions (tag libraries) allow the use of
elements as a replacement for Java code
Thank You

You might also like