Server-Side Programming Guide
Server-Side Programming Guide
SERVER-SIDE PROGRAMMING
Server-Side Programming means that writing scripts that are executed on
the server and are then translated into HyperText Markup Language (HTML)
which can be viewed by all web browsers.
1
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
3.2: Servlets
Servlets are Java programs that run on a web server and act as a middle
layer between a requests coming from a web browser or other HTTP client
and databases or applications on the server.
Using servlets,
We can collect input from users through web page forms, present
records from a databases (or) another source and create web pages
dynamically.
We can develop sites with secure access, interact with DB, and
maintain unique session info of each client.
1. Static Response: HTML document retrieved from the file system and
returned to the client is called static response.
2. Dynamic Response: HTML document is generated by a program in
response to an HTTP request.
2
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
3
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
1. Client
In this architecture, the web browser acts as a Client. Client or user
connected with a web browser. The client is responsible for sending requests
or HttpRequest to web server and processing responses received by the Web
server.
2. Web Server
Web server controls how web user access hosted files and it is responsible
for processing user request and responses. Here server is a software that
understand URLs and HTTP protocol. Whenever browser needs to request
file on the webserver, it process client request using HTTP request, if it finds
requested file sends it back to browser through HTTP Response. There are
two types’ web servers Static and Dynamic webservers.in static web server
sends the file as it is but in dynamic webserver hosted file is updated before
it is sent to the browser.
3. Web Container
Web container is the component in the webserver it interacts with Java
servlets. A web container is responsible for managing the lifecycle of servlets
and it also performs the URL mapping task. Web container handles the
requests of servlets, JSP and other files at the server-side. The important
tasks performed by servlets are loading and unloading servlets, creating and
managing requests and response objects and performs the overall tsk of
servlet management.
Following are the steps how servlet request has been processed consider the
above diagram.
The client sends a request.
Web Server accepts the request and forwards it to the web container.
Web container searches web.xml file for request URL pattern and gets
the address of the servlet.
4
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
Advantages
Below are some important advantages of the servlet as follows:
Servlets are server independent, as they are compatible with any web
server. Compared to other server-side web technologies like ASP and
JavaScript these are server-specific.
Servlets are protocol-independent i.e. it supports FTP, SMTP, etc.
Mainly it provides extended support to HTTP protocol functionality.
5
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
Disadvantages
Designing a servlet can be pretty laborious.
Exceptions need to be handled while designing a servlet since they are
not thread-safe.
Developers may need additional skills to program a servlet.
A servlet life cycle can be defined as the entire process from its
creation till the destruction.
1) init()
2) service()
3) destroy()
6
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
This method is called when the servlet is first created. It is called only once
during its lifecycle and not called again for each user request. So, it is used
for one-time initializations, just as with the init method of applets.
When a user invokes a servlet, a single instance of each servlet gets created,
with each user request resulting in a new thread that is handed off to doGet
or doPost as appropriate. The init() method simply creates or loads some
data that will be used throughout the life of the servlet.
7
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
The service() method is the main method to perform the actual task. The
servlet container (i.e. web server) calls the service() method to handle
requests coming from the client( browsers) and to write the formatted
response back to the client.
Each time the server receives a request for a servlet, the server spawns a
new thread and calls service. The service() method checks the HTTP request
type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut,
doDelete, etc. methods as appropriate.
The service () method is called by the container and service method invokes
doGe, doPost, doPut, doDelete, etc. methods as appropriate. So you have
nothing to do with service() method but you override either doGet() or
doPost() depending on what type of request you receive from the cl ient.
The doGet() and doPost() are most frequently used methods with in each
service request. Here are the signature of these two methods.
A GET request results from a normal request for a URL or from an HTML
form that has no METHOD specified and it should be handled by doGet()
method.
8
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
A POST request results from an HTML form that specifically lists POST as
the METHOD and it should be handled by doPost() method.
The destroy() method is called only once at the end of the life cycle of a
servlet. This method gives your servlet a chance to close database
connections, halt background threads, write cookie lists or hit counts to
disk, and perform other such cleanup activities.
After the destroy() method is called, the servlet object is marked for garbage
collection. The destroy method definition looks like this:
9
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
out.println("<html>");
out.println("</html>");
}catch(Exception e){}
}
}
}
Servlets - Examples
Servlets are Java classes which service HTTP requests and implement the
javax.servlet.Servlet interface.
Web application developers typically write servlets that extend
javax.servlet.http.HttpServlet, an abstract class that implements the Servlet
interface and is specially designed to handle HTTP requests.
10
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
{
// Set response content type
response.setContentType("text/html");
Output:
Finally type http://localhost:8080/HelloWorld in browser's address box. If
everything goes fine, you would get following result:
Servlet has methods to access data contained in HTTP Request (URL) sent to
the server from the browser.
The Query String portion of the HTTP request is so called parameter
data.
For example,
http://www.example.com/servlet/PrintThis?name=Raj&color=Red
where,
the portion after the ? is called a query string.
11
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
The following methods are used to process these parameter data in servlets.
The following program explains how to process these parameter names and
values as well as path of the resource using servlet.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class NewServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
response.setContentType("text/html”);
PrintWriter out = response.getWriter();
try {
12
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet NewServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("Servlet file NewServlet is at: " + request.getContextPath());
Enumeration para1=request.getParameterNames();
while(para1.hasMoreElements())
{
out.println("Parameter name:"+para1.nextElement());
}
String name = request.getParameter("name");
String id = request.getParameter("id");
out.println("Name:" + name);
out.println("Id:" + id);
out.println("</body>");
out.println("</html>");
}catch(Exception e){}
}
}
}
13
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
Output:
The method attribute specifies how to send form-data (the form-data is sent
to the page specified in the action attribute).
The form-data can be sent as URL variables (with method="get") or as HTTP
post transaction (with method="post").
Notes on GET:
It is used to process the query string which is part of URL
Appends form-data into the URL in name/value pairs
The length of a URL is limited (about 3000 characters)
It is recommended when parameter data is not stored but used only to
request information.
Never use GET to send sensitive data! (will be visible in the URL)
Useful for form submissions where a user wants to bookmark the
result
GET is better for non-secure data, like query strings in Google
Notes on POST:
It is used to process the query string as well as to store the data on
server.
Appends form-data inside the body of the HTTP request (data is not
shown in URL)
Has no size limitations.
It is recommended if parameter data is intended to cause the server to
update stored data
14
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
Most browsers will warn you if they are about to resubmit POST data
to avoid duplicate updates
Form submissions with POST cannot be bookmarked
BASIS FOR
GET POST
COMPARISON
Example:
The following program explains how to send the data to server from a web
page and the same how to receive it from the server.
<html>
<head>
</head>
15
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
<body>
<pre>
<form action="NewServlet" method="post">
First Name: <input type="text" name="t1" />
Last Name: <input type="text" name="t2" />
Age: <input type="text" name="t3" />
E-mail:<input type="text" name="t4" />
<input type="submit" value="Submit" />
<form>
</pre>
</body>
</html>
Servlet for processing the data coming from this web page
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class NewServlet extends HttpServlet
{
public void goPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet NewServlet</title>");
out.println("</head>");
out.println("<body>");
String s1 = request.getParameter("t1");
String s2 = request.getParameter("t2");
String s3 = request.getParameter("t3");
String s4 = request.getParameter("t4");
out.println("First Name:" + s1);
out.println("Last Name:" + s2);
16
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
out.println("Age:" + s3);
out.println("E-mail:" + s4);
out.println("</body>");
out.println("</html>");
} catch(Exception e) {}
}
}
Output
Login.html
<html>
<body>
<form action="login" method="get">
<table>
<tr>
<td>User</td>
<td><input name="user" /></td>
</tr>
<tr>
<td>password</td>
<td><input name="password" /></td>
</tr>
</table>
<input type="submit" />
</form>
</body>
</html>
17
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
create a Servlet which receives the request in /login , which is the indicated
direction in the action attribute of the tag <form> of login.html
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet
{
protected void doGet(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException
{
String user = req.getParameter("user");
String pass = req.getParameter("password");
if ("balamurugan".equals(user) && "bala1234".equals(pass))
{
response(resp, "login ok");
}
else
{
response(resp, "invalid login");
}
}
private void response(HttpServletResponse resp, String msg)
throws IOException
{
PrintWriter out = resp.getWriter();
out.println("<html><body>");
out.println(msg);
out.println("</body></html>");
}
}
We compilate this Servlet and we include LoginServlet.class in the folder
/WEB-INF/classes. We modify web.xml to link /login with this Servlet.
web.xml
<web-app>
18
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class> hello </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login-servlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
We restart the server, open the page login.html, write an "x" in user, write
an "x" in password and click on the submit button.
19
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
<html>
<body>
<form action="login" method="post">
<table>
<tr><td>User</td> <td><input name="user" /></td></tr>
<tr><td>password</td> <td><input name="password" /></td></tr>
</table>
<input type="submit" />
</form>
</body>
</html>
import java.io.*;
import javax.servlet.*;
20
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet
{
protected void doPost(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException
{
String user = req.getParameter("user");
String pass = req.getParameter("password");
if ("balamurugan".equals(user) && "bala1234".equals(pass))
{
response(resp, "login ok");
}
else
{
response(resp, "invalid login");
}
}
private void response(HttpServletResponse resp, String msg)
throws IOException
{
PrintWriter out = resp.getWriter();
out.println("<html><body>");
out.println(msg);
out.println("</body></html>");
}
}
21
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
22
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
1) Cookies
2) URL Rewriting
3) Hidden Form Field
4) HttpSession
1. Cookies
23
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
(ii) The server then replies in the form of HTTP response, session id is
given in the form of cookie.
Types of Cookie
There are 2 types of cookies in servlets.
1. Non-persistent cookie
2. Persistent cookie
1. Non-persistent cookie
It is valid for single session only. It is removed each time when user closes
the browser.
2. Persistent cookie
It is valid for multiple session. It is not removed each time when user closes
the browser. It is removed only if user logout or sign out.
24
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
Advantage of Cookie
Simplest technique of maintaining the state.
Cookie are maintained at client side so they do not give any burden to
server.
All server side technology and all web server, application servers
support cookies.
Presistent cookies can remember client data during session and after
session with expiry time.
Limitation of Coockie
It will not work if cookie is disabled from the browser.
Cookies are text files, It does not provides security. Anyone can change
this file.
With cookies need client support that means if client disable the
coockies then it does not store the client location.
Cookies cannot store java objects as values, they only store text or
string.
25
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
Each time when web browser sends request back, then session_id value
can be used to keep track of the different web browsers.
This could be an effective way of keeping track of the session but clicking
on a regular (<a href=….>) hypertext link does not result in a form
submission, so hidden form fields also cannot support general session
tracking.
Hidden Form Field Advantage
Basic knowledge of html is enough to work with this technique.
It will always work whether cookie is disabled or not.
Hidden boxes resides in web pages of browser window so they do not
provide burden to the server.
This technique can be used along with all kind of web server or
application server.
Hidden Form Field Dis-Advantage
More complex than URL Rewriting.
It is maintained at server side.
Extra form submission is required on each pages.
Hidden form field can not store java object as values. They only store
text value
It Also increase network traffic because hidden boxes data travels over
the network along with request and response.
Hidden boxes does not provides data security because their data can be
view through view source option.
<form action="servlet1">
Name:<input type="text" name="userName"/> <br/>
<input type="submit" value="continue"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
26
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
}
catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
27
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
out.close();
}
catch(Exception e){System.out.println(e);}
}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
28
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
3. URL Rewriting
In URL rewriting, we append a token or identifier to the URL of the
next Servlet or the next resource. We can send parameter name/value
pairs using the following format:
url?name1=value1&name2=value2&??
A name and a value is separated using an equal = sign, a parameter
name/value pair is separated from another parameter using the
ampersand(&). When the user clicks the hyperlink, the parameter
name/value pairs will be passed to the server. From a Servlet, we can
use getParameter() method to obtain a parameter value.
index.html
1. <form action="servlet1">
29
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
FirstServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class FirstServlet extends HttpServlet {
6.
7. public void doGet(HttpServletRequest request, HttpServletResponse respon
se){
8. try{
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. String n=request.getParameter("userName");
14. out.print("Welcome "+n);
15.
16. //appending the username in the query string
17. out.print("<a href='servlet2?uname="+n+"'>visit</a>");
18.
19. out.close();
20.
21. }catch(Exception e){System.out.println(e);}
22. }
23.
24. }
SecondServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
30
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
4.
5. public class SecondServlet extends HttpServlet {
6.
7. public void doGet(HttpServletRequest request, HttpServletResponse respon
se)
8. try{
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. //getting value from the query string
14. String n=request.getParameter("uname");
15. out.print("Hello "+n);
16.
17. out.close();
18.
19. }catch(Exception e){System.out.println(e);}
20. }
21.
22.
23. }
web.xml
1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>FirstServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>s1</servlet-name>
10. <url-pattern>/servlet1</url-pattern>
11. </servlet-mapping>
12.
13. <servlet>
14. <servlet-name>s2</servlet-name>
31
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
15. <servlet-class>SecondServlet</servlet-class>
16. </servlet>
17.
18. <servlet-mapping>
19. <servlet-name>s2</servlet-name>
20. <url-pattern>/servlet2</url-pattern>
21. </servlet-mapping>
22.
23. </web-app>
4. HTTPSession Interface
1) bind objects
2) View and manipulate information about a session, such as the session
identifier, creation time, and last accessed time.
A. Creating a Session
32
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
C. Session Termination:
Methods Used:
i) setMaxInactiveInterval(int)
This method takes an integer argument representing a number of
seconds.
After the specified time elapses, the user’s session will expire.
ii) invalidate()
If the timer completes before the next request containing the session
ID is received, the server calls the invalidate() directly at any time in
order to terminate the running session.
Example:
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet(urlPatterns = {"/SessionServlet"})
public class SessionServlet extends HttpServlet {
@Override
33
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
34
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
35
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
36
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
37
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
38
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
39
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
40
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
41
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
42
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
43
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
44
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
45
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
46
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
47
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
48
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
49
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
Typically, the JSP engine checks to see whether a servlet for a JSP file
already exists and whether the modification date on the JSP is older than the
servlet. If the JSP is older than its generated servlet, the JSP container
assumes that the JSP hasn't changed and that the generated servlet still
matches the JSP's contents.
Advantages of JSP:
50
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
A JSP life cycle can be defined as the entire process from its creation
till the destruction which is similar to a servlet life cycle with an
additional step which is required to compile a JSP into servlet.
The following are the paths followed by a JSP
Compilation Initialization Execution Cleanup
The four major phases of JSP life cycle are very similar to Servlet Life
Cycle and they are as follows:
JSP Compilation:
When a browser asks for a JSP, the JSP engine first checks to see
whether it needs to compile the page. If the page has never been
compiled, or if the JSP has been modified since it was last compiled, the
JSP engine compiles the page.
The compilation process involves three steps:
Parsing the JSP.
Turning the JSP into a servlet.
Compiling the servlet.
51
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
JSP Initialization:
When a container loads a JSP it invokes the jspInit() method before
servicing any requests. If you need to perform JSP-specific initialization,
override the jspInit() method:
public void jspInit(){
// Initialization code...
}
Typically initialization is performed only once and as with the servlet init
method, you generally initialize database connections, open files, and
create lookup tables in the jspInit method.
JSP Execution:
This phase of the JSP life cycle represents all interactions with requests
until the JSP is destroyed.
Whenever a browser requests a JSP and the page has been loaded and
initialized, the JSP engine invokes the _jspService() method in the JSP.
The _jspService() method takes an HttpServletRequest and an
HttpServletResponse as its parameters as follows:
void _jspService(HttpServletRequest request,
HttpServletResponse response)
{
// Service handling code...
}
The _jspService() method of a JSP is invoked once per a request and is
responsible for generating the response for that request and this method
is also responsible for generating responses to all seven of the HTTP
methods ie. GET, POST, DELETE etc.
JSP Cleanup:
The destruction phase of the JSP life cycle represents when a JSP is
being removed from use by a container.
The jspDestroy() method is the JSP equivalent of the destroy method for
servlets. Override jspDestroy when you need to perform any cleanup,
such as releasing database connections or closing open files.
The jspDestroy() method has the following form:
public void jspDestroy()
{
52
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
53
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
1. JSP Markup
Three types of markup elements:
1.1 Scripting Elements
Ex: scriptlet
Inserts Java code into servlet
54
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
55
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
56
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
Output:
57
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname"><br/>
5. <input type="submit" value="go">
6. </form>
7. </body>
8. </html>
File: welcome.jsp
1. <html>
2. <body>
3. <%= "Welcome "+request.getParameter("uname") %>
4. </body>
5. </html>
Output: Refer the previous example in scriptlet tag
index.jsp 6. </html>
1. <html>
2. <body>
3. <%! int data=50; %>
4. <%= "Value of the variable i
s:"+data %>
5. </body>
58
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
59
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
60
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
1) import
The import attribute is used to import class, interface or all the
members of a package. It is similar to import keyword in java class or
interface
2)contentType
The contentType attribute defines the MIME(Multipurpose Internet
Mail Extension) type of the HTTP response.The default value is
"text/html;charset=ISO-8859-1".
Example of contentType
attribute
1. <html>
2. <body>
3. <center><h1><b>
4. <%@ page contentType=”ap
plication/msword” %>
5. Today is: <%= new java.util
.Date() %>
6. </b></h1></center>
7. </body>
8. </html>
3) errorPage
The errorPage attribute is used to define the error page, if exception
occurs in the current page, it will be redirected to the error page.
61
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
62
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
We use the TLD (Tag Library Descriptor) file to define the tags.
The taglib directive declares that your JSP page uses a set of custom
tags, identifies the location of the library, and provides a means for
identifying the custom tags in your JSP page.
The taglib directive follows the following syntax:
<%@ taglib uri="uri" prefix="prefixOfTag" >
JSTL has support for common, structural tasks such as iteration and
conditionals, tags for manipulating XML documents,
internationalization tags, and SQL tags.
It also provides a framework for integrating the existing custom tags with
the JSTL tags.
63
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
Advantage of JSTL:
1. Fast Development: JSTL provides many tags that simplifies the
JSP.
2. Code Reusability: We can use the JSTL tags in various pages.
3. No need to use scriptlet tag: It avoids the use of scriptlet tag.
Example:
65
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
66
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
Example:
67
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
Example:
68
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
Example:
69
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
<price>90/kg</price>
</vegetable>
</vegetables>
</c:set>
<x:parse xml="${vegetable}" var="output"/>
<b>Name of the vegetable is</b>:
<x:out select="$output/vegetables/vegetable[1]/name" /><br>
<b>Price of the Potato is</b>:
<x:out select="$output/vegetables/vegetable[2]/price" />
</body> </html>
70
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
Example:
71
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
HTML form basically is a Graphic User Interface (GUI) which you present
to get the input data from users. Once users submit the form from the
client side, on the server side, you need to capture those data for further
processing such as business logic validation, saving the data into the
database and so on.
Example: (AuthorsForm.jsp)
<html>
<head>
<title>Echoing HTML Request Parameters</title>
</head>
<body>
<h3>Choose an author:</h3>
<form method="get">
<input type="checkbox" name="author" value="Tan Ah Teck">Tan
<input type="checkbox" name="author" value="Mohd Ali">Ali
<input type="checkbox" name="author" value="Kumar">Kumar
<input type="submit" value="Query">
</form>
72
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
<%
String[] authors = request.getParameterValues("author");
if (authors != null) {
%>
<h3>You have selected author(s):</h3>
<ul>
<%
for (int i = 0; i < authors.length; ++i) {
%>
<li><%= authors[i] %></li>
<%
}
%>
</ul>
<a href="<%= request.getRequestURI() %>">BACK</a>
<%
}
%>
</body>
</html>
73
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE
Explanations
1. This HTML page has a form with 3 checkboxes. The "name=value"
pair of the checkboxes is "author=so_and_so". No "action" attribute
is specified, the default "action" is the current page (i.e. the query
will be sent to the same page).
2. The JSP scriptlet checks if the query parameter "author" exists to
decide whether to dynamically generate the enclosed codes. "author"
parameter is absent when the page is first requested. Once the
client fills in the form (by checking the boxes) and submits the form,
"author" will be present in the HTTP request, and submitted to
the same page for processing (with the default <form>’s "action"
attribute).
3. The request.getParameterValues() is used to retrieve all the values
of the query parameter. The values are echoed back using an
unordered list.
74