Posts in the “servlets” category

How to put an object on the request in a servlet

Many times when you're working with Java servlets and JSP's, you'll want to forward some piece of information from your servlet to your JSP without having to put that piece of information into the session. For instance, in many applications you may not have a user session, and in other cases where you do have a session, you may just not want to put a bunch of junk in there.

Java servlet session - how to test for a valid session in a servlet

When you're writing Java web applications -- for example, an application like a discussion forum -- you end up writing Java servlets where you need to know if the user accessing your servlet has a valid Java servlet session established. If they have a valid servlet session established, you might do one thing in your servlet code, but if they don't have a valid servlet session, you might handle their request differently.

Tomcat, pathinfo, and servlets

So today I learned that you can't just access PATH_INFO (pathinfo) information from a servlet when you're using Tomcat (at least not Tomcat 3.2.4 running under Apache). I can access the PATH_INFO information okay under Tomcat running standalone on my PC, but for some reason the same config did not work properly using Tomcat under Apache. (I'll investigate this more in the future.)

Specifically, for me to be able to access PATH_INFO (PathInfo) information in a servlet, I had to add this servlet mapping information to my web.xml file:

Servlet forward example - How to forward from a servlet to a JSP

Here's an example of how to forward from a servlet to a JSP in your J2EE code. I can never remember how to do a forward like this when I need it, so even though this example is pretty easy, I've put it out here so I can find it later.

The typical scenario is that you're working on a Java servlet, and you need to forward the user from that servlet to a JSP. Assuming the name of the JSP is "searchResults.jsp", here's the code that will forward from your servlet to that JSP:

How to forward from one JSP to another JSP

When you need to forward from one JavaServer Page (JSP) to another JSP, here's all you have to do:

<jsp:forward page="/faces/success.jsp" />

In the example shown I happen to be working on a small JavaServer Faces (JSF) application, so the URL in this example includes the string /faces/.

 

A Hello World servlet

Last week I was working with OpenSSO quite a bit, and at one point I just needed a really simple Java servlet that I could first try to run, and then try to secure, using OpenSSO. All I really needed for this purpose was a "Hello world servlet", and that's when I realized I've never put one out here.

So, to fix that problem, here is the source code for a very simple Java servlet that will print "Hello, world" when you access it through a browser. To get started, here's the source code for the servlet: