Sunteți pe pagina 1din 28

SERVLET EXAMPLES for all major concepts

Servlet Examples

Your First Servlet

import java.io.*; import javax.servlet.*; import javax.servlet.http.*;

public class MyServlet extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

res.setContentType("text/html"); PrintWriter out = res.getWriter();

out.println("<HTML>"); out.println("<HEAD><TITLE>Hello World</TITLE></HEAD>"); out.println("<BODY>"); out.println("<BIG>Hello World</BIG>"); out.println("</BODY></HTML>");

}

}

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"

"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>

<servlet><servlet-name>MyServletName</servlet-name>

<servlet-class>MyServlet</servlet-class>

</servlet>

<servlet-mapping><servlet-name>MyServletName</servlet-name>

<url-pattern>/index.html</url-pattern>

</servlet-mapping>

</web-app>

===============================================================

2. List All Init Parameters in Servlet

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*;

public class MyServlet extends HttpServlet {

public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {

Tested By M.Gangappa

1

SERVLET EXAMPLES for all major concepts

res.setContentType("text/plain"); PrintWriter out = res.getWriter();

out.println("Init Parameters:"); Enumeration e = getInitParameterNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); out.println(name + ": " + getInitParameter(name));

}

}

}

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"

"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>

<servlet><servlet-name>MyServletName</servlet-name>

<servlet-class>MyServlet</servlet-class>

<init-param>

<param-name>

initial

</param-name>

<param-value>

1000

</param-value> <description> The initial value for the counter <!-- optional -->

</description>

</init-param>

</servlet>

<servlet-mapping><servlet-name>MyServletName</servlet-name>

<url-pattern>/index.html</url-pattern>

</servlet-mapping>

</web-app>

=============================================================== 3. Get all Server Related Parameters

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*;

public class MyServlet extends HttpServlet { public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter();

ServletContext context = getServletContext(); out.println("req.getServerName(): " + req.getServerName()); out.println("req.getServerPort(): " + req.getServerPort()); out.println("context.getServerInfo(): " + context.getServerInfo()); out.println("getServerInfo() name: " +

Tested By M.Gangappa

2

SERVLET EXAMPLES for all major concepts

getServerInfoName(context.getServerInfo())); out.println("getServerInfo() version: " + getServerInfoVersion(context.getServerInfo())); out.println("context.getAttributeNames():"); Enumeration e = context.getAttributeNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); out.println(" context.getAttribute(\"" + name + "\"): " + context.getAttribute(name));

}

}

private String getServerInfoName(String serverInfo) {

int slash = serverInfo.indexOf('/'); if (slash == -1) return serverInfo; else return serverInfo.substring(0, slash);

}

private String getServerInfoVersion(String serverInfo) { // Version info is everything between the slash and the space int slash = serverInfo.indexOf('/'); if (slash == -1) return null; int space = serverInfo.indexOf(' ', slash); if (space == -1) space = serverInfo.length(); return serverInfo.substring(slash + 1, space);

}

}

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"

"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>

<servlet><servlet-name>MyServletName</servlet-name>

<servlet-class>MyServlet</servlet-class>

</servlet>

<servlet-mapping><servlet-name>MyServletName</servlet-name>

<url-pattern>/index.html</url-pattern>

</servlet-mapping>

</web-app>

====================================================

4. Date Servlet: doGet method

import java.io.IOException; import java.io.PrintWriter; import java.util.Date;

Tested By M.Gangappa

3

SERVLET EXAMPLES for all major concepts

import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;

public class DateServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

HttpSession hs = request.getSession(true);

response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.print("<B>");

Date date = (Date) hs.getAttribute("date"); if (date != null) { pw.print("Last access: " + date + "<br>");

}

date = new Date(); hs.setAttribute("date", date); pw.println("Current date: " + date);

}

}

=============================================================== 5. Using Servlet Init Method

import java.util.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*;

public class MyServlet extends HttpServlet {

String msg = "";

public void init(ServletConfig config)

{

msg = "Hello from Java servlets!";

}

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException

{

response.setContentType("text/html"); PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

Tested By M.Gangappa

4

SERVLET EXAMPLES for all major concepts

out.println("<TITLE>"); out.println("Using the init Method"); out.println("</TITLE>"); out.println("</HEAD>"); out.println("<BODY>"); out.println("<H1>Using the init Method</H1>"); out.println(msg); out.println("</BODY>"); out.println("</HTML>");

 

}

}

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"

"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>

<servlet><servlet-name>MyServletName</servlet-name>

<servlet-class>MyServlet</servlet-class>

</servlet>

<servlet-mapping><servlet-name>MyServletName</servlet-name>

<url-pattern>/index.html</url-pattern>

</servlet-mapping>

</web-app>

=============================================================== 6. Returns any parameters and lists server properties.

import java.io.IOException; import java.io.PrintWriter;

import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

public class Properties extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) t hrows ServletException, IOException { PrintWriter out = resp.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>My First Servlet</title>"); out.println("</head>");

out.println("<h2><center>");

out.println("Information About You</center></h2>"); out.println("<br>");

out.println("<center><table border>"); out.println("<tr>"); out.println("<td>Method</td>");

Tested By M.Gangappa

5

SERVLET EXAMPLES for all major concepts

out.println("<td>" + req.getMethod() + "</td>"); out.println("</tr>");

out.println("<tr>"); out.println("<td>User</td>"); out.println("<td>" + req.getRemoteUser() + "</td>"); out.println("</tr>");

out.println("<tr>"); out.println("<td>Client</td>"); out.println("<td>" + req.getRemoteHost() + "</td>"); out.println("</tr>");

out.println("<tr>"); out.println("<td>Protocol</td>"); out.println("<td>" + req.getProtocol() + "</td>"); out.println("</tr>");

java.util.Enumeration e = req.getParameterNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); out.println("<tr>"); out.println("<td>Parameter '" + name + "'</td>"); out.println("<td>" + req.getParameter(name) + "</td>"); out.println("</tr>");

}

out.println("</table></center><br><hr><br>");

out.println("<h2><center>");

out.println("Server Properties</center></h2>"); out.println("<br>");

out.println("<center><table border width=80%>");

java.util.Properties props = System.getProperties(); e = props.propertyNames();

while (e.hasMoreElements()) { String name = (String) e.nextElement(); out.println("<tr>"); out.println("<td>" + name + "</td>"); out.println("<td>" + props.getProperty(name) + "</td>"); out.println("</tr>");

}

out.println("</table></center>");

out.println("</html>");

out.flush();

}

public void init() throws ServletException { ServletConfig config = getServletConfig();

}

public void destroy() {

Tested By M.Gangappa

6

SERVLET EXAMPLES for all major concepts

}

}

==============================================================

Servlets and forms

1.Servlet Post Form Data to Self Servlet

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*;

public class MyServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse res ponse) throws ServletException, java.io.IOException {

System.out.println("command: "+request.getParameter("command"));

response.setContentType("text/html");

java.io.PrintWriter out = response.getWriter();

out.println("<html><head>");

out.println("<title>Help Page</title></head><body>"); out.println("<h2>Please submit your information</h2>");

out.println("<form method=\"post\" action =\"" + request.getContext Path() +"/MyServlet\" >");

out.println("<table border=\"0\"><tr><td valign=\"top\">"); out.println("Your first name: </td> <td valign=\"top\">"); out.println("<input type=\"text\" name=\"firstname\" size=\"20\">")

;

out.println("</td></tr><tr><td valign=\"top\">"); out.println("Your last name: </td> <td valign=\"top\">"); out.println("<input type=\"text\" name=\"lastname\" size=\"20\">"); out.println("</td></tr><tr><td valign=\"top\">"); out.println("Your email: </td> <td valign=\"top\">"); out.println("<input type=\"text\" name=\"email\" size=\"20\">"); out.println("</td></tr><tr><td valign=\"top\">");

out.println("<input type=\"submit\" value=\"Submit Info\"></td></tr

>");

out.println("</table></form>");

out.println("</body></html>");

Tested By M.Gangappa

7

SERVLET EXAMPLES for all major concepts

}

public void doPost(HttpServletRequest request, HttpServletResponse r esponse) throws ServletException,java.io.IOException{

Enumeration paramNames = request.getParameterNames();

String parName;

boolean emptyEnum = false; if (! paramNames.hasMoreElements()) emptyEnum = true;

response.setContentType("text/html");

java.io.PrintWriter out = response.getWriter();

out.println("<html><head>"); out.println("<title>Submitted Parameters</title></head><body>");

if (emptyEnum){ out.println("<h2>Sorry, the request does not contain any paramete

rs</h2>");

} else { out.println("<h2>Here are the submitted parameter values</h2>");

}

while(paramNames.hasMoreElements()){

parName = (String) paramNames.nextElement(); out.println("<strong>" + parName + "</strong> : " + request.getPa rameter(parName)); out.println("<br />");

}

out.println("</body></html>");

}

}

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"

"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>

<servlet><servlet-name>MyServletName</servlet-name>

<servlet-class>MyServlet</servlet-class>

</servlet>

<servlet-mapping><servlet-name>MyServletName</servlet-name>

<url-pattern>/*</url-pattern>

Tested By M.Gangappa

8

SERVLET EXAMPLES for all major concepts

</servlet-mapping>

</web-app>

2. Get Form Text Field as a Servlet parameter

import java.io.*; import javax.servlet.*; import javax.servlet.http.*;

public class MyServlet extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

res.setContentType("text/html"); PrintWriter out = res.getWriter();

String name = req.getParameter("name"); out.println("<HTML>"); out.println("<HEAD><TITLE>Hello, " + name + "</TITLE></HEAD>"); out.println("<BODY>"); out.println("Hello, " + name); out.println("</BODY></HTML>");

}

public String getServletInfo() { return "A servlet that knows the name of the person to whom it's" +

"saying hello";

}

}

<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<servlet><servlet-name>MyServletName</servlet-name>

<servlet-class>MyServlet</servlet-class>

</servlet>

<servlet-mapping><servlet-name>MyServletName</servlet-name>

<url-pattern>*.do</url-pattern>

</servlet-mapping>

</web-app>

<HTML> <HEAD> <TITLE>Introductions</TITLE> </HEAD> <BODY> <FORM METHOD=GET ACTION="Hello.do"> If you don't mind me asking, what is your name?

Tested By M.Gangappa

9

SERVLET EXAMPLES for all major concepts

<INPUT TYPE=TEXT NAME="name"><P> <INPUT TYPE=SUBMIT> </FORM> </BODY> </HTML>

===========================================================

3. Servlet Form Processor CheckBox

import javax.servlet.http.*; import javax.servlet.*; import java.io.IOException;

public class MyServlet extends HttpServlet

{

public void doPost (HttpServletRequest req, HttpServletResponse res) throws IOException

{

ServletOutputStream out = res.getOutputStream(); res.setContentType("text/html"); out.println("<html><head><title>Basic Form Processor Output</title> </head>"); out.println("<body>"); out.println("<h1>Here is your Form Data</h1>"); //extract the form data here String title = req.getParameter("title"); String name = req.getParameter("name"); String city = req.getParameter("city"); String country = req.getParameter("country"); String tel = req.getParameter("tel"); String age = req.getParameter("age"); // extracting data from the checkbox field String[] interests = req.getParameterValues("interests"); //output the data into a web page out.println("Your title is " + title); out.println("<br>Your name is " + name); out.println("<br>Your city is " + city); out.println("<br>Your country is " + country); out.println("<br>Your tel is " + tel); out.println("<br>Your interests include<ul> "); for (int i=0;i<interests.length; i++) { out.println("<li>" + interests[i]);

}

out.println("</ul>"); out.println("<br>Your age is " + age);

out.println("</body></html>");

}

}

<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

Tested By M.Gangappa

10

SERVLET EXAMPLES for all major concepts

<web-app>

<servlet><servlet-name>MyServletName</servlet-name>

<servlet-class>MyServlet</servlet-class>

</servlet>

<servlet-mapping><servlet-name>MyServletName</servlet-name>

<url-pattern>*.do</url-pattern>

</servlet-mapping>

</web-app>

<html> <head> <title>JSP Unleashed, Chapter 1 - A Basic HTML Form</title> </head> <body> <h1>Please enter your information</h1> <form method="POST" action="formProcessor.do"> Title: <select size="1" name="title"> <option>Mr</option> <option>Mrs</option> <option>Miss</option> <option>Ms</option> <option>Other</option> </select><br> Name: <input type="text" name="name" size="20"><br> City: <input type="text" name="city" size="20"><br> Country: <input type="text" name="country" size="20"><br> Telephone: <input type="text" name="tel" size="20"> <P>Please inform us of your interests:<br> <input type="checkbox" name="interests" value="Sport">Sport<br> <input type="checkbox" name="interests" value="Music">Music<br> <input type="checkbox" name="interests" value="Reading">Reading<br> <input type="checkbox" name="interests" value="TV and Film">TV and Fi lm</p> <P>Your age <input type="radio" name="age" value="25orless" checked>Less than 25 <input type="radio" name="age" value="26to40">26-40 <input type="radio" name="age" value="41to65">41-65 <input type="radio" name="age" value="over65">Over 65</p> <P><input type="submit" value="Submit"></p> </form> </body> </html>

===================================================== 4. Servlet Based GuestBook

Tested By M.Gangappa

11

SERVLET EXAMPLES for all major concepts

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*;

public class MyServlet extends HttpServlet {

private Vector entries = new Vector(); private long lastModified = 0;

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter();

printHeader(out);

printForm(out);

printMessages(out);

printFooter(out);

}

// Add a new entry, then dispatch back to doGet() public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

handleForm(req, res); doGet(req, res);

}

private void printHeader(PrintWriter out) throws ServletException { out.println("<HTML><HEAD><TITLE>Guestbook</TITLE></HEAD>"); out.println("<BODY>");

}

private void printForm(PrintWriter out) throws ServletException { out.println("<FORM METHOD=POST>"); // posts to itself out.println("<B>Please submit your feedback:</B><BR>"); out.println("Your name: <INPUT TYPE=TEXT NAME=name><BR>"); out.println("Your email: <INPUT TYPE=TEXT NAME=email><BR>"); out.println("Comment: <INPUT TYPE=TEXT SIZE=50 NAME=comment><BR>"); out.println("<INPUT TYPE=SUBMIT VALUE=\"Send Feedback\"><BR>"); out.println("</FORM>"); out.println("<HR>");

}

private void printMessages(PrintWriter out) throws ServletException { String name, email, comment;

Enumeration e = entries.elements(); while (e.hasMoreElements()) { GuestbookEntry entry = (GuestbookEntry) e.nextElement(); name = entry.name; if (name == null) name = "Unknown user"; email = entry.email; if (name == null) email = "Unknown email"; comment = entry.comment;

Tested By M.Gangappa

12

SERVLET EXAMPLES for all major concepts

if (comment == null) comment = "No comment"; out.println("<DL>"); out.println("<DT><B>" + name + "</B> (" + email + ") says"); out.println("<DD><PRE>" + comment + "</PRE>"); out.println("</DL>");

// Sleep for half a second to simulate a slow data source try { Thread.sleep(500); } catch (InterruptedException ignored) {

}

}

}

private void printFooter(PrintWriter out) throws ServletException { out.println("</BODY>");

}

private void handleForm(HttpServletRequest req, HttpServletResponse res) { GuestbookEntry entry = new GuestbookEntry();

entry.name = req.getParameter("name"); entry.email = req.getParameter("email"); entry.comment = req.getParameter("comment");

entries.addElement(entry);

// Make note we have a new last modified time lastModified = System.currentTimeMillis();

}

public long getLastModified(HttpServletRequest req) { return lastModified;

}

}

class GuestbookEntry { public String name; public String email; public String comment;

}

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"

"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>

<servlet><servlet-name>MyServletName</servlet-name>

<servlet-class>MyServlet</servlet-class>

</servlet>

<servlet-mapping><servlet-name>MyServletName</servlet-name>

<url-pattern>/index.html</url-pattern>

</servlet-mapping>

</web-app>

=========================================================

Tested By M.Gangappa

13

SERVLET EXAMPLES for all major concepts

=========================================================

Sessions

Servlet Session Info

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*;

public class MyServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse r esponse) throws ServletException, java.io.IOException {

response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); HttpSession session = request.getSession();

out.println("<html>"); out.println("<head>"); out.println("<title>Simple Session Tracker</title>"); out.println("</head>"); out.println("<body>");

out.println("<h2>Session Info</h2>"); out.println("session Id: " + session.getId() + "<br><br>"); out.println( "The SESSION TIMEOUT period is " + session.getMaxI nactiveInterval() + " seconds.<br><br>"); out.println( "Now changing it to 20 minutes.<br><br>"); session.setMaxInactiveInterval(20 * 60); out.println("The SESSION TIMEOUT period is now " + session.getM axInactiveInterval() + " seconds.");

out.println("</body>");

out.println("</html>");

}

/** Handles the HTTP <code>POST</code> method.

* @param request servlet request

* @param response servlet response

*/ protected void doPost(HttpServletRequest request, HttpServletRespon

se response)

Tested By M.Gangappa

14

SERVLET EXAMPLES for all major concepts

throws ServletException, java.io.IOException {

doGet(request,response);

}

}

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"

"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>

<servlet><servlet-name>MyServletName</servlet-name>

<servlet-class>MyServlet</servlet-class>

</servlet>

<servlet-mapping><servlet-name>MyServletName</servlet-name>

<url-pattern>/index.html</url-pattern>

</servlet-mapping>

</web-app>

============================================================== 2. Get Set SessionAttributes in Servlet

import java.util.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*;

public class MyServlet extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter();

HttpSession session = req.getSession();

Integer count = (Integer)session.getAttribute("tracker.count"); if (count == null) count = new Integer(1); else count = new Integer(count.intValue() + 1); session.setAttribute("tracker.count", count);

out.println("<HTML><HEAD><TITLE>SessionTracker</TITLE></HEAD>"); out.println("<BODY><H1>Session Tracking Demo</H1>");

out.println("You've visited this page " + count + ((count.intValue() == 1) ? " time." : " times."));

Tested By M.Gangappa

15

SERVLET EXAMPLES for all major concepts

}

out.println("<P>");

out.println("<H2>Here is your session data:</H2>"); Enumeration e = session.getAttributeNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); out.println(name + ": " + session.getAttribute(name) + "<BR>");

}

out.println("</BODY></HTML>");

}

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"

"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>

<servlet><servlet-name>MyServletName</servlet-name>

<servlet-class>MyServlet</servlet-class>

</servlet>

<servlet-mapping><servlet-name>MyServletName</servlet-name>

<url-pattern>/index.html</url-pattern>

</servlet-mapping>

</web-app>

2. Get Set Session Value in a Servlet

import java.util.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*;

public class MyServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse r esponse)

throws ServletException, IOException

{

response.setContentType("text/html"); PrintWriter out = response.getWriter();

HttpSession session = request.getSession(true);

Integer counter2 = (Integer) getServletContext().getAttribute (

"counter2");

if (counter2 == null) { counter2 = new Integer(1); } else { counter2 = new Integer(counter2.intValue() + 1);

}

getServletContext().setAttribute("counter2", counter2);

Tested By M.Gangappa

16

SERVLET EXAMPLES for all major concepts

Integer counter = (Integer) session.getAttribute("counter");

 

if (counter == null) { counter = new Integer(1);

}

else { counter = new Integer(counter.intValue() + 1);

}

session.setAttribute("counter", counter);

 

out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>"); out.println("Using Contexts"); out.println("</TITLE>"); out.println("</HEAD>"); out.println("<BODY>"); out.println("<H1>Using Contexts</H1>");

out.println("Welcome! You have been here " + counter + " times.

<BR>");

out.println("Total page accesses: " + counter2 + "<BR>");

 

if(session.isNew()){ out.println("This is a new session.<BR>");

}

else { out.println("This is not a new session.<BR>");

}

out.println("The session ID: " + session.getId() + "<BR>"); out.println("Last time accessed: " + new Date(session.getLastAc cessedTime()) + "<BR>"); out.println("Creation time: " + new Date(session.getCreationTim e()) + "<BR>"); out.println("Timeout length: " + session.getMaxInactiveInterval () + " seconds<BR>");

out.println("</BODY>");

 

out.println("</HTML>");

}

}

<?xml version="1.0" encoding="ISO-8859-1"?>

 

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"

"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>

<servlet><servlet-name>MyServletName</servlet-name>

 

<servlet-class>MyServlet</servlet-class>

</servlet>

Tested By M.Gangappa

17

SERVLET EXAMPLES for all major concepts

<servlet-mapping><servlet-name>MyServletName</servlet-name>

<url-pattern>/index.html</url-pattern>

</servlet-mapping>

</web-app>

3. use the Servlet API to manage session information

import java.io.IOException; import java.io.PrintWriter;

import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;

public class Counter extends HttpServlet { static final String COUNTER_KEY = "Counter.count";

public void doGet(HttpServletRequest req, HttpServletResponse resp) t hrows ServletException, IOException { HttpSession session = req.getSession(true); resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); int count = 1; Integer i = (Integer) session.getAttribute(COUNTER_KEY); if (i != null) { count = i.intValue() + 1;

}

session.setAttribute(COUNTER_KEY, new Integer(count)); out.println("<html>"); out.println("<head>"); out.println("<title>Session Counter</title>"); out.println("</head>"); out.println("<body>"); out.println("Your session ID is <b>" + session.getId()); out.println("</b> and you have hit this page <b>" + count + "</b> time(s) during this browser session");

out.println("<form method=GET action=\"" + req.getRequestURI() + "\ ">"); out.println("<input type=submit " + "value=\"Hit page again\">"); out.println("</form>"); out.println("</body>"); out.println("</html>"); out.flush();

}

}

4. Servlet Session Check

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; import java.text.DateFormat; public class MyServlet extends HttpServlet {

Tested By M.Gangappa

18

SERVLET EXAMPLES for all major concepts

public void doGet(HttpServletRequest request, HttpServletResponse resp onse) throws ServletException, java.io.IOException {

HttpSession session = request.getSession(false); if (session == null){ response.sendRedirect("/dbproj/login.jsp"); } else { response.sendRedirect("/dbproj/menu.jsp");

}

}

}

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"

"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>

<servlet><servlet-name>MyServletName</servlet-name>

<servlet-class>MyServlet</servlet-class>

</servlet>

<servlet-mapping><servlet-name>MyServletName</servlet-name>

<url-pattern>/index.html</url-pattern>

</servlet-mapping>

</web-app>

=============================================================

CooKie

1. Add Cookie Servlet ‘

import java.io.IOException; import java.io.PrintWriter;

import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest;

Tested By M.Gangappa

19

SERVLET EXAMPLES for all major concepts

import javax.servlet.http.HttpServletResponse;

public class AddCookieServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse re sponse) throws ServletException, IOException { String data = request.getParameter("data"); Cookie cookie = new Cookie("MyCookie", data); response.addCookie(cookie); response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B>MyCookie has been set to"); pw.println(data); pw.close();

}

}

2. Get Cookies Servlet

import java.io.IOException; import java.io.PrintWriter;

import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

public class GetCookiesServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse res ponse)

throws ServletException, IOException {

Cookie[] cookies = request.getCookies();

response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B>"); for (int i = 0; i < cookies.length; i++) { String name = cookies[i].getName(); String value = cookies[i].getValue(); pw.println("name = " + name + "; value = " + value);

}

pw.close();

}

}

3.Servlet Cookie Setter

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*;

public class MyServlet extends HttpServlet {

Tested By M.Gangappa

20

SERVLET EXAMPLES for all major concepts

public void doGet(HttpServletRequest request, HttpServletResponse r esponse) throws ServletException, java.io.IOException {

Cookie cookie = null; //Get an array of Cookies associated with this domain Cookie[] cookies = request.getCookies(); boolean newCookie = false;

//Get the 'mycookie' Cookie if it exists if (cookies != null){ for (int i = 0; i < cookies.length; i++){ if (cookies[i].getName().equals("mycookie")){ cookie = cookies[i];

}

}//end for }//end if

if (cookie == null){ newCookie=true; //Get the cookie's Max-Age from a context-param element //If the 'cookie-age' param is not set properly //then set the cookie to a default of -1, 'never expires' int maxAge; try{

maxAge = new Integer(getServletContext().getInitParameter("c ookie-age")).intValue(); } catch (Exception e) { maxAge = -1;

}

//Create the Cookie object

cookie = new Cookie("mycookie",""+getNextCookieValue()); cookie.setPath(request.getContextPath()); cookie.setMaxAge(maxAge); response.addCookie(cookie);

}//end if // get some info about the cookie response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter();

out.println("<html>"); out.println("<head>"); out.println("<title>Cookie info</title>"); out.println("</head>"); out.println("<body>");

out.println("<h2> Information about the cookie named \"mycookie

\"</h2>");

out.println("Cookie value: "+cookie.getValue()+"<br>"); if (newCookie){ out.println("Cookie Max-Age: "+cookie.getMaxAge()+"<br>");

Tested By M.Gangappa

21

SERVLET EXAMPLES for all major concepts

 

out.println("Cookie Path: "+cookie.getPath()+"<br>");

}

out.println("</body>");

out.println("</html>");

out.close();

 

}

private long getNextCookieValue(){

 

/*This produces a cookie value to show how to create Cookie objects

. If

 

this method was heavily used in a production environment it may produce too many objects; synchronization of a single Date object might be better, based on performance testing. At any rate a production environment would produce a unique cookie value in a different manner such as from a unique database ID. */

 

//returns the number of milleseconds since Jan 1, 1970 return new java.util.Date().getTime();

 

}

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {

 

doGet(request,response);

 

}

}

<?xml version="1.0" encoding="ISO-8859-1"?>

 

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"

 

"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>

 
 

<servlet><servlet-name>MyServletName</servlet-name>

 

<servlet-class>MyServlet</servlet-class>

<init-param>

<param-name>

go

</param-name>

<param-value>

weather

</param-value>

</init-param>

 

</servlet>

<servlet-mapping><servlet-name>MyServletName</servlet-name>

 

<url-pattern>/index.html</url-pattern>

 

</servlet-mapping>

 

</web-app>

4. 4. Servlet Cookie Reader

Tested By M.Gangappa

22

SERVLET EXAMPLES for all major concepts

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*;

public class MyServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse r esponse) throws ServletException, java.io.IOException {

Cookie cookie = null; //Get an array of Cookies associated with this domain Cookie[] cookies = request.getCookies(); boolean hasCookies = false;

if (cookies != null) hasCookies = true;

// display the name/value of each cookie response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter();

out.println("<html>"); out.println("<head>"); out.println("<title>Cookie information</title>"); out.println("</head>"); out.println("<body>"); if (hasCookies){ out.println("<h2> The name and value of each found cookie</h2>"

);

for (int i = 0; i < cookies.length; i++){ cookie = cookies[i]; out.println("Name of cookie #"+(i + 1)+": "+cookie.getName(

)+"<br>");

out.println("Value of cookie #"+(i + 1)+": "+cookie.getValu e()+"<br><br>");

}

} else { out.println("<h2> This request did not include any cookies<

/h2>");

}

out.println("</body>");

out.println("</html>");

out.close();

}

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {

Tested By M.Gangappa

23

SERVLET EXAMPLES for all major concepts

doGet(request,response);

}

}

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"

"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>

<servlet><servlet-name>MyServletName</servlet-name>

<servlet-class>MyServlet</servlet-class>

<init-param>

<param-name>

 

go

</param-name>

<param-value>

 

weather

</param-value>

</init-param>

</servlet>

<servlet-mapping><servlet-name>MyServletName</servlet-name>

<url-pattern>/index.html</url-pattern>

</servlet-mapping>

</web-app>

5. Get/Set Cookie

import java.util.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*;

public class MyServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse r esponse) throws IOException, ServletException

{

response.setContentType("text/html"); PrintWriter out = response.getWriter();

out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>"); out.println("A Web Page"); out.println("</TITLE>"); out.println("</HEAD>"); out.println("<BODY");

Cookie[] cookies = request.getCookies(); boolean foundCookie = false;

for(int i = 0; i < cookies.length; i++) {

Tested By M.Gangappa

24

SERVLET EXAMPLES for all major concepts

 

Cookie cookie1 = cookies[i]; if (cookie1.getName().equals("color")) { out.println("bgcolor = " + cookie1.getValue()); foundCookie = true;

}

}

if (!foundCookie) { Cookie cookie1 = new Cookie("color", "cyan");

cookie1.setMaxAge(24*60*60);

response.addCookie(cookie1);

}

out.println(">"); out.println("<H1>Setting and Reading Cookies</H1>"); out.println("This page will set its background color using a co okie when reloaded."); out.println("</BODY>"); out.println("</HTML>");

 

}

}

<?xml version="1.0" encoding="ISO-8859-1"?>

 

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"

 

"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>

<servlet><servlet-name>MyServletName</servlet-name>

<servlet-class>MyServlet</servlet-class>

</servlet>

<servlet-mapping><servlet-name>MyServletName</servlet-name>

<url-pattern>/index.html</url-pattern>

</servlet-mapping>

</web-app>

6. List Servlet Cookie Information

import java.io.IOException; import java.io.PrintWriter;

import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

public class Cookies extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) t hrows ServletException, IOException { resp.setContentType("text/html"); req.getSession();

Tested By M.Gangappa

25

SERVLET EXAMPLES for all major concepts

PrintWriter out = resp.getWriter(); Cookie cookies[] = req.getCookies(); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet Cookie Information</title>"); out.println("</head>"); out.println("<body>");

if ((cookies == null) || (cookies.length == 0)) { out.println("<center><h1>No Cookies found</h1>"); } else {

out.println("<center><h1>Cookies found</h1>"); for (int i = 0; i < cookies.length; i++) { Cookie c = cookies[i]; out.println(c.getName() + "::" + c.getValue() + "::" + c.getComment() + "::" + c.getMaxAge() + "<BR/>");

}

out.println("</table></center>");

}

out.println("</body>");

out.println("</html>");

out.flush();

}

}

Servlet URL Rewrite

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*;

public class MyServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse resp onse) throws ServletException, java.io.IOException {

response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); String contextPath = request.getContextPath(); String encodedUrl = response.encodeURL(contextPath + "/default

.jsp");

out.println("<html>"); out.println("<head>"); out.println("<title>URL Rewriter</title>"); out.println("</head>"); out.println("<body>");

Tested By M.Gangappa

26

SERVLET EXAMPLES for all major concepts

out.println("<h1>This page will use URL rewriting if necessary<

/h2>");

out.println("Go to the default.jsp page <a href=\"" + encodedUr

l +

"\">here</a>.");

 

out.println("</body>");

out.println("</html>");

}

public void doPost(HttpServletRequest request, HttpServletResponse re sponse) throws ServletException, java.io.IOException { doGet(request,response);

}

}

<?xml version="1.0" encoding="ISO-8859-1"?>

 

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"

"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>

<servlet><servlet-name>MyServletName</servlet-name>

<servlet-class>MyServlet</servlet-class>

<init-param>

<param-name>

 

go

</param-name>

<param-value>

 

weather

</param-value>

</init-param>

</servlet>

<servlet-mapping><servlet-name>MyServletName</servlet-name>

<url-pattern>/index.html</url-pattern>

</servlet-mapping>

</web-app>

2. URL rewriting

import java.io.IOException; import java.io.PrintWriter;

import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;

public class CounterRewrite extends HttpServlet {

Tested By M.Gangappa

27

SERVLET EXAMPLES for all major concepts

static final String COUNTER_KEY = "Counter.count";

public void doGet(HttpServletRequest req, HttpServletResponse resp) t hrows ServletException, IOException { HttpSession session = req.getSession(true); resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); int count = 1; Integer i = (Integer) session.getAttribute(COUNTER_KEY); if (i != null) { count = i.intValue() + 1;

}

session.setAttribute(COUNTER_KEY, new Integer(count)); out.println("<html>"); out.println("<head>"); out.println("<title>Session Counter</title>"); out.println("</head>"); out.println("<body>"); out.println("Your session ID is <b>" + session.getId()); out.println("</b> and you have hit this page <b>" + count

+ "</b> time(s) during this browser session");

String url = req.getRequestURI(); out.println("<form method=GET action=\"" + resp.encodeURL(url) + "\ ">"); out.println("<input type=submit " + "value=\"Hit page again\">"); out.println("</form>"); out.println("</body>"); out.println("</html>"); out.flush();

}

}

Tested By M.Gangappa

28