Sub Page_Load(sender as Object, e as EventArgs) If Not Page.IsPostBack Then ' Default BG color to white to match the way it ' looks when the page first loads. back_red.Value = "FF" back_green.Value = "FF" back_blue.Value = "FF" End If End Sub
println
, Java objects, or XML-to-XHTML
transformation. javax.servlet
and
javax.servlet.http
packages. javax.servlet.Servlet
interface, usually by
extending either javax.servlet.GenericServlet
or
javax.servlet.http.HttpServlet
service()
HttpServlet
you override
doGet()
and doPost()
. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"); out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">"); out.println("<head><title>Hello World</title></head>"); out.println("<body>"); out.println("<h1>Hello World</h1>"); out.println("</body></html>"); } }
HttpServletRequest
has information about the
client, like parameter. HttpServletResponse
is sent back to the client. <html> <head> <title>Introductions</title> </head> <body> <form method="get" action="/servlet/hello"> If you don't mind me asking, what is your name? <input type="text" name="name"/><p/> <input type="submit"/> </form> </body> </html>
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Hello 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"; } }
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); }
doHead()
, instead the
service()
method calls doGet()
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); if (req.getMethod().equals("HEAD")) return; //its really a GET..... } }
index.html picture.png WEB-INF/web.xml WEB-INF/lib/xerces.jar WEB-INF/classes/HelloWorld.class
<?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> hi </servlet-name> <servlet-class> HelloWorld </servlet-class> </servlet> <servlet-mapping> <servlet-name> hi </servlet-name> <url-pattern> /hello.html </url-pattern> </servlet-mapping> </web-app>
HelloWorld
servlet. hi
is also set to handle URLs that
match /hello.html. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SimpleCounter extends HttpServlet { int count = 0; public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); count++; out.println("Since loading, this servlet has been accessed " + count + " times."); } }
If you have not used Java threads recently I suggest you review them. Remember that all threads can have access to the same static variables and even the same objects if the threads can communicate with each other (for example, via a socket or a file). Each thread has a start() method which gets called when it is created and a run() method which does the actual work of the thread.
count++; //Thread 1 count++; //Thread 2 out.println; //Thread 1 out.println; //Thread 2
public synchronized void doGet(HttpServletRequest req, HttpServletResponse res)
PrintWriter out = res.getWriter(); synchronized(this) { count++; out.printl(...); }
PrintWriter out = res.getWriter(); int local_count; synchronized(this) { local_count = ++ count;} out.println(..);
import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class HolisticCounter extends HttpServlet { static int classCount = 0; // shared by all instances int count = 0; // separate for each servlet static Hashtable instances = new Hashtable(); // also shared public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); count++; out.println("Since loading, this servlet instance has been accessed " + count + " times."); // Keep track of the instance count by putting a reference to this // instance in a Hashtable. Duplicate entries are ignored. // The size() method returns the number of unique instances stored. instances.put(this, this); out.println("There are currently " + instances.size() + " instances."); classCount++; out.println("Across all instances, this servlet class has been " + "accessed " + classCount + " times."); } }
init()
is called when the server starts, or is
first requests, or at the request of the server
administrator. getInitParameter("paramname");
destroy()
is called prior to
destruction. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class InitDestroyCounter extends HttpServlet { int count; public void init() throws ServletException { // Try to load the initial count from our saved persistent state FileReader fileReader = null; BufferedReader bufferedReader = null; try { fileReader = new FileReader("InitDestroyCounter.initial"); bufferedReader = new BufferedReader(fileReader); String initial = bufferedReader.readLine(); count = Integer.parseInt(initial); return; } catch (FileNotFoundException ignored) { } // no saved state catch (IOException ignored) { } // problem during read catch (NumberFormatException ignored) { } // corrupt saved state finally { // Make sure to close the file try { if (bufferedReader != null) { bufferedReader.close(); } } catch (IOException ignored) { } } // Default to an initial count of "0" count = 0; } public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); count++; out.println("Since the beginning, this servlet has been accessed " + count + " times."); } public void destroy() { super.destroy(); // entirely optional FileWriter fileWriter = null; PrintWriter printWriter = null; try { fileWriter = new FileWriter("InitDestroyCounter.initial"); printWriter = new PrintWriter(fileWriter); printWriter.println(count); return; } catch (IOException e) { // problem during write // Log the exception. See Chapter 5. } finally { // Make sure to close the file if (printWriter != null) { printWriter.close(); } } } }
init()
to launch a
thread that will run continuously. import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class PrimeSearcher extends HttpServlet implements Runnable { long lastprime = 0; // last prime found Date lastprimeModified = new Date(); // when it was found Thread searcher; // background search thread public void init() throws ServletException { searcher = new Thread(this); searcher.setPriority(Thread.MIN_PRIORITY); // be a good citizen searcher.start(); } public void run() { //do work, say, search for primes. } public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); out.println("The last prime discovered was " + lastprime); out.println(" at " + lastprimeModified); } public void destroy() { searcher.stop(); } }
If-Modified-Since
header, so,
what is the Last-Modified
of a document sent by a
servlet? public long getLastModified(HttpServletRequest req) { return lastprimeModified.getTime() / 1000 * 1000; }
init
parameter values, as in <?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>hi</servlet-name> <servlet-class>HelloWorld</servlet-class> <init-param> <param-name>msg</param-name> <param-value> A can of ASPARAGUS, 73 pigeons, some LIVE ammo, and a FROZEN DAQUIRI!! </param-value> </servlet> </web-app>these can be retrieved with code like
public void init() throws ServletException { //get msg string String msg = getInitParameter("msg"); //Examine all init parameters Enumeration enum = getInitParameterNames(); while (enum.hasMoreElements()){ String name = (String) enum.nextElement();} }
public String ServletConfig.getServletName();
//Return the name of the server public String ServletRequest.getServerName(); //Return the port number for this request public int ServletRequest.getServerPort(); //Return name and version of server software public String ServletContext.getServerInfo(); //Return the value of name server attribute public Object ServletContext.getAttribute(String name);
javax.servlet.context.tempdir
which is a java.io.File
reference to a temp directory. <?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> <context-param> <param-name>rmiregistry</param-name> <param-value>myrmi.jmvidal.cse.sc.edu</param-value> </context-param> <!--servlet elements here--> </web-app>and accessed using
//get the value of name public String ServletContext.getInitParameter(String name); //get an enum over all names public Enumeration ServletContext.getInitParameterNames();
//get the client's IP number public String ServletRequest.getRemoteAddr(); //get the client's host name public String ServletRequest.getRemoteHost();
//get the user's name public String HttpServletRequest.getRemoteUser(); //get the authtype public String HttpServletRequest.getAuthType(); //it is one of BASIC, DIGEST, FORM, CLIENT-CERT.
<form method="get" action="/servlet/search"> Question: <input type="text" name="query"><p> <input type="submit"></p> </form>You can get the value of the
query
parameter with String query = req.getParameter("query");
select
, then you can get all the values with String[] queries = req.getParameterValues("query");
public Enumeration ServletRequest.getParameterNames();
http://server:port/servlet/HelloWorld/someextra/path.html
public String HttpServletRequest.getPathInfo();
public String HttpServletRequest.getPathTranslated();
public URL ServletContext.getResource(String uripath);which you use like
URL url = getServletContext().getResource("/pathto/file.html");
public String HttpServletRequest.getRequestURI();
public String ServletRequest.getScheme();
public String ServletRequest.getProtocol();
//returns the value if it is a string, or null if none public String HttpServletRequest.getHeader(String name); //returns the value as long, -1 if not present, //or throws IllegalArgumentException public long HttpServletRequest.getDateHeader(String name); //returns it as int, -1 if not present, // or throws NumberFormatException public int HttpServletRequest.getIntHeader(String name);
<form action="/servlet/upload" enctype="multipart/form-data" method="post"> Filename: <input type="file" name="file"/><br/> <input type="submit"/> </form>
public BufferedReader ServletRequest.getReader();
public ServletInputStream ServletRequest.getInputStream();
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"); out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">"); out.println("<head><title>Hello World</title></head>"); out.println("<body>"); out.println("<h1>Hello World</h1>"); out.println("</body></html>"); } }
public ServletOutputStream ServletResponse.getOutputStream() throws IOException;
Content-Length
header. It is set with
public void ServletResponse.setContentLength(int len);
public void ServletResponse.setBufferSize(int size);
public int ServletResponse.getBufferSize();
public boolean ServletResponse.isCommitted();
reset()
to clear it. Here is an example:import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class Buffering extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setBufferSize(8 * 1024); // 8K buffer res.setContentType("text/html"); PrintWriter out = res.getWriter(); int size = res.getBufferSize(); // returns 8096 or greater out.println("The client won't see this"); res.reset(); out.println("Nor will the client see this!"); res.reset(); out.println("And this won't be seen if sendError() is called"); if (req.getParameter("important_parameter") == null) { res.sendError(res.SC_BAD_REQUEST, "important_parameter needed"); } } }
public void HttpServletResponse.setStatus(int sc);
Mnemonic | Code | Meaning |
---|---|---|
SC_OK | 200 | Everything's OK. |
SC_NO_CONTENT | 204 | There is nothing to return. |
SC_MOVED_PERMANENTLY | 301 | The requested resource has moved. Put new URL in Location header. |
SC_MOVED_TEMPORARILY | 302 | Temporary move. Put new URL in Location header. |
SC_UNAUTHORIZED | 401 | Not authorized. |
SC_NOT_FOUND | 404 | Document was not found. |
SC_INTERNAL_SERVER_ERROR | 500 | Server is broken. |
Header | Usage |
---|---|
Cache-Control | Either no-cache or no-store (no proxy store) and max-age=fresh for these many seconds |
Connection | keep-alive to keep socket open or close . Servers handle this automagically. |
Retry-After | Date or seconds to wait for server to start working. |
Expires | Date when the documents will(may) change. |
Location | The URL to which the document moved to. |
WWW-Authenticate | Authorization scheme and realm. |
Content-Encoding | Can be gzip or compress . |
public void HttpServletResponse.setHeader(String name, String value);
public void HttpServletResponse.setDateHeader(String name, long date); public void HttpServletResponse.setIntHeader(String name, int value);
Refresh
header:
setHeader("Refresh", "3; URL=http://slashdot.org");
web.xml
<?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> <error-page> <error-code> 400 </error-code> <location> /400.html </location> </error-page> <error-page> <error-code> 404 </error-code> <location> /404.html </location> </error-page> </web-app>
log(String msg); log(String msg, Throwable t);
IOException
, ServletException
or
RuntimeException
(because of service()'s
signature). ServletException
constructor takes a root
cause as argument:
javax.servlet.ServletException(Throwable rootCause); javax.servlet.ServletException(String msg, Throwable rootCause);
public Throwable ServletException.getRootCause();
UnavailableException
is the only one that
subclasses ServletException
. Used to indicate
servlet is unavailable:
javax.servlet.UnavailableException(String msg); //permanently unavailable javax.servlet.UnavailableException(String msg, int seconds); //be back in seconds
IOException
when writing. finally
gets called often. Make sure
to close all other files you might be using. finally
gets executed at the
end of try/catch/finally block, always.import java.io.*; import java.awt.*; import javax.servlet.*; import javax.servlet.http.*; import Acme.JPM.Encoders.GifEncoder; //3rd party public class HelloWorldGraphics extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { ServletOutputStream out = res.getOutputStream(); // binary output! Graphics g = null; try { Image image = new BufferedImage(400, 60, TYPE_INT_BGR); g = image.getGraphics(); // Draw "Hello World!" to the off-screen graphics context g.setFont(new Font("Serif", Font.ITALIC, 48)); g.drawString("Hello World!", 10, 50); // Encode the off-screen image into a GIF and send it to the client res.setContentType("image/gif"); GifEncoder encoder = new GifEncoder(image, out); encoder.encode(); } finally { // Clean up resources if (g != null) g.dispose(); } } }
com.sun.image.codec.jpeg
. Content-Encoding
header to the
appropriate of gzip
(best), compress
,
or deflate
.GZIPOutputStream
or
ZipOutputStream
, make sure to close()
. Accept-Encoding
header that
specifies the acceptable encodings.String name = req.getRemoteUser();to get the name of the user.
<body> <form method="get" action="/servlet/hello"> If you don't mind me asking, what is your name? <input type="text" name="name"/> <input type="hidden" name="id" value="1234"/> <input type="hidden" name="degree" value="bs"/> <input type="submit"> <p/> </form> </body>
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ShoppingCartViewerHidden extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("..."); // Cart items are passed in as the item parameter. String[] items = req.getParameterValues("item"); // Ask if the user wants to add more items or check out. // Include the current items as hidden fields so they'll be passed on. out.println("<form action=\"/servlet/ShoppingCart\" method=\"POST\">"); if (items != null) { for (int i = 0; i < items.length; i++) { out.println("<input type=\"HIDDEN\" name=\"item\" value=\"" + items[i] + "\">"); } } out.println("..."); } }
public Cookie(String name, String value);then add it to the response with
public void HttpServletResponse.addCookie(Cookie cookie);
public Cookie[] HttpServletRequest.getCookies();
public void Cookie.setDomain(String pattern);and the path with
public void Cookie.setPath(String uri);
public void Cookie.setMaxAge(int expiry-second);
public void Cookie.setComment(String comment);
public void Cookie.setValue(String newValue);
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ShoppingCartViewerCookie extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); // Get the current session ID by searching the received cookies. String sessionid = null; Cookie[] cookies = req.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals("sessionid")) { sessionid = cookies[i].getValue(); break; } } } // If the session ID wasn't sent, generate one. // Then be sure to send it to the client with the response. if (sessionid == null) { sessionid = generateSessionId(); Cookie c = new Cookie("sessionid", sessionid); res.addCookie(c); } private static String generateSessionId() { String uid = new java.rmi.server.UID().toString(); // guaranteed unique return java.net.URLEncoder.encode(uid); // encode any special chars } }
javax.servlet.http.HttpSession
object were you
can story any info about him. public HttpSession HttpServletRequest.getSession();if now session then one is created.
public void HttpSession.setAttribute(String name, Object value);and get its value with
public Object HttpSession.getAttribute(String name);
import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class SessionTracker extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); // Get the current session object, create one if necessary HttpSession session = req.getSession(); // Increment the hit count for this page. The value is saved // in this client's session under the name "tracker.count". 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>"); // Display the hit count for this page out.println("You've visited this page " + count + ((count.intValue() == 1) ? " time." : " times.")); 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>"); } }
web.xml
or with
public void HttpSession.setMaxInactiveInterval(int secs);set with care (security vs resource use).
//Has this session just been created? public boolean HttpSession.isNew(); //Invalidate session public void HttpSession.invalidate(); //When was it created? public long HttpSession.getCreationTime();
//return the new url public String HttpServletResponse.encodeURL(String url);
public String HttpSession.getId();
javax.servlet.http.HttpSessionBindingListener
interface. The callbacks you need to implement are
public void HttpSessionBindingListener.valueBound(HttpSessionBindingEvent event); public void HttpSessionBindingListener.valueUnbound(HttpSessionBindingEvent event);
tomcat-users.xml
file: <tomcat-users> <user name="Dilbert" password="dnrc" roles="engineer" /> <user name="Wally" password="iluvalice" roles="engineer,slacker" /> <user name="MrPointyHair" password="MrPointyHair" roles="manager,slacker" /> </tomcat-users>then modify
web.xml
to protect the needed
directories <?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> secret </servlet-name> <servlet-class> SalaryServer </servlet-class> </servlet> <security-constraint> <web-resource-collection> <web-resource-name> SecretProtection </web-resource-name> <url-pattern> /servlet/SalaryServer <!--protect access to these urls--> </url-pattern> <url-pattern> /servlet/secret </url-pattern> <http-method> GET <!--using these methods--> </http-method> <http-method> POST </http-method> </web-resource-collection> <auth-constraint> <role-name> manager <!--only manager can access--> </role-name> </auth-constraint> </security-constraint> <login-config> <auth-method> BASIC <!-- BASIC, DIGEST, FORM, CLIENT-CERT --> </auth-method> <realm-name> Default <!-- optional, only useful for BASIC --> </realm-name> </login-config> <security-role> <role-name> manager </role-name> </security-role> </web-app>
public java.security.Principal HttpServletRequest.getUserPrincipal(); principal.getName();or just check for the correct role with
public boolean HttpServletRequest.isUserRole(String role);
web.xml
to <?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> <!-- ...---> <login-config> <auth-method> FORM <!-- BASIC, DIGEST, FORM, CLIENT-CERT --> </auth-method> <form-login-config> <form-login-page> /loginpage.html </form-login-page> <form-error-page> /errorpage.html </form-error-page> </form-login-config> </login-config>no the server will show
loginpage.html
whenever someone
who has not logged in tries to access a secure
page. loginpage.html
should look something like
<!--The j_* names are important--> <form method="POST" action="j_security_check"> Name: <input type="text" name="j_username" value="" size="15"> Password: <input type="password" name="j_password" value="" size="15"> <input type="submit" value=" OK "> </form>
Authorization:
header to: Authorization: BASIC base64(username:password)
import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import com.oreilly.servlet.Base64Decoder; public class CustomAuth extends HttpServlet { Hashtable users = new Hashtable(); public void init(ServletConfig config) throws ServletException { super.init(config); // Names and passwords are case sensitive! users.put("Wallace:cheese", "allowed"); users.put("Gromit:sheepnapper", "allowed"); users.put("Penguin:evil", "allowed"); } public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); // Get Authorization header String auth = req.getHeader("Authorization"); // Do we allow that user? if (!allowUser(auth)) { // Not allowed, so report he's unauthorized res.setHeader("WWW-Authenticate", "BASIC realm=\"users\""); res.sendError(res.SC_UNAUTHORIZED); // Could offer to add him to the allowed user list } else { // Allowed, so show him the secret stuff out.println("Top-secret stuff"); } } // This method checks the user information sent in the Authorization // header against the database of users maintained in the users Hashtable. protected boolean allowUser(String auth) throws IOException { if (auth == null) return false; // no auth if (!auth.toUpperCase().startsWith("BASIC ")) return false; // we only do BASIC // Get encoded user and password, comes after "BASIC " String userpassEncoded = auth.substring(6); // Decode it, using any base 64 decoder (we use com.oreilly.servlet) String userpassDecoded = Base64Decoder.decode(userpassEncoded); // Check our user list to see if that user and password are "allowed" if ("allowed".equals(users.get(userpassDecoded))) return true; else return false; } }
import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class LoginHandler extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); // Get the user's account number, password, and pin String account = req.getParameter("account"); String password = req.getParameter("password"); String pin = req.getParameter("pin"); // Check the name and password for validity if (!allowUser(account, password, pin)) { out.println("...Access Denied..."); } else { // Valid login. Make a note in the session object. HttpSession session = req.getSession(); session.setAttribute("logon.isDone", account); // just a marker object // Try redirecting the client to the page he first tried to access try { String target = (String) session.getAttribute("login.target"); if (target != null) { res.sendRedirect(target); return; } } catch (Exception ignored) { } // Couldn't redirect to the target. Redirect to the site's home page. res.sendRedirect("/"); } } protected boolean allowUser(String account, String password, String pin) { return true; // trust everyone } }
web.xml
file <security-constraint> <!-- .... ---> <user-data-constraint> <transport-guarantee> CONFIDENTIAL </transport-guarantee> </user-data-constraint> </security-constraint>
public boolean ServletRequest.isSecure();
ServletContext
cannot be use to store
state, for the same reason. HttpSession
should
implement java.io.Serializable
. getServletContext()getResource()
to read files. <distributable/>
in web.xml
web.xml
.web.xml
, so
init parameters cannot be used for him. <env-entry> <!--> <description>Send pincode by mail</description> <!--used as part of the JNDI lookup--> <env-entry-name>mainPincode</env-entry-name> <!--default value--> <env-entry-value>false</env-entry-value> <!--the FQDN of the entry--> <env-entry-type>java.lang.Boolean</env-entry-type> </env-entry>
<ejb-ref> <description>Cruise ship cabin</description> <ejb-ref-name>ejb/CabinHome</ejb-ref-name> <!--Entity or Session: type of EJB component--> <ejb-ref-type>Entity</ejb-ref-type> <home>com.titan.cabin.CabinHome</home> <remote>com.titan.cabin.Cabin</remote> </ejb-ref>then the servlet can get a reference to it with:
InitialContext initCtx = new InitialContext(); Object ref = initCtx.lookup("java:comp/env/ejb/CabinHome"); CabinHome home = (CabinHome) PortableRemoteOject .narrow(ref, CabinHome.class);
import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import org.apache.ecs.*; import org.apache.ecs.html.*; public class ECSHello extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); Document doc = new Document(); doc.appendTitle("Testing ECS"); doc.appendBody(new Big("Hello!")) .appendBody(new P()) .appendBody("The current time is " + new Date()); doc.output(out); } }
<html> <head><title>Hello</title></head> <body> <p> One way is by using an expression: <%= request.getParameter("name") %> </p> <p> Another is by using a scriplet: <% //scriptlet example if (request.getParameter("name") == null) { out.println("Hello World"); } else { out.println("Hello, " + request.getParameter("name")); } %> </p> <p> Finally, there are the declarations: <p> <%! /**Instance variable for this servlet */ private int counter = 0; /**Member function for this servlet */ private String randomNumber() { return(Math.random().toString()); } %> now call it: <%= randomNumber()%=> </body></html>
<%@ directive attribute="value" %>were the main directives are
page
lets you import classes, set content type, and other servlet costumizations.include
lets you insert a file inte the JSP at compile time. taglib
defines custom markup tags. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>The import Attribute</TITLE> <LINK REL=STYLESHEET HREF="JSP-Styles.css" TYPE="text/css"> </HEAD> <BODY> <H2>The import Attribute</H2> <%-- JSP page Directive --%> <%@ page import="java.util.*,coreservlets.*" %> <%-- JSP Declaration --%> <%! private String randomID() { int num = (int)(Math.random()*10000000.0); return("id" + num); } private final String NO_VALUE = "<I>No Value</I>"; %> <%-- JSP Scriptlet --%> <% String oldID = CookieUtilities.getCookieValue(request, "userID", NO_VALUE); if (oldID.equals(NO_VALUE)) { String newID = randomID(); Cookie cookie = new LongLivedCookie("userID", newID); response.addCookie(cookie); } %> <%-- JSP Expressions --%> This page was accessed on <%= new Date() %> with a userID cookie of <%= oldID %>. </BODY></HTML>
<%@ page contentType="application/vnd.ms-excel" %> <%@ page pageEncoding="Shift_JIS" %>
<%@ page session="true" %> <%-- Default --%> <%@ page session="false" %>
<%@ page buffer="sizekb" %> <%@ page buffer="none" %>
<%@ page errorPage="Relative URL" %>
jsp:include
<jsp:include page="bios/cheng-yinghua.jsp" /> <jsp:include page="/templates/footer.jsp" />
<jsp:include page="/fragments/StandardHeading.jsp"> <jsp:param name="bgColor" value="YELLOW" /> </jsp:include>
<%@ include file="Relative URL" %>
<%@ page import="HelloBean" %> <jsp:useBean id="hello" class="HelloBean"> <jsp:setProperty name="hello" property="name" param="name"/> </jsp:useBean> <HTML> <HEAD><TITLE>Hello</TITLE></HEAD> <BODY> <H1> Hello, <jsp:getProperty name="hello" property="name" /> </H1> </BODY> </HTML>with the bean defined as
public class HelloBean { private String name = "World"; public void setName(String name) { this.name = name; } public String getName() { return name; } }
id
in the useBean
but by name
in the get/setProperty
. <.. property="propertyname"
param="paramName">
to set propertyname to some
param's value<.. property="propertyname"
value="constant">
to set it to a constant.package mywebapp; /** A simple bean that has a single String property * called message. */ public class StringBean { private String message = "No message specified"; public String getMessage() { return(message); } public void setMessage(String message) { this.message = message; } }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>Using JavaBeans with JSP</TITLE> <LINK REL=STYLESHEET HREF="JSP-Styles.css" TYPE="text/css"> </HEAD> <BODY> <TABLE BORDER=5 ALIGN="CENTER"> <TR><TH CLASS="TITLE"> Using JavaBeans with JSP</TABLE> <jsp:useBean id="stringBean" class="coreservlets.StringBean"/> <OL> <LI>Initial value (from jsp:getProperty): <I><jsp:getProperty name="stringBean" property="message" /></I></LI> <LI>Initial value (from JSP expression): <I><%= stringBean.getMessage() %></I></LI> <LI><jsp:setProperty name="stringBean" property="message" value="Best string bean: Fortex" /> Value after setting property with jsp:setProperty: <I><jsp:getProperty name="stringBean" property="message" /></I> <LI><% stringBean.setMessage("My favorite: Kentucky Wonder"); %> Value after setting property with scriptlet: <I><%= stringBean.getMessage() %></I> </OL> </BODY></HTML>
...?name=july
you can set it with:
<jsp:setProperty name="customer" property="firstName" param="name" /> or, if the bean has the correct property names: <jsp:setProperty name="customer" property="name"/> more generally, set all properties to their respective param values with <jsp:setProperty name="customer" property="*"/>
<jsp:useBean ... scope="page" />
bean lives for this page only, default. <jsp:useBean ... scope="request" />
bean is attached to request
. Could be shared via include
<jsp:useBean ... scope="session" />
also attached to HttpSession
object.<jsp:useBean ... scope="application" />
also atteched to ServletContext
.package coreservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; /** Servlet that reads a customer ID and displays * information on the account balance of the customer * who has that ID. */ public class ShowBalance extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Fill up the bean BankCustomer customer = BankCustomer.getCustomer(request.getParameter("id")); String address; //Use a different view depending on the customer. // if (customer == null) { address = "/bank-account/UnknownCustomer.jsp"; } else if (customer.getBalance() < 0) { address = "/bank-account/NegativeBalance.jsp"; request.setAttribute("badCustomer", customer); } else if (customer.getBalance() < 10000) { address = "/bank-account/NormalBalance.jsp"; request.setAttribute("regularCustomer", customer); } else { address = "/bank-account/HighBalance.jsp"; request.setAttribute("eliteCustomer", customer); } //Forward control to the .jsp page RequestDispatcher dispatcher = request.getRequestDispatcher(address); dispatcher.forward(request, response); } }
package coreservlets; import java.util.*; /** Bean to represent a bank customer. */ public class BankCustomer { private String id, firstName, lastName; private double balance; public BankCustomer(String id, String firstName, String lastName, double balance) { this.id = id; this.firstName = firstName; this.lastName = lastName; this.balance = balance; } public String getId() { return(id); } public String getFirstName() { return(firstName); } public String getLastName() { return(lastName); } public double getBalance() { return(balance); } public double getBalanceNoSign() { return(Math.abs(balance)); } public void setBalance(double balance) { this.balance = balance; } // Makes a small table of banking customers. for Testing purposes. private static HashMap customers; static { customers = new HashMap(); customers.put("id001", new BankCustomer("id001", "John", "Hacker", -3456.78)); customers.put("id002", new BankCustomer("id002", "Jane", "Hacker", 1234.56)); customers.put("id003", new BankCustomer("id003", "Juan", "Hacker", 987654.32)); } /** Finds the customer with the given ID. * Returns null if there is no match. */ public static BankCustomer getCustomer(String id) { return((BankCustomer)customers.get(id)); } }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>Your Balance</TITLE> <LINK REL=STYLESHEET HREF="/bank-support/JSP-Styles.css" TYPE="text/css"> </HEAD> <BODY> <H1>Your Balance</H1> <P> <IMG SRC="/bank-support/Money.gif" ALIGN="RIGHT"/> <jsp:useBean id="regularCustomer" type="coreservlets.BankCustomer" scope="request" /> <UL> <LI>First name: <jsp:getProperty name="regularCustomer" property="firstName" /> <LI>Last name: <jsp:getProperty name="regularCustomer" property="lastName" /> <LI>ID: <jsp:getProperty name="regularCustomer" property="id" /> <LI>Balance: $<jsp:getProperty name="regularCustomer" property="balance" /> </UL> </BODY> </HTML>
scope="request"
so bean
only lasts for that one request. scope="session"
and
scope="application"
for longer-lasting
beans. <% String destination; if (Math.random() > 0.5) { destination = "/examples/page1.jsp"; } else { destination = "/examples/page2.jsp"; } %> <jsp:forward page="<%= destination %>" />
include
: String firstTable, secondTable, thirdTable; if (someCondition) { firstTable = "/WEB-INF/Sports-Scores.jsp"; secondTable = "/WEB-INF/Stock-Prices.jsp"; thirdTable = "/WEB-INF/Weather.jsp"; } else if (...) { ... } RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/Header.jsp"); dispatcher.include(request, response); dispatcher = request.getRequestDispatcher(firstTable); dispatcher.include(request, response); dispatcher = request.getRequestDispatcher(secondTable); dispatcher.include(request, response); dispatcher = request.getRequestDispatcher(thirdTable); dispatcher.include(request, response); dispatcher = request.getRequestDispatcher("/WEB-INF/Footer.jsp"); dispatcher.include(request, response);
jsp:useBean
and
jsp:getProperty
in your .jsp ${expression}
. That is${name}
<%= pageContext.findAttribute("name") %>
PageContext
, HttpServletRequest
, HttpSession
, and ServletContext
, in that order.package coreservlets; /** Servlet that creates some scoped variables (objects stored * as attributes in one of the standard locations). Forwards * to a JSP page that uses the expression language to * display the values. */ import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ScopedVars extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("attribute1", "First Value"); HttpSession session = request.getSession(); session.setAttribute("attribute2", "Second Value"); ServletContext application = getServletContext(); application.setAttribute("attribute3", new java.util.Date()); request.setAttribute("repeated", "Request"); session.setAttribute("repeated", "Session"); application.setAttribute("repeated", "ServletContext"); RequestDispatcher dispatcher =request.getRequestDispatcher("/el/scoped-vars.jsp"); dispatcher.forward(request, response); } }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD><TITLE>Accessing Scoped Variables</TITLE> <LINK REL=STYLESHEET HREF="/el/JSP-Styles.css" TYPE="text/css"> </HEAD> <BODY> <H1>Accessing Scoped Variables</H1> <UL> <LI><B>attribute1:</B> ${attribute1} <!--First value--> <LI><B>attribute2:</B> ${attribute2} <!--Second value--> <LI><B>attribute3:</B> ${attribute3} <!-- the date--> <LI><B>Source of "repeated" attribute:</B> ${repeated} <!-- Request --> </UL> </BODY></HTML>
customer
then you can${customer.firstName}
firstName
is a property of the customer
bean.
session.setAttribute("customer", customerBean);
${customer["firstName"]}
List
, or Map
you can also use${customer["firstName"]}
${names[0]}
something.do
Action
)
execute
method on that class is executed,
it is passed a form beanbean:write
This talk available at http://jmvidal.cse.sc.edu/talks/servlets/
Copyright © 2009 José M. Vidal
.
All rights reserved.
04 February 2008, 04:00PM