Saturday, 29 October 2011

Servlets FAQ -Part4


How do I use Session Tracking? That is, how can I maintain "session scope data" between servlets in the same application?
Location: http://www.jguru.com/faq/view.jsp?EID=151
Created: Sep 3, 1999 Modified: 2000-09-10 10:49:31.243
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

Session Tracking is one of the most powerful features of Servlets and JSP. Basically, the servlet engine takes care of using Cookies in the right way to preserve state across successive requests by the same user. Your servlet just needs to call a single method (getSession) and it has access to a persistent hashtable of data that's unique to the current user. Way cool.
See section 2.3 of the Servlet Essentials tutorial (http://www.novocode.com/doc/servlet-essentials/) . Also see The Session Tracking API (http://webreview.com/wr/pub/1999/01/08/bookshelf/) , excerpted from Java Servlet Programming (http://www.oreilly.com/catalog/jservlet/) by Jason Hunter (http://webreview.com/wr/pub/au/Hunter_Jason).
A point I haven't seen emphasized enough is that you should only add objects that are serializable to an <mono>HttpSession</mono>. Specifically, a JDBC Connection object is not serializable, so should not be added to the session (despite the example in Jason Hunter's otherwise admirable Java Servlet Programming). If you'd like to associate a connection with a session, then store some arbitrary, unique handle in the session, then use that to key off your own hashtable of connections. (Make sure upon retrieval that the returned connection is not null, and if it is, create a new connection!)
The reason is that sessions may, at the whim of the server, be swapped out to disk, in order to save memory or reboot the server. This behavior can be disabled by setting a configuration parameter in your server or servlet engine. (I can't remember offhand what these are -- please email me if you know.) From the spec:
Some servlet engine implementations will persist session data or distribute it amongst multiple network nodes. For an object bound into the session to be distributed or persisted to disk, it must implement the Serializable interface.
Comments and alternative answers
Also see the FAQ What servlet code corresponds to...
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 21, 2000
Also see the FAQ What servlet code corresponds to the various "scope" values for the <jsp:useBean> tag? .

Re: Also see the FAQ What servlet code corresponds to...
Author: Aditya Sharma (http://www.jguru.com/guru/viewbio.jsp?EID=1151271), Mar 10, 2004
Sorry i feel it is just an explanation by words.A small illustration of code for session tracking will help

Re[2]: Also see the FAQ What servlet code corresponds to...
Author: Link Tree (http://www.jguru.com/guru/viewbio.jsp?EID=1212794), Nov 24, 2004
Very simple code - let say that the
public void doPost(HttpServletRequest request, HttpServletResponse response){
...
//lets take the session obj
HttpSession session = request.getSession(true);
//now let us take the user name assosiated with this session
String currUserLogin = (String) session.getAttribute("currentUserLogin")
...
//now we do the work according to the user name
doSomeWork(currUserLogin);
...
 
}
You should do the same thing in the login servlet where you take the user name and use the addAttribute() of the session obj.

what about the "jsessionid" added to keep the session ?
Author: M. washu (http://www.jguru.com/guru/viewbio.jsp?EID=1217388), Dec 21, 2004
Hi all,
Is there a way to include jsessionid in a hidden field (in a form) rather than in the URL (by the URL rewriting mechanism ) ? I saw that HttpSessionContext class was deprecated for security reason, but for security reasons too i would like to know if there is a way to prevent the jessionid from being logged in the HTTP server log files (of course without using cookies) ? Thanks in advance.
How can I detect whether the user accepted my cookie?
Location: http://www.jguru.com/faq/view.jsp?EID=152
Created: Sep 3, 1999 Modified: 2000-09-06 16:35:12.955
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

Here's a clever trick: use a redirect. Drop a cookie on the HttpServletResponse object, then call response.sendRedirect() to a "phase two" servlet. The "phase two" servlet then tests whether the cookie was sent back to it. If so, that means the user accepted the cookie the first time; if not, it means that either the client rejected the cookie, or the browser doesn't support cookies.
Note that this technique only works if the "phase two" servlet is hidden from the user; if the user can jump directly to the test phase, then the servlet can't tell the difference between newly-arrived clients and cookie-unfriendly clients. That means you should send a redirect from the test phase, to make sure the user doesn't have a chance to bookmark the test phase's URL.
Alex Chaffee (http://www.stinky.com/alex/, alex@jguru.com) has written a Servlet that demonstrates this technique called CookieDetector (http://www.purpletech.com/code/CookieDetector.html)
How do I integrate HTML design into my Servlet?
Location: http://www.jguru.com/faq/view.jsp?EID=153
Created: Sep 3, 1999 Modified: 2001-01-15 07:31:27.091
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

The question can be rephrased, "How can I design a work flow that incorporates HTML designers and programmers to build a dynamically generated web site that will keep expanding and growing over time?" This is a special case of the intractable Content Management Problem of the Web in general. The real problem is to allow HTML designers (that is, humans) to use their favorite HTML editing tools without learning Java, and to allow marketing people (arguably humans) to change the look of the site on a whim, without having to alter the database access code inside the servlet. (And vice versa -- to alter the business logic and data access without altering the user interface.)
See my article at Servlet Central (http://www.servletcentral.com/1998-12/designprocess.dchtml) for an expansion on these themes.
There are many, many possibilities... The list below is not complete, but should give you some guidelines.
A. Hardcode HTML. You can just put HTML inside of print statements in your Servlet's doGet() or doPost() method.
Pro: easy to code, easy to understand for the programmer.
Con: difficult to understand for the designer; when a change has to be made, the programmer has to wait for the designer to finish her HTML, then re-hard-code it all back into print statements, then make sure the generated HTML actually does what the original HTML did. Basically, good for a hello world servlet, not good for a real web site.

B. Server Side Includes (SSI). Use the <SERVLET> tag inside your HTML file (and rename it .shtml). The HTML designers will make pretty pages; your servlets will output small pieces of text that get spliced in to the web page by the server.
Pro: separates UI (HTML) and code.
Con: You have two possible end paths with SSI: either your servlet outputs many tiny bits of text with no HTML tags, or your servlet outputs a big bunch of text with embedded HTML tags. In the first case, your code can't take advantage of its knowledge of the structure of the data -- for example, you can't format an HTML table from a database. In the second case, you're back to hardcoding HTML, thus making it hard to change the look of your pages.

C. Presentation Templates. This is a good way to put common navigation elements (button bar, credits, etc) on all of your pages. The technology is built in to the Java Web Server, and implemented by several (though not all) of the servlet engines.
Pro: you don't have to enter in the same common HTML for all the countless pages in your web site.
Con: your servlet code still has to hardcode HTML if it wants to be powerful (see item B, SSI).

D. JSP Java Server Pages. You write files in HTML format, and embed actual Java code inside the HTML. This is kind of like using JavaScript, only it's on the server, and it's real Java. This is directly parallel to Microsoft's ASP.
Pro: it's really cool; you only need a single file to do both UI and layout code; you don't have to type "println" so much.
Con: if you do anything interesting, then your HTML designers will get really confused looking at the interlaced Java and HTML code -- so make sure to put the complicated code inside a JavaBean where it belongs, not in the JSP page.

The new version of the JSP spec has lots of features for integrating with JavaBeans, which is a great way to separate user interface (JSP) from data and business logic (beans). See also the JSP FAQ (see our References section for a link).
Halcyon Software has a product called Instant ASP, which allows you to execute Microsft IIS-style ASPs (including code in VBScript, Jscript, Perl, Java, and JavaScript) in any Servlet Engine. Also Live Software has CF_Anywhere, which executes Cold Fusion CFML pages. See the References section for links.
E. Write your own page parser. If for some reason you're not happy with the standard mechanisms for doing templates (see B-D above), you can always write your own parser. Seriously. It's not rocket science.
F. HTML Object Model Class Libraries e.g. htmlKona, XML. With these class libraries, you write code and build an object model, then let the objects export HTML. This doesn't really work for complicated layouts -- and forget about letting your designer use an HTML editor -- but it can be useful when you have a highly dynamic site generating HTML, and you want to automate the process. Unfortunately, you still have to learn HTML, if only to understand and validate the output. See the References section of this FAQ for a listing of some class libraries that can help.
G. Do it all yourself Develop a database-driven content management system. Think C|Net. It has a lot of standard content, but the database is king. HTML designers have little pieces of the page that they can play with, but ultimately they're just putting content into a database, and the site (servlet) is generating every page request dynamically. This sort of system is very difficult to design and build, but once you've built it, it can really pay off -- but only if you have dozens of writers, editors, designers, and programmers all working on the same site on an ongoing basis.
For a brief list of alternate page template systems, see the References section of this FAQ. 

No comments: