SERVLET EXAMPLES for all major concepts
Servlet Examples
Your First Servlet
import [Link].*; import [Link].*; import [Link].*; public class MyServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { [Link]("text/html"); PrintWriter out = [Link](); [Link]("<HTML>"); [Link]("<HEAD><TITLE>Hello World</TITLE></HEAD>"); [Link]("<BODY>"); [Link]("<BIG>Hello World</BIG>"); [Link]("</BODY></HTML>"); } }
<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "[Link] <web-app> <servlet><servlet-name>MyServletName</servlet-name> <servlet-class>MyServlet</servlet-class> </servlet> <servlet-mapping><servlet-name>MyServletName</servlet-name> <url-pattern>/[Link]</url-pattern> </servlet-mapping> </web-app>
=============================================================== 2. List
All Init Parameters in Servlet
[Link].*; [Link].*; [Link].*; [Link].*;
import import import import
public class MyServlet extends HttpServlet { public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
Tested By [Link]
SERVLET EXAMPLES for all major concepts
[Link]("text/plain"); PrintWriter out = [Link](); [Link]("Init Parameters:"); Enumeration e = getInitParameterNames(); while ([Link]()) { String name = (String) [Link](); [Link](name + ": " + getInitParameter(name)); } } } <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "[Link] <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>/[Link]</url-pattern> </servlet-mapping> </web-app>
=============================================================== 3. Get all Server Related Parameters
import import import import [Link].*; [Link].*; [Link].*; [Link].*;
public class MyServlet extends HttpServlet { public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { [Link]("text/plain"); PrintWriter out = [Link](); ServletContext context = getServletContext(); [Link]("[Link](): " + [Link]()); [Link]("[Link](): " + [Link]()); [Link]("[Link](): " + [Link]()); [Link]("getServerInfo() name: " +
Tested By [Link]
SERVLET EXAMPLES for all major concepts
getServerInfoName([Link]())); [Link]("getServerInfo() version: " + getServerInfoVersion([Link]())); [Link]("[Link]():"); Enumeration e = [Link](); while ([Link]()) { String name = (String) [Link](); [Link](" [Link](\"" + name + "\"): " + [Link](name)); } } private String getServerInfoName(String serverInfo) { int slash = [Link]('/'); if (slash == -1) return serverInfo; else return [Link](0, slash); } private String getServerInfoVersion(String serverInfo) { // Version info is everything between the slash and the space int slash = [Link]('/'); if (slash == -1) return null; int space = [Link](' ', slash); if (space == -1) space = [Link](); return [Link](slash + 1, space); } } <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "[Link] <web-app> <servlet><servlet-name>MyServletName</servlet-name> <servlet-class>MyServlet</servlet-class> </servlet> <servlet-mapping><servlet-name>MyServletName</servlet-name> <url-pattern>/[Link]</url-pattern> </servlet-mapping> </web-app>
====================================================
4. Date Servlet: doGet method
import [Link]; import [Link]; import [Link];
Tested By [Link]
SERVLET EXAMPLES for all major concepts
import import import import import [Link]; [Link]; [Link]; [Link]; [Link];
public class DateServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession hs = [Link](true); [Link]("text/html"); PrintWriter pw = [Link](); [Link]("<B>"); Date date = (Date) [Link]("date"); if (date != null) { [Link]("Last access: " + date + "<br>"); } date = new Date(); [Link]("date", date); [Link]("Current date: " + date); } }
=============================================================== 5. Using Servlet Init Method
import import import import [Link].*; [Link].*; [Link].*; [Link].*;
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 { [Link]("text/html"); PrintWriter out = [Link](); [Link]("<HTML>"); [Link]("<HEAD>");
Tested By [Link]
SERVLET EXAMPLES for all major concepts
[Link]("<TITLE>"); [Link]("Using the init Method"); [Link]("</TITLE>"); [Link]("</HEAD>"); [Link]("<BODY>"); [Link]("<H1>Using the init Method</H1>"); [Link](msg); [Link]("</BODY>"); [Link]("</HTML>"); } } <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "[Link] <web-app> <servlet><servlet-name>MyServletName</servlet-name> <servlet-class>MyServlet</servlet-class> </servlet> <servlet-mapping><servlet-name>MyServletName</servlet-name> <url-pattern>/[Link]</url-pattern> </servlet-mapping> </web-app>
=============================================================== 6. Returns any parameters and lists server properties.
import [Link]; import [Link]; import import import import import [Link]; [Link]; [Link]; [Link]; [Link];
public class Properties extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) t hrows ServletException, IOException { PrintWriter out = [Link](); [Link]("<html>"); [Link]("<head>"); [Link]("<title>My First Servlet</title>"); [Link]("</head>"); [Link]("<h2><center>"); [Link]("Information About You</center></h2>"); [Link]("<br>"); [Link]("<center><table border>"); [Link]("<tr>"); [Link]("<td>Method</td>");
Tested By [Link]
SERVLET EXAMPLES for all major concepts
[Link]("<td>" + [Link]() + "</td>"); [Link]("</tr>"); [Link]("<tr>"); [Link]("<td>User</td>"); [Link]("<td>" + [Link]() + "</td>"); [Link]("</tr>"); [Link]("<tr>"); [Link]("<td>Client</td>"); [Link]("<td>" + [Link]() + "</td>"); [Link]("</tr>"); [Link]("<tr>"); [Link]("<td>Protocol</td>"); [Link]("<td>" + [Link]() + "</td>"); [Link]("</tr>"); [Link] e = [Link](); while ([Link]()) { String name = (String) [Link](); [Link]("<tr>"); [Link]("<td>Parameter '" + name + "'</td>"); [Link]("<td>" + [Link](name) + "</td>"); [Link]("</tr>"); } [Link]("</table></center><br><hr><br>"); [Link]("<h2><center>"); [Link]("Server Properties</center></h2>"); [Link]("<br>"); [Link]("<center><table border width=80%>"); [Link] props = [Link](); e = [Link](); while ([Link]()) { String name = (String) [Link](); [Link]("<tr>"); [Link]("<td>" + name + "</td>"); [Link]("<td>" + [Link](name) + "</td>"); [Link]("</tr>"); } [Link]("</table></center>"); [Link]("</html>"); [Link](); } public void init() throws ServletException { ServletConfig config = getServletConfig(); } public void destroy() {
Tested By [Link]
SERVLET EXAMPLES for all major concepts
} }
==============================================================
Servlets and forms
[Link] Post Form Data to Self Servlet
import import import import [Link].*; [Link].*; [Link].*; [Link].*;
public class MyServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse res ponse) throws ServletException, [Link] { [Link]("command: "+[Link]("command")); [Link]("text/html"); [Link] out = [Link](); [Link]("<html><head>"); [Link]("<title>Help Page</title></head><body>"); [Link]("<h2>Please submit your information</h2>"); [Link]("<form method=\"post\" action =\"" + [Link] Path() +"/MyServlet\" >"); [Link]("<table border=\"0\"><tr><td valign=\"top\">"); [Link]("Your first name: </td> <td valign=\"top\">"); [Link]("<input type=\"text\" name=\"firstname\" size=\"20\">") ; [Link]("</td></tr><tr><td valign=\"top\">"); [Link]("Your last name: </td> <td valign=\"top\">"); [Link]("<input type=\"text\" name=\"lastname\" size=\"20\">"); [Link]("</td></tr><tr><td valign=\"top\">"); [Link]("Your email: </td> <td valign=\"top\">"); [Link]("<input type=\"text\" name=\"email\" size=\"20\">"); [Link]("</td></tr><tr><td valign=\"top\">"); [Link]("<input type=\"submit\" value=\"Submit Info\"></td></tr >"); [Link]("</table></form>"); [Link]("</body></html>");
Tested By [Link]
SERVLET EXAMPLES for all major concepts
} public void doPost(HttpServletRequest request, HttpServletResponse r esponse) throws ServletException,[Link]{ Enumeration paramNames = [Link](); String parName; boolean emptyEnum = false; if (! [Link]()) emptyEnum = true; [Link]("text/html"); [Link] out = [Link](); [Link]("<html><head>"); [Link]("<title>Submitted Parameters</title></head><body>"); if (emptyEnum){ [Link]("<h2>Sorry, the request does not contain any paramete rs</h2>"); } else { [Link]("<h2>Here are the submitted parameter values</h2>"); } while([Link]()){ parName = (String) [Link](); [Link]("<strong>" + parName + "</strong> : " + [Link] rameter(parName)); [Link]("<br />"); } [Link]("</body></html>"); } } <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "[Link] <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 [Link]
SERVLET EXAMPLES for all major concepts
</servlet-mapping> </web-app>
2. Get Form Text Field as a Servlet parameter
import [Link].*; import [Link].*; import [Link].*; public class MyServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { [Link]("text/html"); PrintWriter out = [Link](); String name = [Link]("name"); [Link]("<HTML>"); [Link]("<HEAD><TITLE>Hello, " + name + "</TITLE></HEAD>"); [Link]("<BODY>"); [Link]("Hello, " + name); [Link]("</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" "[Link] <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="[Link]"> If you don't mind me asking, what is your name?
Tested By [Link]
SERVLET EXAMPLES for all major concepts
<INPUT TYPE=TEXT NAME="name"><P> <INPUT TYPE=SUBMIT> </FORM> </BODY> </HTML>
===========================================================
3. Servlet Form Processor CheckBox
import [Link].*; import [Link].*; import [Link]; public class MyServlet extends HttpServlet { public void doPost (HttpServletRequest req, HttpServletResponse res) throws IOException { ServletOutputStream out = [Link](); [Link]("text/html"); [Link]("<html><head><title>Basic Form Processor Output</title> </head>"); [Link]("<body>"); [Link]("<h1>Here is your Form Data</h1>"); //extract the form data here String title = [Link]("title"); String name = [Link]("name"); String city = [Link]("city"); String country = [Link]("country"); String tel = [Link]("tel"); String age = [Link]("age"); // extracting data from the checkbox field String[] interests = [Link]("interests"); //output the data into a web page [Link]("Your title is " + title); [Link]("<br>Your name is " + name); [Link]("<br>Your city is " + city); [Link]("<br>Your country is " + country); [Link]("<br>Your tel is " + tel); [Link]("<br>Your interests include<ul> "); for (int i=0;i<[Link]; i++) { [Link]("<li>" + interests[i]); } [Link]("</ul>"); [Link]("<br>Your age is " + age); [Link]("</body></html>"); } } <?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "[Link]
Tested By [Link]
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="[Link]"> 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 [Link]
11
SERVLET EXAMPLES for all major concepts
import import import import [Link].*; [Link].*; [Link].*; [Link].*;
public class MyServlet extends HttpServlet { private Vector entries = new Vector(); private long lastModified = 0; public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { [Link]("text/html"); PrintWriter out = [Link](); 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 { [Link]("<HTML><HEAD><TITLE>Guestbook</TITLE></HEAD>"); [Link]("<BODY>"); } private void printForm(PrintWriter out) throws ServletException { [Link]("<FORM METHOD=POST>"); // posts to itself [Link]("<B>Please submit your feedback:</B><BR>"); [Link]("Your name: <INPUT TYPE=TEXT NAME=name><BR>"); [Link]("Your email: <INPUT TYPE=TEXT NAME=email><BR>"); [Link]("Comment: <INPUT TYPE=TEXT SIZE=50 NAME=comment><BR>"); [Link]("<INPUT TYPE=SUBMIT VALUE=\"Send Feedback\"><BR>"); [Link]("</FORM>"); [Link]("<HR>"); } private void printMessages(PrintWriter out) throws ServletException { String name, email, comment; Enumeration e = [Link](); while ([Link]()) { GuestbookEntry entry = (GuestbookEntry) [Link](); name = [Link]; if (name == null) name = "Unknown user"; email = [Link]; if (name == null) email = "Unknown email"; comment = [Link];
Tested By [Link]
12
SERVLET EXAMPLES for all major concepts
if (comment == null) comment = "No comment"; [Link]("<DL>"); [Link]("<DT><B>" + name + "</B> (" + email + ") says"); [Link]("<DD><PRE>" + comment + "</PRE>"); [Link]("</DL>"); // Sleep for half a second to simulate a slow data source try { [Link](500); } catch (InterruptedException ignored) { } } } private void printFooter(PrintWriter out) throws ServletException { [Link]("</BODY>"); } private void handleForm(HttpServletRequest req, HttpServletResponse res) { GuestbookEntry entry = new GuestbookEntry(); [Link] = [Link]("name"); [Link] = [Link]("email"); [Link] = [Link]("comment"); [Link](entry); // Make note we have a new last modified time lastModified = [Link](); } 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" "[Link] <web-app> <servlet><servlet-name>MyServletName</servlet-name> <servlet-class>MyServlet</servlet-class> </servlet> <servlet-mapping><servlet-name>MyServletName</servlet-name> <url-pattern>/[Link]</url-pattern> </servlet-mapping> </web-app>
========================================================= Tested By [Link] 13
SERVLET EXAMPLES for all major concepts =========================================================
Sessions
Servlet Session Info
import import import import [Link].*; [Link].*; [Link].*; [Link].*; public class MyServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse r esponse) throws ServletException, [Link] { [Link]("text/html"); [Link] out = [Link](); HttpSession session = [Link](); [Link]("<html>"); [Link]("<head>"); [Link]("<title>Simple Session Tracker</title>"); [Link]("</head>"); [Link]("<body>"); [Link]("<h2>Session Info</h2>"); [Link]("session Id: " + [Link]() + "<br><br>"); [Link]( "The SESSION TIMEOUT period is " + [Link] nactiveInterval() + " seconds.<br><br>"); [Link]( "Now changing it to 20 minutes.<br><br>"); [Link](20 * 60); [Link]("The SESSION TIMEOUT period is now " + [Link] axInactiveInterval() + " seconds."); [Link]("</body>"); [Link]("</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 [Link]
14
SERVLET EXAMPLES for all major concepts
throws ServletException, [Link] { doGet(request,response); } }
<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "[Link] <web-app> <servlet><servlet-name>MyServletName</servlet-name> <servlet-class>MyServlet</servlet-class> </servlet> <servlet-mapping><servlet-name>MyServletName</servlet-name> <url-pattern>/[Link]</url-pattern> </servlet-mapping> </web-app>
============================================================== 2. Get Set SessionAttributes in Servlet
import import import import [Link].*; [Link].*; [Link].*; [Link].*;
public class MyServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { [Link]("text/html"); PrintWriter out = [Link](); HttpSession session = [Link](); Integer count = (Integer)[Link]("[Link]"); if (count == null) count = new Integer(1); else count = new Integer([Link]() + 1); [Link]("[Link]", count); [Link]("<HTML><HEAD><TITLE>SessionTracker</TITLE></HEAD>"); [Link]("<BODY><H1>Session Tracking Demo</H1>"); [Link]("You've visited this page " + count + (([Link]() == 1) ? " time." : " times."));
Tested By [Link]
15
SERVLET EXAMPLES for all major concepts
[Link]("<P>"); [Link]("<H2>Here is your session data:</H2>"); Enumeration e = [Link](); while ([Link]()) { String name = (String) [Link](); [Link](name + ": " + [Link](name) + "<BR>"); } [Link]("</BODY></HTML>"); } } <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "[Link] <web-app> <servlet><servlet-name>MyServletName</servlet-name> <servlet-class>MyServlet</servlet-class> </servlet> <servlet-mapping><servlet-name>MyServletName</servlet-name> <url-pattern>/[Link]</url-pattern> </servlet-mapping> </web-app>
2. Get Set Session Value in a Servlet
import import import import [Link].*; [Link].*; [Link].*; [Link].*;
public class MyServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse r esponse) throws ServletException, IOException { [Link]("text/html"); PrintWriter out = [Link](); HttpSession session = [Link](true); Integer counter2 = (Integer) getServletContext().getAttribute ( "counter2"); if (counter2 == null) { counter2 = new Integer(1); } else { counter2 = new Integer([Link]() + 1); } getServletContext().setAttribute("counter2", counter2);
Tested By [Link]
16
SERVLET EXAMPLES for all major concepts
Integer counter = (Integer) [Link]("counter"); if (counter == null) { counter = new Integer(1); } else { counter = new Integer([Link]() + 1); } [Link]("counter", counter); [Link]("<HTML>"); [Link]("<HEAD>"); [Link]("<TITLE>"); [Link]("Using Contexts"); [Link]("</TITLE>"); [Link]("</HEAD>"); [Link]("<BODY>"); [Link]("<H1>Using Contexts</H1>"); [Link]("Welcome! You have been here " + counter + " times. <BR>"); [Link]("Total page accesses: " + counter2 + "<BR>"); if([Link]()){ [Link]("This is a new session.<BR>"); } else { [Link]("This is not a new session.<BR>"); } [Link]("The session ID: " + [Link]() + "<BR>"); [Link]("Last time accessed: " + new Date([Link] cessedTime()) + "<BR>"); [Link]("Creation time: " + new Date([Link] e()) + "<BR>"); [Link]("Timeout length: " + [Link] () + " seconds<BR>"); [Link]("</BODY>"); [Link]("</HTML>"); } } <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "[Link] <web-app> <servlet><servlet-name>MyServletName</servlet-name> <servlet-class>MyServlet</servlet-class> </servlet>
Tested By [Link]
17
SERVLET EXAMPLES for all major concepts
<servlet-mapping><servlet-name>MyServletName</servlet-name> <url-pattern>/[Link]</url-pattern> </servlet-mapping> </web-app>
3. use the Servlet API to manage session information
import [Link]; import [Link]; import import import import import [Link]; [Link]; [Link]; [Link]; [Link];
public class Counter extends HttpServlet { static final String COUNTER_KEY = "[Link]"; public void doGet(HttpServletRequest req, HttpServletResponse resp) t hrows ServletException, IOException { HttpSession session = [Link](true); [Link]("text/html"); PrintWriter out = [Link](); int count = 1; Integer i = (Integer) [Link](COUNTER_KEY); if (i != null) { count = [Link]() + 1; } [Link](COUNTER_KEY, new Integer(count)); [Link]("<html>"); [Link]("<head>"); [Link]("<title>Session Counter</title>"); [Link]("</head>"); [Link]("<body>"); [Link]("Your session ID is <b>" + [Link]()); [Link]("</b> and you have hit this page <b>" + count + "</b> time(s) during this browser session"); [Link]("<form method=GET action=\"" + [Link]() + "\ ">"); [Link]("<input type=submit " + "value=\"Hit page again\">"); [Link]("</form>"); [Link]("</body>"); [Link]("</html>"); [Link](); } }
4. Servlet Session Check
import import import import import public [Link].*; [Link].*; [Link].*; [Link].*; [Link]; class MyServlet extends HttpServlet {
Tested By [Link]
18
SERVLET EXAMPLES for all major concepts
public void doGet(HttpServletRequest request, HttpServletResponse resp onse) throws ServletException, [Link] { HttpSession session = [Link](false); if (session == null){ [Link]("/dbproj/[Link]"); } else { [Link]("/dbproj/[Link]"); } } } <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "[Link] <web-app> <servlet><servlet-name>MyServletName</servlet-name> <servlet-class>MyServlet</servlet-class> </servlet> <servlet-mapping><servlet-name>MyServletName</servlet-name> <url-pattern>/[Link]</url-pattern> </servlet-mapping> </web-app>
=============================================================
CooKie
1. Add Cookie Servlet
import [Link]; import [Link]; import import import import [Link]; [Link]; [Link]; [Link];
Tested By [Link]
19
SERVLET EXAMPLES for all major concepts
import [Link]; public class AddCookieServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse re sponse) throws ServletException, IOException { String data = [Link]("data"); Cookie cookie = new Cookie("MyCookie", data); [Link](cookie); [Link]("text/html"); PrintWriter pw = [Link](); [Link]("<B>MyCookie has been set to"); [Link](data); [Link](); } }
2. Get Cookies Servlet
import [Link]; import [Link]; import import import import import [Link]; [Link]; [Link]; [Link]; [Link];
public class GetCookiesServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse res ponse) throws ServletException, IOException { Cookie[] cookies = [Link](); [Link]("text/html"); PrintWriter pw = [Link](); [Link]("<B>"); for (int i = 0; i < [Link]; i++) { String name = cookies[i].getName(); String value = cookies[i].getValue(); [Link]("name = " + name + "; value = " + value); } [Link](); } }
[Link] Cookie Setter
import import import import [Link].*; [Link].*; [Link].*; [Link].*;
public class MyServlet extends HttpServlet {
Tested By [Link]
20
SERVLET EXAMPLES for all major concepts
public void doGet(HttpServletRequest request, HttpServletResponse r esponse) throws ServletException, [Link] { Cookie cookie = null; //Get an array of Cookies associated with this domain Cookie[] cookies = [Link](); boolean newCookie = false; //Get the 'mycookie' Cookie if it exists if (cookies != null){ for (int i = 0; i < [Link]; 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()); [Link]([Link]()); [Link](maxAge); [Link](cookie); }//end if // get some info about the cookie [Link]("text/html"); [Link] out = [Link](); [Link]("<html>"); [Link]("<head>"); [Link]("<title>Cookie info</title>"); [Link]("</head>"); [Link]("<body>"); [Link]("<h2> Information about the cookie named \"mycookie \"</h2>"); [Link]("Cookie value: "+[Link]()+"<br>"); if (newCookie){ [Link]("Cookie Max-Age: "+[Link]()+"<br>");
Tested By [Link]
21
SERVLET EXAMPLES for all major concepts
[Link]("Cookie Path: "+[Link]()+"<br>"); } [Link]("</body>"); [Link]("</html>"); [Link](); } 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 [Link]().getTime(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, [Link] { doGet(request,response); } } <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "[Link] <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>/[Link]</url-pattern> </servlet-mapping> </web-app>
4. 4. Servlet Cookie Reader Tested By [Link] 22
SERVLET EXAMPLES for all major concepts
import import import import
[Link].*; [Link].*; [Link].*; [Link].*;
public class MyServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse r esponse) throws ServletException, [Link] { Cookie cookie = null; //Get an array of Cookies associated with this domain Cookie[] cookies = [Link](); boolean hasCookies = false; if (cookies != null) hasCookies = true; // display the name/value of each cookie [Link]("text/html"); [Link] out = [Link](); [Link]("<html>"); [Link]("<head>"); [Link]("<title>Cookie information</title>"); [Link]("</head>"); [Link]("<body>"); if (hasCookies){ [Link]("<h2> The name and value of each found cookie</h2>" ); for (int i = 0; i < [Link]; i++){ cookie = cookies[i]; [Link]("Name of cookie #"+(i + 1)+": "+[Link]( )+"<br>"); [Link]("Value of cookie #"+(i + 1)+": "+[Link] e()+"<br><br>"); } } else { [Link]("<h2> This request did not include any cookies< /h2>"); } [Link]("</body>"); [Link]("</html>"); [Link](); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, [Link] {
Tested By [Link]
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" "[Link] <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>/[Link]</url-pattern> </servlet-mapping> </web-app>
5. Get/Set Cookie
import import import import [Link].*; [Link].*; [Link].*; [Link].*;
public class MyServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse r esponse) throws IOException, ServletException { [Link]("text/html"); PrintWriter out = [Link](); [Link]("<HTML>"); [Link]("<HEAD>"); [Link]("<TITLE>"); [Link]("A Web Page"); [Link]("</TITLE>"); [Link]("</HEAD>"); [Link]("<BODY"); Cookie[] cookies = [Link](); boolean foundCookie = false; for(int i = 0; i < [Link]; i++) {
Tested By [Link]
24
SERVLET EXAMPLES for all major concepts
Cookie cookie1 = cookies[i]; if ([Link]().equals("color")) { [Link]("bgcolor = " + [Link]()); foundCookie = true; } } if (!foundCookie) { Cookie cookie1 = new Cookie("color", "cyan"); [Link](24*60*60); [Link](cookie1); } [Link](">"); [Link]("<H1>Setting and Reading Cookies</H1>"); [Link]("This page will set its background color using a co okie when reloaded."); [Link]("</BODY>"); [Link]("</HTML>"); } } <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "[Link] <web-app> <servlet><servlet-name>MyServletName</servlet-name> <servlet-class>MyServlet</servlet-class> </servlet> <servlet-mapping><servlet-name>MyServletName</servlet-name> <url-pattern>/[Link]</url-pattern> </servlet-mapping> </web-app>
6. List Servlet Cookie Information
import [Link]; import [Link]; import import import import import [Link]; [Link]; [Link]; [Link]; [Link];
public class Cookies extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) t hrows ServletException, IOException { [Link]("text/html"); [Link]();
Tested By [Link]
25
SERVLET EXAMPLES for all major concepts
PrintWriter out = [Link](); Cookie cookies[] = [Link](); [Link]("<html>"); [Link]("<head>"); [Link]("<title>Servlet Cookie Information</title>"); [Link]("</head>"); [Link]("<body>"); if ((cookies == null) || ([Link] == 0)) { [Link]("<center><h1>No Cookies found</h1>"); } else { [Link]("<center><h1>Cookies found</h1>"); for (int i = 0; i < [Link]; i++) { Cookie c = cookies[i]; [Link]([Link]() + "::" + [Link]() + "::" + [Link]() + "::" + [Link]() + "<BR/>"); } [Link]("</table></center>"); } [Link]("</body>"); [Link]("</html>"); [Link](); } }
Servlet URL Rewrite
import import import import [Link].*; [Link].*; [Link].*; [Link].*;
public class MyServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse resp onse) throws ServletException, [Link] { [Link]("text/html"); [Link] out = [Link](); String contextPath = [Link](); String encodedUrl = [Link](contextPath + "/default .jsp"); [Link]("<html>"); [Link]("<head>"); [Link]("<title>URL Rewriter</title>"); [Link]("</head>"); [Link]("<body>");
Tested By [Link]
26
SERVLET EXAMPLES for all major concepts
[Link]("<h1>This page will use URL rewriting if necessary< /h2>"); [Link]("Go to the [Link] page <a href=\"" + encodedUr l + "\">here</a>."); [Link]("</body>"); [Link]("</html>"); } public void doPost(HttpServletRequest request, HttpServletResponse re sponse) throws ServletException, [Link] { doGet(request,response); } } <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "[Link] <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>/[Link]</url-pattern> </servlet-mapping> </web-app>
2. URL rewriting
import [Link]; import [Link]; import import import import import [Link]; [Link]; [Link]; [Link]; [Link];
public class CounterRewrite extends HttpServlet {
Tested By [Link]
27
SERVLET EXAMPLES for all major concepts
static final String COUNTER_KEY = "[Link]"; public void doGet(HttpServletRequest req, HttpServletResponse resp) t hrows ServletException, IOException { HttpSession session = [Link](true); [Link]("text/html"); PrintWriter out = [Link](); int count = 1; Integer i = (Integer) [Link](COUNTER_KEY); if (i != null) { count = [Link]() + 1; } [Link](COUNTER_KEY, new Integer(count)); [Link]("<html>"); [Link]("<head>"); [Link]("<title>Session Counter</title>"); [Link]("</head>"); [Link]("<body>"); [Link]("Your session ID is <b>" + [Link]()); [Link]("</b> and you have hit this page <b>" + count + "</b> time(s) during this browser session"); String url = [Link](); [Link]("<form method=GET action=\"" + [Link](url) + "\ ">"); [Link]("<input type=submit " + "value=\"Hit page again\">"); [Link]("</form>"); [Link]("</body>"); [Link]("</html>"); [Link](); } }
Tested By [Link]
28