This document was uploaded by user and they confirmed that they have the permission to share
it. If you are author or own the copyright of this book, please report to us by using this DMCA
report form. Report DMCA
Overview
Download & View Servlets Faq From Jguru as PDF for free.
Servlets FAQ From jGuru Generated Sep 13, 2005 2:17:14 PM Location: http://www.jguru.com/faq/Servlets Ownership: http://www.jguru.com/misc/user-agree.jsp#ownership. How do I set my CLASSPATH for servlets? Location: http://www.jguru.com/faq/view.jsp?EID=141 Created: Sep 3, 1999 Modified: 2001-05-05 14:19:15.228 Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) That depends. For developing servlets, just make sure that the JAR file containing javax.servlet.* is in your CLASSPATH, and use your normal development tools (javac and so forth). • •
For JSDK: JSDK_HOME/lib/jsdk.jar For Tomcat: TOMCAT_HOME/lib/servlet.jar
For running servlets, you need to set the CLASSPATH for your servlet engine. This varies from engine to engine. Each has different rules for how to set the CLASSPATH, which libraries and directories should be included, and which libraries and directories should be excluded. Note: for engines that do dynamic loading of servlets (e.g. JRun, Apache Jserv, Tomcat), the directory containing your servlet class files shoud not be in your CLASSPATH, but should be set in a config file. Otherwise, the servlets may run, but they won't get dynamically reloaded. The Servlets 2.2 spec says that the following should automatically be included by the container, so you shouldn't have to add them to your CLASSPATH manually. (Classloader implementations are notoriously buggy, though, so YMMV.) • •
classes in the webapp/WEB-INF/classes directory JAR files in the webapp/WEB-INF/lib directory
This applies to webapps that are present on the filesystem, and to webapps that have been packaged into a WAR file and placed in the container's "webapps" directory. (e.g. TOMCAT_HOME/webapps/myapp.war) The Complete CLASSPATH Guide for Servlets (http://www.meangene.com/java/classpath.html) by Gene McKenna ([email protected]) has detailed instructions on how to set your CLASSPATH for JavaWebServer and JRun. See also http://www.jguru.com/faq/view.jsp?EID=413601 Comments and alternative answers
Important precision : Under Apache (at least with... Author: Denis BUCHER (http://www.jguru.com/guru/viewbio.jsp?EID=7742), Jan 22, 2000
Important precision : Under Apache (at least with jserv under Linux) you SHOULD NOT put this in any system path, as it won't work. You must put the new path into jserv.properties file, that you located maybe into your apache config dir !!! I've found it simpler to just copy the JAR file to... Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Jun 15, 2000 I've found it simpler to just copy the JAR file to the extensions directory of your runtime: jre/lib/ext under your JDK directory, as in: c:\jdk1.3\jre\lib\ext If you are using JRun (atleast with v2.3.3), adding... Author: sharad gupta (http://www.jguru.com/guru/viewbio.jsp?EID=100198), Jul 21, 2000 If you are using JRun (atleast with v2.3.3), adding servlet classes in system path won't work. Instead add the path in jsm.properties file. Unfortunately, Jaz' extension solution doesn't work... Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Sep 17, 2000 Unfortunately, Jaz' extension solution doesn't work for some JARs, notably XML parsers. I'm not exactly sure why; perhaps it's package name collision. The webapp solution (WEB-INF/lib) is preferred. I would not hesitate to have a static block in one... Author: Aprameya Paduthonse (http://www.jguru.com/guru/viewbio.jsp?EID=4707), Feb 1, 2001 I would not hesitate to have a static block in one of my early loaded servlets to list the environment parameters static { Properties envProps = System.getProperties(); System.out.println("__________________________ BEGIN JAVA SETTINGS _______________________________"); for (Enumeration e = envProps.propertyNames() ; e.hasMoreElements() ;) { String prop = (String)e.nextElement(); System.out.println(prop + " : " + envProps.getProperty(prop)); } System.out.println("_____________________________END JAVA SETTINGS _______________________________"); }
view this Author: kumar varma (http://www.jguru.com/guru/viewbio.jsp?EID=1225116), Feb 4, 2005 along with classpath explanation can you please give us details about servletapi.jar,tools.jar,etc.? Is it the "servlets" directory or the "servlet" directory? Location: http://www.jguru.com/faq/view.jsp?EID=142 Created: Sep 3, 1999 Modified: 1999-12-22 11:09:48.603 Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) For Java Web Server: • •
on the file system, it's "servlets" c:\JavaWebServer1.1\servlets\DateServlet.class in a URL path, it's "servlet" http://www.stinky.com/servlet/DateServlet
Other servlet engines have their own conventions. Usually on the file system it's "servlets" and in a URL it's "/servlet" (which is an alias or virtual path). Comments and alternative answers
It depends on your mapping. Virtual path could be ... Author: Roceller Alvarez (http://www.jguru.com/guru/viewbio.jsp?EID=41828), Apr 28, 2000 It depends on your mapping. Virtual path could be different from the real path. Re: It depends on your mapping. Virtual path could be ... Author: Tim Urberg (http://www.jguru.com/guru/viewbio.jsp?EID=510070), Oct 17, 2001 If you have Tomcat the directory will be: TOMCAT_HOME/webapps/ROOT/WEB-INF/classes If you're running JRun it will be: C:\Program Files\Allaire\JRun\servers\default\default-app\WEB-INF\classes I hope that helps Why doesn't my servlet work inside a tag? Location: http://www.jguru.com/faq/view.jsp?EID=143 Created: Sep 3, 1999 Modified: 2000-05-21 14:36:17.445 Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)
If you use your servlet inside an SSI, you must use res.getOutputStream() and not res.getWriter(). Check the server error logs for more details. Comments and alternative answers
Does anyone here have any experience getting <s... Author: Slim Whitman (http://www.jguru.com/guru/viewbio.jsp?EID=29020), Mar 27, 2000 Does anyone here have any experience getting <servlet> tags to work under Netscape Enterprise Server version 4? (I have service pack 3) I don't get any errors, but it's as if the server never parses the servlet tag. Parse HTML is turned on in the server, without using the exec tag, and for all html files. (instead of shtml) I'm not quite sure about this, but I believe that only... Author: Roceller Alvarez (http://www.jguru.com/guru/viewbio.jsp?EID=41828), Apr 28, 2000 I'm not quite sure about this, but I believe that only works on JRUN. Jason Hunter's Servlet book was a defacto when it was... Author: Matt Woody (http://www.jguru.com/guru/viewbio.jsp?EID=36408), May 12, 2000 Jason Hunter's Servlet book was a defacto when it was released because in 1998. He, under O'Reilly, released the best servlet book to date. Because he used the JavaWebServer in all his examples, he frequently used the <servlet> tag. The <servlet> tag is NOT a part of the Servlet API. It was simply a cool thing that JavaWebServer supported. I would suggest that you look towards JSP if you like that idea of combining HTML and Servlets. Otherwise you could create your own utilities to parse html documents, extract syntax within <servlet> and , write to a different file, compile it, and then somehow tie the compiled code and the html together. Another option would be to parse an html document, inverse the outlying html and the syntax within <servlet>, and then compile that. I have quite often pondered doing this. How do I support both GET and POST protocol from the same Servlet? Location: http://www.jguru.com/faq/view.jsp?EID=144 Created: Sep 3, 1999 Modified: 2000-08-10 10:04:27.869 Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) The easy way is, just support POST, then have your doGet method call your doPost method:
Note that implementing the <mono>service() method is usually not what you want to do, since HttpServlet provides its own implementation of <mono>service() that turns around and calls <mono>doGet(), doPost(), etc. Lee Crocker ([email protected]): "It's probably cleaner not to override <mono>service() when extending HttpServlet. The existing service method just calls <mono>doGet(), <mono>doPost(), etc. as appropriate, so you can certainly override it if you feel like it, but then you wind up not only treating GET and POST identically, but also all other HTTP commands, like HEAD, TRACE, and OPTIONS. If you want GET and POST to do the same thing, just have <mono>doGet() and <mono>doPost() call the same private method that does all the work." See also: • • •
What is the difference between the doGet and doPost methods? How does one choose between overriding the doGet(), doPost(), and service() methods? What is the difference between POST and GET methods? What about PUT, DELETE, TRACE, OPTIONS, and HEAD?
Comments and alternative answers
I created a servlet, from which I usually extend, by... Author: Nicola Ken Barozzi (http://www.jguru.com/guru/viewbio.jsp?EID=39153), Apr 23, 2000 I created a servlet, from which I usually extend, by making a new method that gets called by doGet() and doPost() and handles error handling. Apart from that it is a normal HttpServlet. CODE: /** * Copyright: Copyright (c) 2000 * @author Nicola Ken Barozzi */ import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public abstract class WebAppServlet extends HttpServlet { public void init(ServletConfig config) throws ServletException { super.init(config); }
Re: I created a servlet, from which I usually extend, by... Author: Nirav Patel (http://www.jguru.com/guru/viewbio.jsp?EID=424727), May 18, 2001 Exactly... The same happens when you use an IDE such as IBM Visual Age for Java. When you create a new Servlet, Visual Age for Java automatically creates the init(), doGet(..), doPost(..), and performTask(..) method. It also invokes the performTask(..) method from within the doGet(..) and doPost(..) methods. So, now when the user invokes either of the doGet() or doPost() method from the HTML Form using GET and POST, the query is automatically redirected to performTask(..) method. Re: I created a servlet, from which I usually extend, by... Author: Ajay P (http://www.jguru.com/guru/viewbio.jsp?EID=1234517), Mar 24, 2005 Hi! When i am trying to compile the code using ApacheTomcat on IE i am getting the entire code as an output display. How am i suppose to run this servlet? Should i be saving the code as WebAppServlet.html? Help me out with this.If i am conceptually wrong then please tell me as what concept is involved with the execution. Thank you. Re[2]: I created a servlet, from which I usually extend, by... Author: Ajay P (http://www.jguru.com/guru/viewbio.jsp?EID=1234517), Mar 24, 2005 Hey i'm sorry.I need to store it in a java file. I don know as where i kept my brain that time. Its fine now. No need for any reply to the previous message. Thank you.
How do I fully shut down the server? Location: http://www.jguru.com/faq/view.jsp?EID=145 Created: Sep 3, 1999 Modified: 1999-12-22 11:10:54.113 Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) For JWS, under Windows, pressing control-C doesn't fully shut down the server. You should use the Admin Tool and click "Shut Down". (Or you can hit ctl-alt-del, find "JREW" in the list, and "End Task".) Comments and alternative answers
How do I fully shut down the server? Author: Rajan Kumar (http://www.jguru.com/guru/viewbio.jsp?EID=416254), May 6, 2001 You can shut down the JWS from admin tool; or alternativly by going to NT services and "stop" the "javawebserver" service. My browser says "the server returned an invalid or unrecognized response" -- what gives? Location: http://www.jguru.com/faq/view.jsp?EID=146 Created: Sep 3, 1999 Modified: 1999-12-22 11:11:42.609 Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) This is probably due to a NullPointerException being thrown. There's a bug in JWS 1.1 whereby it doesn't correctly log these exceptions. The solution is to put your doPost() method inside a try block and catch NullPointerException. See the debugging question in this FAQ for more details and source code. What is the HelloWorld Servlet? Location: http://www.jguru.com/faq/view.jsp?EID=147 Created: Sep 3, 1999 Modified: 2001-12-29 11:08:03.612 Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)
import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class HelloHttpServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { String name = req.getParameter("name"); if (name == null) name = "Joe"; res.setContentType("text/plain"); ServletOutputStream out = res.getOutputStream(); out.println("Hello, " + name + "!"); }
} This code responds to an invocation of the form http://myserver.foo.com/servlet/HelloHttpServlet?name=Fred Comments and alternative answers
Don't forget to include imports!!!! Author: Sharat N (http://www.jguru.com/guru/viewbio.jsp?EID=502507), Oct 16, 2001 (for new guys)In the above program, include http imports. import javax.servlet.*; import javax.servlet.http.*; import java.io.*; Thanks Sharat function setContentType not found in Tomcat 3.2.1 Author: John Meagher (http://www.jguru.com/guru/viewbio.jsp?EID=813752), Mar 26, 2002 Whenever I javax helloWorld.java, I get this error: function setContentType(java.lang.String) not found in class javax.servlet.http.HttpServletResponse Why would I get this message, if my classpath is ok? How do I get the name of the currently executing script? Location: http://www.jguru.com/faq/view.jsp?EID=148 Created: Sep 3, 1999 Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Use req.getRequestURI() or req.getServletPath(). The former returns the path to the script including any extra path information following the name of the servlet; the latter strips the extra path info. For example:
URL http://www.purpletech.com/servlets/HelloEcho/extra/info?height=100&width=200 getRequestURI /servlets/HelloEcho/extra/info getServletPath /servlets/HelloEcho getPathInfo /extra/info getQueryString height=100&width=200 This is useful if your form is self-referential; that is, it generates a form which calls itself again. For example:
out.println(""); (encodeURL adds session information if necessary. See the Sun Servlet Tutorial and this FAQ's Session Tracking question. Note that this method was renamed from "encodeUrl" to the properly-capitalized "encodeURL" somewhere around version 2.1 of the servlet spec.) Note that early versions of Java Web Server and some servlet engines had a bug whereby getRequestURI would also return the GET parameters following the extra path info. Comments and alternative answers
I tried to do this in IBM WAS 3.02 and got the error... Author: Avinash Kachhy (http://www.jguru.com/guru/viewbio.jsp?EID=224947), Oct 9, 2000 I tried to do this in IBM WAS 3.02 and got the error that the method req.getServletPath() was not defined. Is this correct for WAS or did I do something wrong? out.println("Servlet Path = " + req.getServletPath()); Thanks Avinash Use this piece of code to demonstrate the physical... Author: Aprameya Paduthonse (http://www.jguru.com/guru/viewbio.jsp?EID=4707), Feb 1, 2001 Use this piece of code to demonstrate the physical location of the servlet that gets invoked by a virtual path(URI)
How do I ensure that my servlet is thread-safe? Location: http://www.jguru.com/faq/view.jsp?EID=150 Created: Sep 3, 1999 Modified: 2003-01-08 14:30:31.956 Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) [See also What is the meaning of calling a method or object "thread-safe?" ] This is actually a very complex issue. A few guidelines:
1. The init() method is guaranteed to be called once per servlet instance, when the servlet is loaded. You don't have to worry about thread safety inside this method, since it is only called by a single thread, and the web server will wait until that thread exits before sending any more threads into your service() method.
2. Every new client request generates (or allocates) a new thread; that thread calls the service() method of your servlet (which may in turn call doPost(), doGet() and so forth). 3. Under most circumstances, there is only one instance of your servlet, no matter how many client requests are in process. That means that at any given moment, there may be many threads running inside the service() method of your solo instance, all sharing the same instance data and potentially stepping on each other's toes. This means that you should be careful to synchronize access to shared data (instance variables) using the synchronized keyword. (Note that the server will also allocate a new instance if you register the servlet with a new name and, e.g., new init parameters.)
4. Note that you need not (and should not) synchronize on local data or parameters. And especially you shouldn't synchronize the service() method! (Or doPost(), doGet() et al.) 5. A simple solution to synchronizing is to always synchronize on the servlet instance itself using "synchronized (this) { ... } ". However, this can lead to performance bottlenecks; you're usually better off synchronizing on the data objects themselves.
6. If you absolutely can't deal with synchronizing, you can declare that your servlet "implements SingleThreadModel". This
empty interface tells the web server to only send one client request at a time into your servlet. From the JavaDoc: "If the target servlet is flagged with this interface, the servlet programmer is guaranteed that no two threads will execute concurrently the service method of that servlet. This guarantee is ensured by maintaining a pool of servlet instances for each such servlet, and dispatching each service call to a free servlet. In essence, if the servlet implements this interface, the servlet will be thread safe." Note that this is not an ideal solution, since performance may suffer (depending on the size of the instance pool), plus it's more difficult to share data across instances than within a single instance. See also What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?
7. To share data across successive or concurrent requests, you can use either instance variables or class-static variables, or use Session Tracking.
8. The destroy() method is not necessarily as clean as the init() method.
The server calls destroy either after all service calls have been completed, or after a certain number of seconds have passed, whichever comes first. This means that other threads might be running service requests at the same time as your destroy() method is called! So be sure to synchronize, and/or wait for the other requests to quit. Sun's Servlet Tutorial has an example of how to do this with reference counting.
9. destroy() can not throw an exception, so if something bad happens, call log() with a helpful message (like the exception). See the
"closing a JDBC connection" example in Sun's Tutorial.
Comments and alternative answers
Point 3: Isn't it one servlet instance per regist... Author: sharma MR (http://www.jguru.com/guru/viewbio.jsp?EID=4939), Mar 15, 2000 Point 3: Isn't it one servlet instance per registered name of the servlet? Point 6: What is the initial size of the pool? Assume there is only one instance of the servlet that implements singlethreadmodel. Does more request imply more instances ( as opposed to more thread when the servlet does not implement SingleThread)? If so, what is the maximum servlet instances? Does it depend on the resource? Point 2: Each client generates a thread which can call... Author: Tony Biag (http://www.jguru.com/guru/viewbio.jsp?EID=27664), Mar 23, 2000 Point 2: Each client generates a thread which can call doGet() (et al) method. Does the thread associated with the client request guaranteed to have the sole access and ownership of HttpServletRequest and HttpServletResponse objects? To put it the other way, do I need to synchronize access to these objects (HttpServletRequest and HttpServletResponse)? 3. Maybe. It probably depends on the engine implem... Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Mar 24, 2000 3. Maybe. It probably depends on the engine implementation. It might be good to check the spec and documentation if your logic depends on it. 6. The thread pool size is determined by the engine; there should be a config parameter. Every request that comes in while another request is being processed spawns a new instance, up to a certain number of instances. After that, they stall. Again, the numbers are up to the engine. 2. You definitely always are the only one who has the Request and Response objects, so don't bother synchronizing on them. They're per client request, remember. 2. "Every new client request generates a new ... Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Apr 3, 2000 2. "Every new client request generates a new thread" -- actually, the servlet engines are free to implement thread pools, which means there's a chance that two successive doGets will happen on the same actual thread. You shouldn't make any assumptions about this either (in case you're tempted to use ThreadLocal variables or some other bad idea :-).
in case you're tempted to use ThreadLocal variables or some other bad idea :-). Author: Pahl Aakh (http://www.jguru.com/guru/viewbio.jsp?EID=1170988), Apr 16, 2005 Alex, Would you please explain why thie could be a problem? I would think that as long as you assign a new, appropriate, value to ThreadLocal variable before it is used, it will be used properly! A thread will complete the first request-processing before it starts the next one even if reused out of the threadpool, won't it. Thanks Point 3: Reading the "Playing it Smart With Java... Author: Lars Andersson (http://www.jguru.com/guru/viewbio.jsp?EID=40504), Apr 26, 2000 Point 3: Reading the "Playing it Smart With Java Servlets" by Matthew Ferris and Michael Bogovich in Servlet Central March 1999, the authors suggest a solution where a new instance of a transaction class is created for every client request. Calling this instance's doRun() method would create an execution environment similar to what you get when using the SingleThreadModel. The benefit would be that you can maintain common resources such as connection pools in the servlet's doGet() method before calling the transaction instance's doRun() method. The transaction object can be pooled for performance, or associated with the session if further processing is needed in a later request. This setup sounds good to me, but I have not tried it yet. Any comments? How local data in servlet is syncronized Author: Arun Selvaraj (http://www.jguru.com/guru/viewbio.jsp?EID=1105676), Aug 1, 2003 you need not (and should not) synchronize on local data or parameters. And especially you shouldn't synchronize the service() method! (Or doPost(), doGet() et al.) But at any point of time we will have only one instance created for a single servlet.It means that there will be a memory allocation for each and every member of that servlet class only one. So calls to service method will actually use the allocated memory reference. Then how the local variables inside the service will not be allocated at sigle place? And if i declare any other method which is called from service() method in my servlet, will it be thread-safe (or) do i need to syncronize it? Please Clarify. Re: How local data in servlet is syncronized Author: Steve Xu (http://www.jguru.com/guru/viewbio.jsp?EID=1107576), Aug 9, 2003 don't confuse the instance variable with the local variable inside service method. instance variable: allocated at the object level, needs to be synchronized. local variable: allocated on the stack of the calling thread, does not need to be synchronized.
synchronize the read only instance variable Author: Deepesh Rastogi (http://www.jguru.com/guru/viewbio.jsp?EID=1119170), Oct 2, 2003 Do I need to synchronize the instance variable/object, which I am trying to keep for read only purposes? I am using two instnce variable, the first is the property from file and the other is an object on which I need to make a method calls to log/store in the database.I do not think both the variable be synchronized... thanks deepesh whats the difference Author: Prashant Jain (http://www.jguru.com/guru/viewbio.jsp?EID=1251496), Jul 2, 2005 what exactly the difference between synchronizing the service method of the servlet and making the servlet to implement singlethreadmodel ? when there just one instance of a servlet then synchronizing the service method would actually sync' every request (thread) calling the servlet. ??? 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. 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/, [email protected]) has written a Servlet that demonstrates this technique called CookieDetector (http://www.purpletech.com/code/CookieDetector.html) See also http://www.jguru.com/jguru/faq/view.jsp?EID=138297 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/199812/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. Comments and alternative answers
Comments on E and F Page parsers have been written.... Author: Brett Knights (http://www.jguru.com/guru/viewbio.jsp?EID=8054), Jan 27, 2000 Comments on E and F Page parsers have been written. Go to http://www.docuverse.com/htmlsdk/index.html and you can download the pieces necessary to parse html files into a dom Document. You can then use dom methods to modify then emit the results. OR if you prefer F you can suck most of an html page into an xsl template tag and insert <xsl: tags to format your dynamic output. It's not great for really dynamic sites but it's an excellent way to have a page designer do a bunch of work then turn it over to you for installing dynamism (dynamicality? :-) Saxon is an excellent engine for this. There's another option: use SSI for Java. It's an SSI... Author: Joe Morse (http://www.jguru.com/guru/viewbio.jsp?EID=91113), Jun 29, 2000 There's another option: use SSI for Java. It's an SSI parser that runs in your VM, and it's open source (GPL). It also includes some cool utility classes (which you can mimic or extend) for creating stateful form elements and other things. There's even an iterator for printing variable-length collections (e.g. db recordsets, etc). Plus, it's portable; it will run on any web server with little or no changes. Check it out at http://www.freecode.com/cgi-bin/viewproduct.pl?8543. XMLC Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Oct 27, 2001 A great new "third way" solution -- with templates on one side, and servlets on the other -- is XMLC. Faced with the problem of separating presentation from code, XMLC takes the radical step of... (drumroll please...) actually separating the presentation from the code! The presentation "layer" is literally an HTML file. The code "layer" is a servlet (or any Java class) that reaches into the HTML file and changes its content, based on "ID" attributes embedded inside the HTML tags. (The way it accomplishes this is by compiling the HTML file into a Java class and data structure, but that's almost beside
the point.) How do I send email from a servlet? Location: http://www.jguru.com/faq/view.jsp?EID=154 Created: Sep 3, 1999 Modified: 2000-07-25 12:18:54.284 Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) From: James Cooper ([email protected]) GSP and GnuJSP both come with SMTP classes that make sending email very simple. if you are writing your own servlet you could grab one of the many SMTP implementations from www.gamelan.com (search for SMTP and java). All the ones I've seen are pretty much the same -- open a socket on port 25 and drop the mail off. so you have to have a mail server running that will accept mail from the machine JServ is running on. See also the JavaMail FAQ for a good list of Java mail resources, including SMTP and POP classes. Comments and alternative answers
If you want to use the JavaMail API, get it and create... Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Jul 24, 2000 If you want to use the JavaMail API, get it and create a program similar to the Hello World program. See also Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Sep 20, 2001 This thread: Re: Automatically send and get mails using servlet... Some examples Author: Chris Lack (http://www.jguru.com/guru/viewbio.jsp?EID=326717), Sep 21, 2001 I've written an "EMailClient" class for sending e-mails for my guestbook entries. I've also done an "InBox" servlet class that lists e-mails in your pop mail in-box so that you can delete or bounce them before downloading to your PC. Have a look at the code, it might help http://www.chris.lack.org and choose the java option on the professional menu. By the way you'll need JavaMail and Java Activation foundation from Sun if you've not already downloaded them. You don't need your own mail server. Are there any ISPs that will host my servlets? Location: http://www.jguru.com/faq/view.jsp?EID=155
Created: Sep 3, 1999 Modified: 2003-04-04 10:57:05.916 Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) The Adrenaline Group maintains a list of over 50 ISP's who host Java Servlets (http://www.adrenalinegroup.com/jwsisp.html) . Another list is at http://www.servlets.com. Those that our gurus (you) have had specific experience with include: • • • • • • • • • • •
Daniel Kehoe ([email protected]) has had "very happy experiences" with Silicon Valley Web Hosting (http://www.svwh.net/) for several clients. Horus Networks - http://www.horus.ch/servlets.shtml (http://www.servlets.net) is an ISP geared towards hosting servlets. http://www.ebpcs.net http://www.mycgiserver.com is free (!) and does EJB too http://www.tricreations.com http://www.webappcabaret.com http://www.cwihosting.com (see comment below) http://scorpions.net/ Rage Media Rimu Hosting
A few ISPs have also said that they can host Java applications: • • •
The Sphere (http://www.thesphere.com/) Centralogic (http://www.centralogic.com/) Electronaut (http://www.electronaut.com/)
Please report any experiences, good or bad, you have with these services to this thread. See also What ISPs provide hosting services which include JSP support? Comments and alternative answers
Horus Networks is very flexible on all services, and... Author: Denis BUCHER (http://www.jguru.com/guru/viewbio.jsp?EID=7742), Jan 22, 2000 Horus Networks is very flexible on all services, and we would be pleased to host servlets... c.f. our own programmation tests under http://www.horus.ch/servlets.shtml http://www.horus-networks.com/servlets.shtml Web Hosting Author: dufunk Eugene Rozum (http://www.jguru.com/guru/viewbio.jsp?EID=1193732), Aug 17, 2004 Prokmu jsp hosting offers the best quality/price JSP/Servlet services! Re: Web Hosting
Author: dufunk Eugene Rozum (http://www.jguru.com/guru/viewbio.jsp?EID=1193732), Sep 6, 2004 http://www.prokmu.com Re[2]: Web Hosting Author: Eugene Rozum (http://www.jguru.com/guru/viewbio.jsp?EID=1254770), Jul 24, 2005 Prokmu Jsp hosting http://www.prokmu.net http://www.ebpcs.net is a very cool one too Author: Steve Nguyen (http://www.jguru.com/guru/viewbio.jsp?EID=39558), Apr 24, 2000 http://www.ebpcs.net is a very cool one too If anyone looking for free Servlet/JSP hosting check... Author: Nilesh Shah (http://www.jguru.com/guru/viewbio.jsp?EID=1810), May 30, 2000 If anyone looking for free Servlet/JSP hosting check this out. http://www.mycgiserver.com http://www.servlets.net http://www.tricreations.co... Author: Melanie Munden (http://www.jguru.com/guru/viewbio.jsp?EID=138305), Aug 30, 2000 http://www.servlets.net http://www.tricreations.com Check out www.wantjava.com They support Tomcat, O... Author: James Ward (http://www.jguru.com/guru/viewbio.jsp?EID=242591), Nov 1, 2000 Check out www.wantjava.com They support Tomcat, Oracle, and mySQL! They also have great customer service! Another good listing of ISPs that support Java Servlets... Author: Bill Day (http://www.jguru.com/guru/viewbio.jsp?EID=135825), Dec 8, 2000 Another good listing of ISPs that support Java Servlets is at: www.servlets.com The listings include contact info and rates. More more more Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jul 16, 2001 • •
CWI Hosting (http://www.cwihosting.com) Author: Scott Barstow (http://www.jguru.com/guru/viewbio.jsp?EID=226863), Oct 11, 2001 Do not use these guys. I have had nine kinds of grief with them, and their support is less than adequate. I have had outages of three days, and mail outages of three - four days. Re: CWI Hosting (http://www.cwihosting.com) Author: Joost Schouten (http://www.jguru.com/guru/viewbio.jsp?EID=581960), Jan 24, 2004 I just wanted to say that I use CWI hosting aswell, and do appreciate their service. They have provided me with good support, even on my own code at times. Just wanted to give them a fair chance. Joost re: Webhosting for servlets Author: richard freeman (http://www.jguru.com/guru/viewbio.jsp?EID=752499), Feb 8, 2002 Zetnet.com will host jsp, sql, mysql, etc. with all of their standard hosting packages (Ranging from UK£100 per annum). Drop me a line on 01524 34918 if you are interested in doing so... 4Java.ca - inexpensive and reliable host Author: support 4javaca (http://www.jguru.com/guru/viewbio.jsp?EID=804843), Mar 20, 2002 They host JSP, Servlet, J2EE. Very inexpensive, only USD$8.50/month! http://www.4java.ca MyServletHosting.com Author: Walter Meyer (http://www.jguru.com/guru/viewbio.jsp?EID=23642), Mar 27, 2002 I've been with MyServletHosting.com for over a year. The experience was great at first, but over that last 5 or 6 months, stability has really degraded. When I contact tech support they always apologize and say they're in the middle of moving their clients to more stable servers. Maybe they'll straighten everything out in the future, but for now, I'm looking for a new host.
Re: Scorpions.net Author: John Colucci (http://www.jguru.com/guru/viewbio.jsp?EID=816265), Mar 28, 2002 I am with Scorpions.net for about 8 months now. I have personal and business sites there. They use Tomcat,iPlanet, Java web server. Oracle hosting is super cheap and no set up fees. So far I am happy with them. John. Check out http://www.ragemedia.ca Author: Alex Iljin (http://www.jguru.com/guru/viewbio.jsp?EID=894025), May 27, 2002 Check out http://www.ragemedia.ca They provide J2EE application hosting (including Servlets, JSP and EJB's) based on Tomcat/Jboss platform, plus PostgreSQL database is standard for all plans. Rimu Hosting Author: Peter B (http://www.jguru.com/guru/viewbio.jsp?EID=1071364), Mar 29, 2003 Try http://rimuhosting.com Rimu Hosting provide Virtual Dedicated servers. That includes 128MB of memory, 8GB of disk space, and 30GB of transfers. Accounts come with JBoss and include JDK1.4, JSP, EJB and servlet support. You don't share the Java VM and you get to configure JBoss the way you need it. Other features include SSH root access, Webmin CP, MySQL, PHP, Redhat Linux.
Re: Rimu Hosting Author: Peter B (http://www.jguru.com/guru/viewbio.jsp?EID=1071364), Oct 15, 2003 A customer who just signed up pointed that our plans now come with 4GB of disk. Our Red Hat file systems have been updated to use Java 1.4.2, JBoss 3.2.1 as well a choice of a recent Tomcat or Jetty servlet engine.
I am with Alacarte Java Hosting (http://www.alacartejava.com) and we specialize in low cost Java JSP Hosting, Servlet Hosting, and much more. Checkout our Web Site at http://www.alacartejava.com « previous