SUBJECT CODE
TYPE THE SUBJECT NAME HERE
UNIT NO 3
SERVER SIDE SCRIPTING
● 3.7 Parameter
III V Data-Sessions-Cookies-URL
Rewriting-Other Capabilities
IT8501
WEB TECHNOLOGY
IT8501
WEB TECHNOLOGY
3.7 Parameter
Data-Sessions-Cookies-URL
Rewriting-Other Capabilities
IT8501
WEB TECHNOLOGY
UNIT III
Parameter Data-Sessions-Cookies-URL Rewriting-Other Capabilities
Parameter Data in Servlet
● GET Method
The GET method sends the encoded user information appended to the page request. The page and the
encoded information are separated by the ? (question mark) symbol as follows −
http://www.test.com/hello?key1 = value1&key2 = value2
● The GET method is the default method to pass information from browser to web server and it
produces a long string that appears in your browser's Location:box.
● The GET method has size limitation: only 1024 characters can be used in a request string.
IT8501
WEB TECHNOLOGY
∙ getParameter() − You call request.getParameter() method to get the value of a form
parameter.
∙ getParameterValues() − Call this method if the parameter appears more than once and
returns multiple values, for example checkbox.
∙ getParameterNames() − Call this method if you want a complete list of all parameters in the
current request.
GET Method Example using URL
∙ Here is a simple URL which will pass two values to HelloForm program using GET method.
∙ http://localhost:8080/HelloForm?first_name = ZARA&last_name = ALI
∙ Given below is the HelloForm.java servlet program to handle input given by web browser.
We are going to use getParameter() method which makes it very easy to access passed
information −
IT8501
WEB TECHNOLOGY
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloForm extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Using GET Method to Read Form Data";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
out.println(docType +
"<html>\n" +
IT8501
WEB TECHNOLOGY
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>First Name</b>: "
+ request.getParameter("first_name") + "\n" +
" <li><b>Last Name</b>: "
+ request.getParameter("last_name") + "\n" +
"</ul>\n" +
"</body>" +
"</html>"
);
}
IT8501
WEB TECHNOLOGY
Assuming your environment is set up properly, compile HelloForm.java as follows −
$ javac HelloForm.java
If everything goes fine, above compilation would produce HelloForm.class file.
Next you would have to copy this class file in
<Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes and create following
entries in web.xml file located in
<Tomcat-installation-directory>/webapps/ROOT/WEB-INF/
<servlet>
<servlet-name>HelloForm</servlet-name>
<servlet-class>HelloForm</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloForm</servlet-name>
<url-pattern>/HelloForm</url-pattern>
</servlet-mapping>
IT8501
WEB TECHNOLOGY
Now type http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI in your browser's
Location:box and make sure you already started tomcat server, before firing above command in the
browser. This would generate following result −
Using GET Method to Read Form Data
∙ First Name: ZARA
∙ Last Name: ALI
GET Method Example Using Form
Here is a simple example which passes two values using HTML FORM and submit button. We are
going to use same Servlet HelloForm to handle this input.
IT8501
WEB TECHNOLOGY
<html>
<body>
<form action = "HelloForm" method = "GET">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
Keep this HTML in a file Hello.htm and put it in <Tomcat-installationdirectory>/webapps/ROOT
directory. When you would access http://localhost:8080/Hello.htm, here is the actual output of the
above form.
Top of Form
First Name: Last Name:
Bottom of Form
IT8501
WEB TECHNOLOGY
Sessions
● can store the user information into the session object by using setAttribute() method and
This is later.
how youwhen needed
create this information
a HttpSession can be fetched from the session.
object.
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException { HttpSession session = req.getSession();}
● This is how you store info in session. Here we are storing username, emailid and userage
in session with the attribute name uName, uemailId and uAge respectively.
● session.setAttribute("uName", "ChaitanyaSingh");session.setAttribute("uemailId",
"[email protected]");session.setAttribute("uAge", "30");
T
IT8501
WEB TECHNOLOGY
tring userEmailId = (String) session.getAttribute("uemailId");String userAge = (String)
session.getAttribute("uAge");
Methods of HttpSession
● public void setAttribute(String name, Object value): Binds the object with a name and stores
the name/value pair as an attribute of the HttpSession object. If an attribute already exists, then
this method replaces the existing attributes.
● public Object getAttribute(String name): Returns the String object specified in the parameter,
from the session object. If no object is found for the specified attribute, then the getAttribute()
method returns null.
● public Enumeration getAttributeNames(): Returns an Enumeration that contains the name of
all the objects that are bound as attributes to the session object.
● public void removeAttribute(String name): Removes the given attribute from session.
● setMaxInactiveInterval(int interval): Sets the session inactivity time in seconds. This is the time
in seconds that specifies how long a sessions remains active since last request received from
client.
IT8501
WEB TECHNOLOGY
Session Example
index.html
<form action="login"> User Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPassword"/><br/> <input type="submit"
value="submit"/></form>
String userEmailId = (String) session.getAttribute("uemailId");String userAge = (String)
session.getAttribute("uAge");
Methods of HttpSession
● public void setAttribute(String name, Object value): Binds the object with a name
and stores the name/value pair as an attribute of the HttpSession object. If an attribute
already exists, then this method replaces the existing attributes.
● public Object getAttribute(String name): Returns the String object specified in the
parameter, from the session object. If no object is found for the specified attribute, then
the getAttribute() method returns null.
IT8501
WEB TECHNOLOGY
MyServlet1.java
import java.io.*;import javax.servlet.*;import javax.servlet.http.*;public class MyServlet1 extends
HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
try
{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();
String name = request.getParameter("userName");
String password = request.getParameter("userPassword");
pwriter.print("Hello "+name);
pwriter.print("Your Password is: "+password);
HttpSession session=request.getSession();
session.setAttribute("uname",name); session.setAttribute("upass",password); pwriter.print("<a
href='welcome'>view details</a>"); pwriter.close();
}catch(Exception exp)
{
System.out.println(exp); } } }
IT8501
WEB TECHNOLOGY
MyServlet2.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet2 extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
{ try
{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();
HttpSession session=request.getSession(false);
String myName=(String)session.getAttribute("uname");
String myPass=(String)session.getAttribute("upass");
pwriter.print("Name: "+myName+" Pass: "+myPass);
pwriter.close(); }
catch(Exception exp)
{
System.out.println(exp); }}}
IT8501
WEB TECHNOLOGY
WEB.xml
<web-app><servlet> <servlet-name>Servlet1</servlet-name>
<servlet-class>MyServlet1</servlet-class></servlet><servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/login</url-pattern></servlet-mapping><servlet>
<servlet-name>Servlet2</servlet-name>
<servlet-class>MyServlet2</servlet-class></servlet><servlet-mapping>
<servlet-name>Servlet2</servlet-name>
First Screen:
<url-pattern>/welcome</url-pattern></servlet-mapping></web-app>Output:
IT8501
WEB TECHNOLOGY
After clicking Submit:
After clicking view details:
IT8501
WEB TECHNOLOGY
Cookies
Cookies which is also used for session management
● When a user visits web application first time, the servlet container creates new HttpSession object by
calling request.getSession(). A unique Id is assigned to the session.
● The Servlet container also sets a Cookie in the header of the HTTP response with cookie name
and the unique session ID as its value.
● The cookie is stored in the user browser, the client (user’s browser) sends this cookie back to the
server for all the subsequent requests until the cookie is valid.
● The Servlet container checks the request header for cookies and get the session information
from the cookie and use the associated session from the server memory.
T
IT8501
WEB TECHNOLOGY
Types of Cookies
We can classify the cookie based on their expiry time:
1)Session
2)Persistent
1) SessionCookies:
Session cookies do not have expiration time. It lives in the browser memory. As soon as
the web browser is closed this cookie gets destroyed.
2) Persistent Cookies:
Unlike Session cookies they have expiration time, they are stored in the user hard drive
and gets destroyed based on the expiry time.
IT8501
WEB TECHNOLOGY
How to send Cookies to the Client
Here are steps for sending cookie to the client:
● Create a Cookie object.
● Set the maximum Age.
● Place the Cookie in HTTP response header.
1) Create a Cookie object:
Cookie c = new Cookie("userName","Chaitanya");
2) Set the maximum Age:
By using setMaxAge () method we can set the maximum age for the particular cookie in seconds.
c.setMaxAge(1800);
3) Place the Cookie in HTTP response header:
We can send the cookie to the client browser through response.addCookie() method.
response.addCookie(c);
How to read cookies
Cookie c[]=request.getCookies(); //c.length gives the cookie count for(int i=0;i<c.length;i++){
out.print("Name: "+c[i].getName()+" & Value: "+c[i].getValue());}
IT8501
WEB TECHNOLOGY
Example of Cookies in java servlet
index.html
<form action="login"> User Name:<input type="text" name="userName"/><br/> Password:<input
type="password" name="userPassword"/><br/> <input type="submit" value="submit"/></form>
MyServlet1.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet1 extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
try
{
IT8501
WEB TECHNOLOGY
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();
String name = request.getParameter("userName");
String password = request.getParameter("userPassword");
pwriter.print("Hello "+name);
pwriter.print("Your Password is: "+password); //Creating two cookies
Cookie c1=new Cookie("userName",name);
Cookie c2=new Cookie("userPassword",password); //Adding the cookies to response
header response.addCookie(c1);
response.addCookie(c2);
pwriter.print("<br><a href='welcome'>View Details</a>");
pwriter.close(); }
catch(Exception exp)
{ System.out.println(exp); } }}
IT8501
WEB TECHNOLOGY
MyServlet2.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet2 extends HttpServlet { public void doGet(HttpServletRequest request,
HttpServletResponse response)
{
Try
{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter(); //Reading cookies Cookie
c[]=request.getCookies(); //Displaying User name value from cookie
pwriter.print("Name: "+c[1].getValue()); //Displaying user password value from cookie
pwriter.print("Password: "+c[2].getValue());
pwriter.close(); }
catch(Exception exp){ System.out.println(exp);
} }}
IT8501
WEB TECHNOLOGY
web.xml
<web-app><display-name>BeginnersBookDemo</display-name>
<welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list>
<servlet> <servlet-name>Servlet1</servlet-name>
<servlet-class>MyServlet1</servlet-class></servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Servlet2</servlet-name>
<servlet-class>MyServlet2</servlet-class>
</servlet><servlet-mapping>
<servlet-name>Servlet2</servlet-name>
<url-pattern>/welcome</url-pattern></servlet-mapping></web-app>
IT8501
WEB TECHNOLOGY
IT8501
WEB TECHNOLOGY
Methods of Cookie class
● public void setComment(String purpose): This method is used for setting up comments
in the cookie. This is basically used for describing the purpose of the cookie.
● public String getComment(): Returns the comment describing the purpose of this cookie,
or null if the cookie has no comment.
● public void setMaxAge(int expiry): Sets the maximum age of the cookie in seconds.
IT8501
WEB TECHNOLOGY
● public int getMaxAge(): Gets the maximum age in seconds of this Cookie.
By default, -1 is returned, which indicates that the cookie will persist until browser shutdown.
● public String getName(): Returns the name of the cookie. The name cannot be changed after
creation.
● public void setValue(String newValue): Assigns a new value to this Cookie.
● public String getValue(): Gets the current value of this Cookie.
IT8501
WEB TECHNOLOGY
URL Rewriting and other capabilities
● URL Rewriting
● Advantage of URL Rewriting
● Disadvantage of URL Rewriting
● Example of URL Rewriting and other capabilities
IT8501
WEB TECHNOLOGY
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.
IT8501
WEB TECHNOLOGY
URL Rewriting Structure
IT8501
WEB TECHNOLOGY
Advantage of URL Rewriting
•It will always work whether cookie is disabled or not (browser independent).
•Extra form submission is not required on each pages.
Disadvantage of URL Rewriting
•It will work only with links.
•It can send Only textual information.
Example of using URL Rewriting
In this example, we are maintaning the state of the user using link. For this
purpose, we are appending the name of the user in the query string and getting
the value from the query string in another page.
index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
IT8501
WEB TECHNOLOGY
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
IT8501
WEB TECHNOLOGY
String n=request.getParameter("userName");
out.print("Welcome "+n);
//appending the username in the query string
out.print("<a href='servlet2?uname="+n+"'>visit</a>");
out.close();
}
catch(Exception e){System.out.println(e);}
}
}
IT8501
WEB TECHNOLOGY
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();
//getting value from the query string
String n=request.getParameter("uname");
out.print("Hello "+n);
IT8501
WEB TECHNOLOGY
out.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
IT8501
WEB TECHNOLOGY
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>
IT8501
WEB TECHNOLOGY