Professional Documents
Culture Documents
PROGRAMMING
UNIT III: SERVER SIDE
PROGRAMMING
• Servlet Architecture
• Servlet lifecycle
• Request and Response
• Being a Web Container
• Session management
• Overview of JSP
• JSP Elements
Introduction – request-response model
• Request-response model.
HTTP
Request
request
Server
<html>
<head>
<html>
<body>
<head>
…
<body>
…
Client
response
HTTP
HTML
Introduction – what is a request and response
Not a problem.
I can handle
dynamic
requests.
Helper
Application
Web Server machine
request
GET.
GET. GET.
….. ….. …..
request Servlet
Http request Web
Container
response
Thread
Web
Server
The CONTAINER
What is the role of Web Container ?
S2
• Communication Support
S1
• Lifecycle Management
• Security S3
• JSP Support
S4
• How does the Container know which Servlet the client has
requested for?
constructor()
destroy()
init()
Initialized
Service()
Servlet Lifecycle - Hierarchy
Interface Servlet
Client A Client B
Servlet
Thread Thread
A B
Request
Yes
Yes
Send Redirect
Send resource
Request Dispatcher Error page
Being a Web Container – Servlet Config and Context
Servlet Context
Attributes Parameters
Context Context
Types Request Request
Session Servlet Init
We cannot set Init
Method to set setAttribute(String, Object) parameters.
getInitParameter
Method to get getAttribute(String) (String)
Session Management – Session Tracking
ID# 42
“ale” “dark”
#42
Client A 1 HttpSession
request, “ale”, ID# 42
2
Container
Session Tracking – Cookies
HTTP/1.1 200 OK
Set-Cookie: JSESSIONID=0ABS
Content-Type: text/html
Client A Server: Apache-Coyote/1.1
<html>
…
</html>
Container
OK, here’s the HTTP Response
cookie with
my request
Cookie: JSESSIONID=0ABS
Accept: text/html……
Client A
HTTP Request Container
Session Tracking – URL Rewriting
URL ;jsessionid=1234567
Container
HTTP/1.1 200 OK
Content-Type: text/html
Server: Apache-Coyote/1.1
<html>
<body>
< a href =“ http:// www.sharmanj.com/Metavante;jsessionid=0AAB”>
click me </a>
Client A </html>
HTTP Response
GET /Metavante;jsessionid=0AAB
HTTP / 1.1
Host: www.sharmanj.com
Accept: text/html
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello simple servlet</b>");
out.print("</body></html>");
}
public void destroy(){System.out.println("servlet is destroyed");}
public ServletConfig getServletConfig(){return config;}
public String getServletInfo(){return "copyright 2007-1010";}
Life Cycle of Servlet
servlet
GenericServlet HttpServlet
init(ServletConfig);
doGet(HttpServletRequest,
service(ServletRequest,
HttpServletResponse);
ServletResponse);
doPost(HttpServletRequest,
HttpServletResponse);
destroy(); …….
HttpServletResponse Interface
• HttpServletResponse
– Object passed to doGet and doPost
– Extends ServletResponse
• Methods
– void addCookie( Cookie cookie )
• Add Cookie to header of response to client
– ServletOutputStream
getOutputStream()
• Gets byte-based output stream, send binary data to client
– PrintWriter getWriter()
• Gets character-based output stream, send text to client
– void setContentType( String type )
• Specify MIME type of the response (Multipurpose Internet Mail
Extensions)
• MIME type “text/html” indicates that response is HTML document.
• Helps display data
Handling HTTP GET Requests
• HTTP GET requests
– Usually gets content of specified URL
• Usually HTML document (web page)
• Example servlet
– Handles HTTP GET requests
– User clicks Get Page button in HTML document
• GET request sent to servlet HTTPGetServlet
– Servlet dynamically creates HTML document
displaying "Welcome to Servlets!"
Handling HTTP GET Requests
3 import javax.servlet.*;
4 import javax.servlet.http.*;
– Method doGet
• Responds to GET requests
• Default action: BAD_REQUEST error (file not found)
• Override for custom GET processing
• Arguments represent client request and server response
Handling HTTP GET Requests
14 response.setContentType( "text/html" ); // content type
– setContentType
• Specify content
12 •PrintWriter
text/html for HTML documents
output;
15 output = response.getWriter(); // get writer
– getWriter
• Returns PrintWriter object, can send text to client
• getOutputStream to send binary data (returns
ServletOutputStream object)
Handling HTTP GET Requests
19 buf.append( "<HTML><HEAD><TITLE>\n" );
20 buf.append( "A Simple Servlet Example\n" );
21 buf.append( "</TITLE></HEAD><BODY>\n" );
22 buf.append( "<H1>Welcome to Servlets!</H1>\n" );
23 buf.append( "</BODY></HTML>" );
24 output.println( buf.toString() );
25 – Lines 19-23 create HTML document
output.close(); // close PrintWriter stream
– ACTION
• localhost - your computer
• :8080 - port
14
• /servlet - directory
<INPUT TYPE="submit" VALUE="Get HTML Document">
– GUI component
• INPUT element
• TYPE - "submit" (button)
• VALUE - label
• When pressed, performs ACTION
• If parameters passed, separated by ? in URL
1 // Fig. 19.5: HTTPGetServlet.java
2 // Creating and sending a page to the client
3 import javax.servlet.*;
4 import javax.servlet.http.*; Import necessary classes and inherit
5 import java.io.*;
methods from HttpServlet.
6
7 public class HTTPGetServlet extends HttpServlet {
8 public void doGet( HttpServletRequest request,
9 HttpServletResponse response )
10 throws ServletException, IOException
11 {
12 PrintWriter output;
13
14 response.setContentType( "text/html" ); // content type
15 output = response.getWriter(); // get writer
16
1. import
17 // create and send HTML page to client
1.1 extends HttpServlet
Create PrintWriter object.
18 StringBuffer buf = new StringBuffer();
19 buf.append( "<HTML><HEAD><TITLE>\n"2. doGet
);
Create HTML file and send to
20 2.1 setContentType
buf.append( "A Simple Servlet Example\n" ); client.
21 2.2 getWriter
buf.append( "</TITLE></HEAD><BODY>\n" );
22 buf.append( "<H1>Welcome to Servlets!</H1>\n"
2.3 println );
23 buf.append( "</BODY></HTML>" );
24 output.println( buf.toString() );
25 output.close(); // close PrintWriter stream
26 }
27 }
1 <!-- Fig. 19.6: HTTPGetServlet.html -->
2 <HTML>
3 <HEAD>
4 <TITLE>
5 Servlet HTTP GET Example ACTION specifies form
6 </TITLE>
handler, METHOD specifies
7 </HEAD>
8 <BODY>
request type.
9 <FORM
10 ACTION="http://lab.cs.siu.edu:8080/rahimi/HTTPGetServlet"
11 METHOD="GET">
12 <P>Click the button to have the servlet send
13 an HTML document</P>
14 <INPUT TYPE="submit" VALUE="Get HTML Document">
15 </FORM>
16 </BODY> HTML document
performs ACTION
2. <FORM> when
2.2 METHOD
3. INPUT TYPE
Program Output
Handling HTTP POST Requests
• HTTP POST
– Used to post data to server-side form handler (i.e.
surveys)
– Both GET and POST can supply parameters
• Example servlet
– Survey
• Store results in file on server
– User selects radio button, presses Submit
• Browser sends POST request to servlet
– Servlet updates responses
• Displays cumulative results
Handling HTTP POST Requests
9 public class HTTPPostServlet extends HttpServlet {
– Extend HttpServlet
• Handle GET and POST
10 private String animalNames[] =
11 { "dog", "cat", "bird", "snake", "none" };
– doPost
• Responds to POST requests (default BAD_REQUEST)
• Same arguments as doGet (client request, server response)
18
Handling HTTP POST Requests
File f = new File( "survey.txt" );
23 ObjectInputStream input = new ObjectInputStream(
24 new FileInputStream( f ) );
26 animals = (int []) input.readObject();
40 – Open survey.txt,
String value = load animals array
41 request.getParameter( "animal" );
– Content type
67
Handling HTTP POST Requests
StringBuffer buf = new StringBuffer();
68 buf.append( "<html>\n" );
69 buf.append( "<title>Thank you!</title>\n" );
70 buf.append( "Thank you for participating.\n" );
71 buf.append( "<BR>Results:\n<PRE>" );
73 DecimalFormat twoDigits = new DecimalFormat( "#0.00" );
74 for ( int i = 0; i < percentages.length; ++i ) {
75 buf.append( "<BR>" );
76 buf.append( animalNames[ i ] );
88 responseOutput.println( buf.toString() );
– METHOD="POST"
– Radio buttons (only one may be selected)
• TYPE - radio
• NAME - parameter name
• VALUE - parameter value
• CHECKED - initially selected
8
Handling HTTP POST Requests
<FORM METHOD="POST" ACTION=
9 "http://lab.cs.siu.edu:8080/rahimi/HTTPPostServlet">
10 What is your favorite pet?<BR><BR>
11 <INPUT TYPE=radio NAME=animal VALUE=dog>Dog<BR>
12 <INPUT TYPE=radio NAME=animal VALUE=cat>Cat<BR>
13 <INPUT TYPE=radio NAME=animal VALUE=bird>Bird<BR>
14 <INPUT TYPE=radio NAME=animal VALUE=snake>Snake<BR>
15 <INPUT TYPE=radio NAME=animal VALUE=none CHECKED>None
16 <BR><BR><INPUT TYPE=submit VALUE="Submit">
17 <INPUT TYPE=reset>
18 </FORM>
– Method doPost
21
• Cookie
Get language selection
c = new Cookie( language, getISBN( language ) );
22 c.setMaxAge( 120 ); // seconds until cookie removed
– Cookie constructor
• Cookie ( name, value )
• getISBN is utility method
• setMaxAge( seconds ) - deleted when expire
Cookies
23 response.addCookie( c ); // must precede getWriter
46 Cookie cookies[];
48 cookies = request.getCookies(); // get client's cookies
– Method doGet
– getCookies
• Returns array of Cookies
57
Cookies
if ( cookies != null ) {
62 output.println(
63 cookies[ i ].getName() + " How to Program. " +
64 "ISBN#: " + cookies[ i ].getValue() + "<BR>" );
– Cookie methods
• getName, getValue
• Used to determine recommended book
• If cookie has expired, does not execute
1 // Fig. 19.9: CookieExample.java
2 // Using cookies. Allows class to handle
3 import javax.servlet.*;
GET and POST.
4 import javax.servlet.http.*;
5 import java.io.*;
6
7 public class CookieExample extends HttpServlet {
8 private String names[] = { "C", "C++", "Java",
9 "Visual Basic 6" };
10 private String isbn[] = {
11 "0-13-226119-7", "0-13-528910-6",
12 "0-13-012507-5", "0-13-528910-6" };
13
14 public void doPost( HttpServletRequest request,
15 Create a new Cookie,
HttpServletResponse response )
16 throws ServletException, IOException
initialized with language
1. import
17 {
18 PrintWriter output;
parameter.1.1 extends HttpServlet
2. doPost
19 String language = request.getParameter( "lang" );
2.1 getParameter
20
21 2.2 Cookie
Cookie c = new Cookie( language, getISBN( language ) );
22 c.setMaxAge( 120 ); // seconds until cookie removed
2.3 setMaxAge
24
25 response.setContentType( "text/html" ); Set maximum age of
26 output = response.getWriter(); cookie, add to header.
27
28 // send HTML page to client
29 output.println( "<HTML><HEAD><TITLE>" );
30 output.println( "Cookies" );
31 output.println( "</TITLE></HEAD><BODY>" );
32 output.println( "<P>Welcome to Cookies!<BR>" );
33 output.println( "<P>" );
34 output.println( language );
35 output.println( " is a great language." );
36 output.println( "</BODY></HTML>" );
37
38 output.close(); // close stream
39 }
40
41 public void doGet( HttpServletRequest request,
42 HttpServletResponse response )
43 throws ServletException, IOException
44 {
45 PrintWriter output; Returns array of
46 Cookie cookies[]; Cookies.
47
48
3. doGet
cookies = request.getCookies(); // get client's cookies
49
50 response.setContentType( "text/html" );
51
52
3.1 getCookies
output = response.getWriter();
53 output.println( "<HTML><HEAD><TITLE>" );
54 output.println( "Cookies II" );
55 output.println( "</TITLE></HEAD><BODY>" );
56
57 if ( cookies != null ) {
58 output.println( "<H1>Recommendations</H1>" );
59
60 // get the name of each cookie
61 for ( int i = 0; i < cookies.length; i++ )
62 output.println(
63 cookies[ i ].getName() + " How to Program. " +
64 "ISBN#: " + cookies[ i ].getValue() + "<BR>" );
65 }
66 else {
67 output.println( "<H1>No Recommendations</H1>" Use
); cookies to determine
68 output.println( "You did not select a languagerecommended
or" ); book and
69 output.println( "the cookies have expired." );ISBN.
70 }
71
72 output.println( "</BODY></HTML>" ); If cookies have expired,
73 output.close(); // close stream no recommendations.
74 }
75
76
3.2 getName, getValue
private String getISBN( String lang )
77 {
78 for ( int i = 0; i < names.length; ++i )
79 4. Method getISBN
if ( lang.equals( names[ i ] ) )
80 return isbn[ i ];
81
82 return ""; // no matching string found
83 }
84 }
1 <!-- Fig. 19.10: SelectLanguage.html -->
2 <HTML>
3 <HEAD>
4 <TITLE>Cookies</TITLE>
5 </HEAD>
6 <BODY>
7 <FORM ACTION="http://lab.cs.siu.edu:8080/rahimi/CookieExample"
8 METHOD="POST">
9 <STRONG>Select a programming language:<br>
10 </STRONG><BR>
11 <PRE>
12 <INPUT TYPE="radio" NAME="lang" VALUE="C">C<BR>
13 <INPUT TYPE="radio" NAME="lang" VALUE="C++">C++<BR>
14 <INPUT TYPE="radio" NAME="lang" VALUE="Java"
15 CHECKED>Java<BR> HTML file
16 <INPUT TYPE="radio" NAME="lang"
17 1. POST
VALUE="Visual Basic 6">Visual Basic 6
18 </PRE>
19 <INPUT TYPE="submit" VALUE="Submit">
2. Radio buttons
20 <INPUT TYPE="reset"> </P>
21 </FORM>
22 </BODY>
23 </HTML>
1 <!-- Fig. 19.11: BookRecommendation.html -->
2 <HTML>
3 <HEAD>
4 <TITLE>Cookies</TITLE>
5 </HEAD>
6 <BODY>
7 <FORM ACTION="http://lab.cs.siu.edu:8080/rahimi/CookieExample"
8 METHOD="GET">
9 Press "Recommend books" for a list of books.
10 <INPUT TYPE=submit VALUE="Recommend books">
11 </FORM>
12 </BODY>
13 </HTML>
HTML file
1. GET
2. Submit
Program Output
Session Tracking with HttpSession
• HttpSession (javax.servlet.http)
– Alternative to cookies
– Data available until browsing ends
• Methods
–23Creation
HttpSession session = request.getSession( true );
– getSession( createNew )
• Class HttpServletRequest
• Returns client's previous HttpSession object
• createNew - if true, creates new HttpSession object
if does not exist
Session Tracking with HttpSession
26 session.putValue( language, getISBN( language ) );
– getValueNames()
• Returns array of Strings with names
– getValue( name )
• Returns value of name as an Object
• Cast to proper type
Session Tracking with HttpSession
• Redo previous example
– Use HttpSession instead of cookies
– Use same HTML files as before
• Change ACTION URL to new servlet
1 // Fig. 19.13: SessionExample.java
2 // Using sessions.
3 import javax.servlet.*;
4 import javax.servlet.http.*;
5 import java.io.*;
6
7 public class SessionExample extends HttpServlet {
8 private final static String names[] =
9 { "C", "C++", "Java", "Visual Basic 6" };
10 private final static String isbn[] = {
11 "0-13-226119-7", "0-13-528910-6",
12 "0-13-012507-5", "0-13-528910-6" };
13
14 public void doPost( HttpServletRequest request,
15 HttpServletResponse response )
16 throws ServletException, IOException
17 { 1. import
18 PrintWriter output;
19 2. doPost
String language = request.getParameter( "lang" ); Load HttpSession
20 if exists, create if does
2.1 getSession
21 // Get the user's session object. not.
22 // Create a session (true) if one
2.2 does not exist.
putValue
23 HttpSession session = request.getSession( true );
24 Set name/value
25 // add a value for user's choice to session pair.
26 session.putValue( language, getISBN( language ) );
27
28 response.setContentType( "text/html" );
29 output = response.getWriter();
30
31 // send HTML page to client
32 output.println( "<HTML><HEAD><TITLE>" );
33 output.println( "Sessions" );
34 output.println( "</TITLE></HEAD><BODY>" );
35 output.println( "<P>Welcome to Sessions!<BR>" );
36 output.println( "<P>" );
37 output.println( language );
38 output.println( " is a great language." );
39 output.println( "</BODY></HTML>" );
40
41 output.close(); // close stream
42 }
43
44 public void doGet( HttpServletRequest request,
45 HttpServletResponse response )
46 throws ServletException, IOException
Do not create object if does
47
48
{
PrintWriter output;
3. doGet not exist. session set to
49 null.
50 // Get the user's session object.
51
52
3.1 getSession
// Don't create a session (false) if one does not exist.
HttpSession session = request.getSession( false );
53
110
Servlets & JSPs
Java Server Pages (JSP)
Agenda
• Introduction
• JSP Elements
• Implicit Objects
• Tag Libraries
• JSP Actions
• Error Handling
• Demo
111
Introduction – What is JSP
(business logic)
request servlet
Business Tier
Container
Helper
Objects
JSP
(presentation logic)
response
112
Introduction – JSP v/s Servlet
Servlets JSP
114
Introduction – Comments
• JSP Comments
<%-- {CODE HERE} --%>
Does not show the comments on the page
Does not show the comments in page source
Can only be used outside JSP Elements
• HTML Comments
<!– {CODE HERE} -->
Does not show the comments on the page
Shows the comments in page source
Can only be used outside JSP Elements
116
JSP Elements - Declarations
• Example
<%! int instanceVar = 10; %>
117
JSP Elements - Declarations
Request 1
Request 2
Declarations
Request 3
118
JSP Elements - Scriptlets
• Example
<% int localVar = 10; %>
119
JSP Elements - Expressions
• Example
<%= localVar %>
120
JSP Elements - Example
<% Scriptlets
String name = "Sharad";
userCnt++;
%> Expressions
<table>
<tr><td>
Welcome <%=name%>. You are user number <%=userCnt%>
</td></tr>
</table>
</body>
</html>
121
JSP Elements - Directives
Example
<%@ page import=“java.util.ArrayList” %>
122
Directives – page directive
• Any number of the pre-defined attributes can be added to the page directive
123
Directives – include directive
header.jsp
Main page
<%@ include file =“footer.jsp"/>
<table><tr>
<td>Contact Details</td>
<tr></table>
main.jsp footer.jsp
124
Directives – taglib directive
taglib directive
Used in JSPs to use the tag handler functionality
125
taglib directive – high-level overview
<tag>
<name>txtBox</name>
<%@ taglib uri=“sharmanjTags” prefix=“sharmanj” %> <tagclass>TxtBoxTag</tagclass>
….. <bodycontent>EMPTY</bodycontent>
< sharmanj:txtBox length=“10“ name=“userName”/> <attribute>
….. <name>name</name>
<required>true</required>
test.jsp ….
</attribute>
…
</tag>
sharmanj-taglib.tld
<web-app>
<taglib>
<taglib-uri>sharmanjTags</taglib-uri> public class TxtBoxTag extends TagSupport {
<taglib-location> public int doStartTag() {
sharmanj-taglib.tld ….
</taglib-location> }
</taglib> }
</web-app>
TxtBoxTag.java
web.xml
126
Implicit Objects - Introduction
– out: JspWriter
– request: HttpRequest
– response: HttpResponse
– session: HttpSession
– config: ServletConfig
– application: ServletContex
– page: JSP page
– pageContext: Special object
127
Implicit Objects - Example
<html>
<head>
<title>JSP Implicit objects Example</title>
</head>
<body>
<%
if (“YES”.equals(request.getAttribute(“SCOPE”))) {
out.println(“REQUEST”);
} else {
if (“YES”.equals(session.getAttribute(“SCOPE”))) {
out.println(“SESSION”);
} else {
out.println(“NONE”);
}
}
%>
</body>
</html>
128
Implicit Objects – out
• An instance of JspWriter
129
Implicit Objects – request
• Instance of HttpServletRequest
• Use the attributes stored in request object for display /basic
validations in JSP
a = 10
Helper
Uses helper Object
object
(a = 10)
130
Implicit Objects – response
• Instance of HttpServletResponse
• Send the response back to the client (HTML in most of the
cases)
JSP1
response.sendRedirect(“url”);
131
Implicit Objects – session
• Instance of HttpSession
• Retrieve and set the session attributes in JSP
• Remember the client across multiple requests
Request 1
Response1
Response2
SESSION
132
Implicit Objects – config and application
133
Servlet Config Servlet Config Servlet Config Servlet Config
Implicit Objects – page
Hello <%=userName%>
<jsp:include page=“/header.jsp"/>
header.jsp
Main page
<table><tr>
<td>Contact Details</td>
<tr></table>
<jsp:include page=“/footer.jsp"/>
footer.jsp
main.jsp
134
Implicit Objects – pageContext
application
session
pageContext
request
page
135
JSP Actions
<jsp:include>
<jsp:forward>
<jsp:param>
<jsp:useBean>
<jsp:getProperty>
<jsp:setProperty>
136
JSP Actions - <jsp:include>
Definition:
Includes a page at the given location in the main page
Syntax:
137
JSP Actions – Include Action v/s Include Directive
138
JSP Actions - <jsp:forward>
Definition:
Forwards the request to the given page
Syntax:
139
JSP Actions - <jsp:param>
Definition:
Pass parameters to the included/forwarded page
Syntax:
140
JSP Actions - <jsp:useBean>
getId();
setId(..)
getName()
How can I use
setName(…)
that bean?
bean
Servlet JSP
141
JSP Actions - <jsp:useBean>
Definition:
Instantiate a bean class, use bean properties, and set property values
Syntax:
<jsp:useBean id=“{beanInstanceName}"
scope="page|request|session|application"
class=“{package.class}"
type=“{package.class}"
beanName=" {package.beanName}”>
</ jsp:useBean>
Definition:
Gets property values of a Bean
Syntax:
<jsp:getProperty name=“{beanInstanceName}"
property= “{propertyName}">
143
JSP Actions - <jsp:setProperty>
Definition:
Sets property values in a Bean
Syntax:
<jsp:setProperty name=“{beanInstanceName}"
property= "*" | property="propertyName"
param=“{parameterName}"
value="{paramValue}" } />
144
JSP Actions – useBean
<jsp:useBean id=“userBean"
scope="session“
class=“com.sharmanj.UserBean" >
<jsp:setProperty name=“userBean”
property=“userName”
value=“Sharad”/>
</ jsp:useBean>
145
Error Handling – Types of errors
• Errors in HTML
147
Error Handling – Error page
148
Error Handling
• Specify error page in your main page • Specify error page in web.xml
<%@page errorPage=“errPage.jsp" %> <web-app>
<html> …………….
<head> ……………
<title>This is the main page</title>
</head> <error-page>
<body> <exception-type>com.a.myExp</exception-type>
………………….. <location>/error.jsp</location>
………………….. </error-page>
…………………… <error-page>
…………………… <error-code>404</error-code>
<location>/errorServlet</location>
// ERROR CODE GOES HERE </error-page>
………………….
…………………. ………………..
</body> ……………….
</html> </web-app>
149
JSP Overview - Servlets v/s JSPs
import javax.servlet.HttpServlet.*
<%@ page import=“foo.*” %>
import foo.*;
public class MyJsp_jsp extends
<html>
HttpServlet
<body>
{
int count = 0;
<% int i = 10; %>
public void display()
<%! int count = 0; %>
{
out.println(“Hello”);
Hello! Welcome
}
public void _jspService(req, res)
<%! Public void display()
{
{
int i = 0;
out.println(“Hello”);
out.println(“<html>\r<body>”);
} %>
out.println(“Hello! Welcome”);
}
</body>
}
</html>
JSP Overview - What is a JSP
153