The Source for Java Technology Collaboration
User: Password:



Jayson Falkner's Blog

J2EE Archives


Lazy coder's mapping of DNS prefix to a sub-directory in a web application.

Posted by jfalkner on February 19, 2008 at 11:50 AM | Permalink | Comments (2)

The Servlet specification provides a really elegant mechanism for packaging up a whole website in to a single WAR file and deploying that file as a website. Multiple websites can be mapped to different domain name prefixes, such as 'www.proteomecommons.org' versus 'tranche.proteomecommons.org'. This blog explains a hack to map the domain prefix to a sub directory of the same web application.

Why use this hack? Well, I had two good reasons. First is that when I first helped make the website we didn't put it in a proper build system. Thus it grew in to a hodgepodge of JSP, HTML, and Java code. Second, the domain prefix that we were using 'tranche.proteomecommons.org' wouldn't easily fit into its own web application because it relies on a shared in-memory database. Sure, I could invest a significant chunk of time refactoring the code and binding the database to a local, protected socket, but that'd take a lot more time than the ten minutes that it would take to hack out a URL mapping filter.

Here is the filter's source-code in full. I'll discuss how it works after.

package org.proteomecommons;

import java.io.File;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Jayson Falkner - jfalkner@umich.edu
 */
public class TrancheRedirectFilter implements Filter {
    // save the filter config -- needed later
    FilterConfig config = null;
    // the domain to match
    String domain = "tranche.proteomecommons.org";
    // uri to pre-append
    String preAppend = "/dev/dfs";
    
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse res = (HttpServletResponse)response;
        // check the URL for the domain name
        String url = req.getRequestURL().toString();
        if (url.contains(domain)) {
            // get the resource
            String uri = tweak(url);
            // forward to the resource
            req.getRequestDispatcher(uri).forward(req, res);
        } else {
            chain.doFilter(req, res);
        }
    }
    
    // dynamically change the URL
    private String tweak(final String url) {
        String uri = url.split("proteomecommons.org|\\?")[1];
        // if it starts with 'tranche.proteomecommons.org' move to /dev/dfs directory
        if (url.contains(domain)) {
            uri = preAppend+uri;
            
            // check if this is a real file and a directory
            String path = config.getServletContext().getRealPath(uri);
            File pathFile = new File(path);
            if (!uri.endsWith("/") && pathFile.exists() && pathFile.isDirectory()) {
                uri += "/";
            }
        }
        return uri;
    }
    
    public void init(FilterConfig filterConfig) throws ServletException {
        this.config = filterConfig;
    }
    
    public void destroy() {
    }
}

The code assumes that you want to map all URLs that start with a certain prefix to a sub-directory of your website. For example, 'www.proteomecommons.org' goes to the normal website. The Tranche Project website was developed in the '/dev/dfs' folder of the website, thus by default making its URL http://www.proteomecommons.org/dev/dfs. However, Tranche grew up quickly and we wanted to give it a proper, top level domain 'tranche.proteomecommons.org' while not breaking any of the old '/dev/dfs' links. In short, we wanted to make all URLs starting with 'tranche.proteomecommons.org' automatically go to the '/dev/dfs' folder without redirecting to a ugly URL starting with www and /dev/dfs at the end.

The Filter is generic. The first two variables will swap any domain name prefix with a folder location. In this case, 'tranche.proteomecommons.org' is swapped with '/dev/dfs'.

    // the domain to match
    String domain = "tranche.proteomecommons.org";
    // uri to pre-append
    String preAppend = "/dev/dfs";

If you want to copy/paste the above code, simply swap these variables to be the domain name and local directory of files to map to. If you are up for it, you might abstract them to variables in the Filter's web.xml declaration.

Only the tweak() method of the filter merits more discussion. The other code causes the Filter to invoke or skip tweak() based on if the URL has the domain name specified. In the tweak() method, the code does the swapping.

   private String tweak(final String url) {
        String uri = url.split("proteomecommons.org|\\?")[1];
        // if it starts with 'tranche.proteomecommons.org' move to /dev/dfs directory
        if (url.contains(domain)) {
            uri = preAppend+uri;
            
            // check if this is a real file and a directory
            String path = config.getServletContext().getRealPath(uri);
            File pathFile = new File(path);
            if (!uri.endsWith("/") && pathFile.exists() && pathFile.isDirectory()) {
                uri += "/";
            }
        }
        return uri;
    }

First, the URL is split to remove the domain name with prefix, 'tranche.proteomecommons.org' and replace it with the default domain name, 'www.proteomecommons.org'. Next, the URL is padded to include the proper sub-directory, "/dev/dfs". Finally, the Filter forwards the request and response to the appropriate page. A little File check is made to handle a fringe case where a URLs go to a directory.

That is it! If it still isn't clear why the above is handy, note that the two URLs now work exactly the same:

Also, the two links go to the same exact file on the server. All of our old links work fine. All of the new links starting with 'tranche.proteomecommons.org' work. Best of all the whole hack took about 10 minutes...well, a half hour if you count writing this blog.



Blarg #25: A JSP that shows Request Headers

Posted by jfalkner on July 03, 2006 at 06:32 PM | Permalink | Comments (1)

This code as been shown many times before, including in my book. This is exactly what the title says: a JSP that will display the request headers sent by your browser. It is also a good example of how to use the JSP EL and the JSTL core tags to make an incredibly simple JSP.

Here is the code. Simply copy and paste it in to a JSP, ideally one that you are editing in Netbeans. You must have the JSTL JARs in your classpath.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<html>
<head><title>HTTP Request Headers</title></head>
<body>
<h2>This is a list of the HTTP request headers sent by your browser.</h2>

<c:forEach var="v" items="${header}">
    <b>${v.key}</b>: ${v.value}<br />
</c:forEach>

</body>
</html>


Blarg #15: How can I do image processing on the server-side?

Posted by jfalkner on May 27, 2005 at 04:51 PM | Permalink | Comments (3)

I met Fred and John and they asked about doing clever image manipulation on the client-side, but without requiring the client to run anything but a web browser. It seemed like doing a few tricks with ImageIO on the server-side would solve the problem, and it'd eliminate the piles of JScript they had been working on. Here is the code so that others can easily write servlets that manipulate and generate images. Nothing like a blog to make something Googleable.

The initial task seemed pretty straight forward. Documents are imaged and an algorithm picks out text from certain places in the document. Most of the time the text is recognized fine, but in the cases where it is not a user has to manually verify the value of the text. The webapp needs to show the entire document with the area of interest highlighted, the specific chunk of text being handled, and provide a way to give feedback.

The first servlet dynamically highlights an area on an existing image. It saves Fred and John from having to make multiple copies of their image, and it doesn't require anything but an image tag on the client-side.

Here is the interesting bit that highlights the image. The highlight is nothing more than a rectangle filled with a semi-transparent color....

		// read in the image
		InputStream imageIn = this.getServletContext().getResourceAsStream(
				"/images/" + imageID);
		// buffer for speed
		BufferedInputStream in = new BufferedInputStream(imageIn);

		// check the cache, start with no image
		BufferedImage bi = ImageIO.read(in);

		// highlight the image
		Graphics g = bi.getGraphics();
		// highlight the area
		g.setColor(new Color(1f, 0f, 0f, 0.5f));
		g.fillRect(x, y, width, height);
		// draw a box
		g.setColor(Color.BLACK);
		g.drawRect(x, y, width, height);

		// set the response type
		response.setContentType("image/jpeg");

		// send the image straight to the client
		ServletOutputStream out = response.getOutputStream();

		// write the image as a png
		ImageIO.write(bi, "JPEG", out);

Note that ImageIO and the Graphics object makes the task easy. ImageIO gives you a BufferedImage and Graphics lets you draw a semi-transparent color on it. The entire servlet code is in the "Extended Entry" section, a.k.a. the section that google probably won't see but that you can cut-and-paste from.

The second servlet is very similar, except it dynamically returns sub-sections of an existing image. This saves Fred and John the task of making many different little images that correspond to each interested section of a scanned document. Instead they can focus on describing those sections (x, y, width, height) in their database and rely on the servlet to dynamically generate appropriate images for a web browser.

		// read in the image
		InputStream imageIn = this.getServletContext().getResourceAsStream(
				"/images/" + imageID);
		// buffer for speed
		BufferedInputStream in = new BufferedInputStream(imageIn);

		// check the cache, start with no image
		BufferedImage bi = ImageIO.read(in);

		// make the sub-image
		BufferedImage subImage = bi.getSubimage(x1, y1, width, height);

		// set the response type
		response.setContentType("image/jpeg");

		// send the image straight to the client
		ServletOutputStream out = response.getOutputStream();

		// write the image as a png
		ImageIO.write(subImage, "JPEG", out);

Again, ImageIO and BufferedImage make the task easy. ImageIO gives the BufferedImage and the sub-image is made by invoking BufferedImage's getSubImage() method. The results are then serialized to the client as a JPEG. Full code is in the copy-and-paste section.

One final thing. The image and img HTML tags don't take well to passing URL parameters. That is why the servlets expect image names to be encoded as x-y-width-height-imagename, where everything but the dashes is replaced with appropriate values. On the server-side the URL is split up and the appropriate values are parsed. Check out the copy-and-paste section if you'd like to see the code.

Good luck Fred and John!

Jayson Falkner
jayson@jspinsider.com

Continue Reading...



Blarg #14: Why custom tags aren't worth your time

Posted by jfalkner on May 23, 2005 at 02:42 PM | Permalink | Comments (14)

I think I've decided that custom tags aren't worth your time. Certainly 'classic' custom tags, pre JSP 2.0, are ridicuously hard to use regardless of if you'd actually want to use them. I'm not talking about those. I'm talking about custom tags in general. Simple tags, .tag files, and the whole custom tag mechanism.

We have the JSTL, which includes a few helpful tags that take care of iteration, formatting, and i18n. What else do you need a custom tag for? The only things I can think of are managing form state or coding up some snazzy DHTML widgets, but how often do you do code such snazzy widgets and aren't there plenty of existing form state tag libs? Please tell me. What is a good use for a custom tag, and make sure to explain why it wouldn't be easier to do the same thing using servlet filters or JSP EL expressions. Better yet, show the use and point to the code.

I'll propose it now. Stop encouraging people to make their own custom tags. Especially new developers who don't know better.

A slight revision!

After some feedback, I've decided that I need to soften my stance a little. .tag files are great for abstracting repetitive chunks of HTML, e.g. DHTML widgets such as a rollover effect. Since tag files are taglibs, I think they should be saved. As for the other stuff...it is still in peril.

BTW, does anyone know of a good example I can reference? I'd love to find a nice DHTML library of taglibs that also takes care of any little cross-browser bug.



Blarg #13: I think it is silly that your HelloWorld servlet produces static content

Posted by jfalkner on May 23, 2005 at 02:27 PM | Permalink | Comments (15)

Why is it that the first servlet people teach is one that produces static content? HelloWorld.html is appropriate. HelloWorld.java is silly. The more JSP/Servlets I do, the more frustrated I get when I see others do a mediocre job of introducing the important concepts. Sure it is important to teach that code goes in WEB-INF/classes and all the other beginner's stuff, but it certainly doesn't merit a static servlet.

How about we all figure out an appropriate dynamic, simple servlet for the every present I'm-coding-my-first-servlet exercise. The only thing I can think of at the moment is a Servlet that displays the date, and that is far to cheesy to end the blog with. I'll finish writing this when I come up with a slightly better idea.

How about a simple hit counting filter? e.g. "HelloWorld! You've been here X times?", replacing the x with an appropriate increment. Here is the code.

package example;

import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;

public class HelloServlet extends HttpServlet {
  int count = 0;
  public void doGet (HttpServletRequest req,
                     HttpServletResponse res)
    throws ServletException, IOException {
    // increment x
    count ++;

    // write out some text
    PrintWriter out = res.getWriter();

    out.println("Hello, world! This page has been visited "+count+" times.");
    out.close();
  }
}

Can you think of a better example? I'll be teaching this for real. Perhaps to your next employee. You don't want your next coder making static servlets do you?

Jayson Falkner
jayson@jspinsider.com



Blarg #11: Help me print your book. I downloaded it for free.

Posted by jfalkner on January 19, 2005 at 05:33 PM | Permalink | Comments (2)

Thanks for letting us to use and download your book "Servlets and JavaServer Pages: The J2EE Technology Web Tier", that is on TheServerSide.com.

I am wondering, if its free, why the print option is turned off in the pdf file? It is prohibited to print it? Hope you can answer me on this issue?

You are welcome! I almost completely forgot that the book is free if you register over at the TheServerSide.com, which is also free. Hopefully the next version of the book will be free, with no registration required. FYI, the first few chapters are completely free and printable at www.jspbook.com

Here are the links to those chapters: Chapter 1 and Chapter 2 and Chapter 3. Chapter 2 and 3 are two of my favorites. Great material if you are learning JSP or Servlets.

As for the print button thing. I have no part in disabling that, and I can't explain the mystery that surrounds e-books.

However, consider this. Printing 700+ pages requires a lot of paper, time, and ink. All of those cost money. For $30 you can buy a pre-printed copy of the whole book. Plus I get something like 15% on each sale. That is $4.50, which happens to be enough money to buy a wet burrito, on wet burrito day, at my favorite wet burrito joint. If you buy the book, I'll buy a wet burrito, and that way we all win. Plus, you'd be amazed at what some good food does to e-mail response times.

Thinking about it some more...I could swear that I've heard rumors of lots of different PDF reading programs. Some of which are not only free but can ignore the no-print option. I'd look in to it, but I think it is most appropriate that I support both my publisher, cheers AW, and TheServerSide.com, cheers guys. As blarg readers, please tell me what you think in my talkback!



Blarg #9: Help me make code that is a webapp, uses a DB, and is secure

Posted by jfalkner on November 22, 2004 at 07:25 PM | Permalink | Comments (2)

Here is a reply to a really common question. What are the things I should keep in mind when making a secure website? This particular question was from a person who was considering using Java or Python, but the important stuff really doesn't rely on a particular programming language. If you are green, take a peek. If you know your stuff, fill in what I missed.

You'll note my answer hints at Linux+Java, and I don't say just use J2EE. I'm biased to the free, simple, easy solution. Please feel free to argue something better.

howdy,

it looks like i might be writing some code that involves
 
  - a web-based front-end
  - lots of database action on the back-end
  - a real need to care about security
 
 i'll probably be doing this with someone who's pretty good with Python, 
 but we might be convinced to switch to java.  seems like i ought to pick 
 your brain about this in either case.  any good resources i should start 
 with (i don't know anything that's not obvious about databases or 
 security, for example)?

In general, security isn't too tough, especially if you have local access to the server. Here are the easy fixes:

  • Don't let external ip addresses access your DB. Always admin in person, at the box. Close/firewall the sensitive ports.
  • Don't let root or dbadmin remotely log in to the server. Always require that sort of user to log in locally.
  • Don't ever let users execute SQL commands. Abstract DB access via a simple library.
  • If you don't need full db write access, set up a SQL view that won't let the webapp write/delete parts of the DB that it shouldn't.
  • Tunnel all sensitive web traffic using SSL/TLS. Everything else sends content via plain text. If you are real paranoid, buy a real 509.x certificate so that you don't have to worry about man-in-the-middle hacks.
  • Sandbox the app. Literally with Java. Don't let webapp code read/write to things that it shouldn't. This is a common flaw in most CGI-based apps.
  • Don't use ftp or telnet. Use sftp and ssh if you need to, and never give more read/write access than is needed.
  • Back up frequently and have the server e-mail its remote access and firewall logs to you. Proactively block all the ips that ping your server every second with a login attempt (you'll have quite a few)
  • Don't be lazy.

Doing all this on linux/java is no problem. SSH, SFTP, and firewall/packet filtering comes with linux. All the restrict-root-to-a-local-user tricks are simple SSHD configuration options. Pick up a SQL book or google for help with db management, it is old hat. Java/Jakarta Tomcat will solve all the webapp/SSL/TLS/db access issues.

Outside of Linux/Java. Most all of the mentioned software is available for non-windows boxes. Don't use windows. As for python, if you are happpy with the db access libraries and the webapp/CGI libraries you should be fine. If I remember right, python has weak HTTP/SSL/TLS support, but Apache can easily make up for that.

You should be able to pair "howto" with any of software names I mentioned and google will turn up plenty of guides.

Good Luck!

Jayson Falkner
jayson@jspinsider.com



Chinese Translation of "Another Java Servlet Filter Most Web Applications Should Have"

Posted by jfalkner on April 10, 2004 at 05:52 PM | Permalink | Comments (1)

Michael Tsai has recently finished a Chinese translation of one of my popular O'Reilly articles, "Another Java Servlet Filter Most Web Applications Should Have". If Chinese is your native language and you are a web application programmer, this translation is for you.

It may seem kind of odd that I'm writing this blog in English, especially since it would probably be most helpful if it was authored in Chinese; however, it is the best I can do to give a little attention to Michael's effort. Not only did he graciously offer to translate the article, but he took the time to make sure the translation kept true to the original article -- even when it involved several e-mail exchanges just to make sure a single sentence was correctly understood and accurately translated.

Cheers to you Michael! I'm glad you are helping branch out good, free information to Chinese developers, and I hope readers of your translation take the time to say thanks!

P.S. For those English servlet developers, the article is still available in English.



Blarg #7: How long does it takes to compress a response using a GZIP filter?

Posted by jfalkner on January 27, 2004 at 09:13 PM | Permalink | Comments (1)

Hi, just found out about your book the other day from java.net and was really grateful for the example of the Compression code. I've had to implement that in the past on the web server level and it was a real pain then, but this was relatively effortless. I'm adding this book to my to-buy list.

I do have a question. Perhaps if others are interested some sort of improvement could be integrated. Where would we add output messages that would help us with the timing of the compression?

i.e.If I put something like this in GZipFilter:

                 System.out.println("GZIP supported, compressing.");
                 long ini = System.currentTimeMillis();
                 GZIPResponseWrapper wrappedResponse = new
 GZIPResponseWrapper(response);
                 chain.doFilter(req, wrappedResponse);
                 wrappedResponse.finishResponse();
                 System.out.println("Compressed in " +
 (System.currentTimeMillis()-ini) + " ms");

I get the total time for the entire request, not just the time it takes to do the compression. >From testing I realize the compression time is pretty short, say in the order of tens of microseconds, but I'm still pretty interested. I was thinking that moving the time initializer from before the response constructor to before the finishResponse method call would work, but I wasn't sure if that would get the total compression time, or just the time for the last output to be flushed from the response buffer.

Thanks,
Ronald

Hi Ronald,

Awesome. I'm glad you found my book, and I hope you enjoy it.

The trick here is to split the request and compression in to two separate things. Buffer the response, then compress the buffer and time only the compression. You can more or less do this easily by editing the code in the com.jspbook.GZIPResponseStream class, e.g. here is the existing code in the close() method of GZIPResponseStream.

ByteArrayOutputStream baos = (ByteArrayOutputStream)bufferedOutput;
// prepare a gzip stream
ByteArrayOutputStream compressedContent = new ByteArrayOutputStream();
GZIPOutputStream gzipstream = new GZIPOutputStream(compressedContent);
byte[] bytes = baos.toByteArray();
gzipstream.write(bytes);
gzipstream.finish();
// get the compressed content
byte[] compressedBytes = compressedContent.toByteArray();

You can see the response gets put in to a byte array, then the byte array is compressed and the results are saved to another byte array. You could put a time check in as follows (very similar to what you were doing).

ByteArrayOutputStream baos = (ByteArrayOutputStream)bufferedOutput;
// prepare a gzip stream
ByteArrayOutputStream compressedContent = new ByteArrayOutputStream();
long ini = System.currentTimeMillis(); // <------- starting timing here
GZIPOutputStream gzipstream = new GZIPOutputStream(compressedContent);
byte[] bytes = baos.toByteArray();
gzipstream.write(bytes);
gzipstream.finish();
// get the compressed content
byte[] compressedBytes = compressedContent.toByteArray();
System.out.println("Compressed in " + (System.currentTimeMillis()-ini) +
" ms"); // <-------------- stop timing here

And the result is you are only counting how long the compression took. Although fair warning needs to be given. The current GZIPResponseStream class tries to buffer content, as shown above (it allows you to set the content-length header properly), but when compressing really big files the filter streams content back to the client as not to use up all of your web application's memory. The above timing example won't work if you are testing it on files larger than the buffer -- the default buffer is 50k, you may need to increase it for your benchmark.

In general, the resources it takes to compress content aren't an issue. However, if you find that compression takes up too much processing power, remember you can combine compression with caching to try and reduce the overhead.

Cheers, Jayson Falkner jayson@jspinsider.com

A few links



Blarg #6: How do I become an expert Java developer?

Posted by jfalkner on January 27, 2004 at 08:11 AM | Permalink | Comments (4)

Hi,
I'm a young java programmer(for now) and on the brink of writing my SCJP1.4 exam I want to be a Java Developer(J2EE) more than anything else. I've picked up REALLY REALLY bad coding conventions and norms along my path to Java-enlightenment and I would like to know from YOU, what could I do to turn this around and become a precision Java Developer, Are there Rules and Guidelines (in ENGLISH) that I can follow that will set me apart as a "developer of note"?

Please Advise
Lloyd

Hi Lloyd, depending on who you ask there are many different answers to this question. However, a great way to get started is by reading the Java coding conventions Sun encourages -- most all Java code you see will roughly follow these. These conventions fall along the lines of standard Java documentation, which is the next place you should look when seeking advice about Java. As a rule of thumb, check Java documentation first and goggle second.

If you really want to practice coding or look at a bunch of "good" code, try hacking away at your favorite open-source project (I'd suggest Tomcat, http://jakarta.apache.org/tomcat, or JBoss, http://jboss.org). You'll find lots of code that will show how general Java code usually looks, and you will also be able to see lots of examples of clever coding tricks. Plus, if you can really understand what is going on in a decent sized open-source project, odds are your Java skills are up to snuff.

Some Links

Jayson Falkner
jayson@jspinsider.com
http://www.jspbook.com



Blarg #5: Are you aware that the source-code for www.jspbook.com isn't available?

Posted by jfalkner on January 25, 2004 at 09:22 PM | Permalink | Comments (0)

Hi Jayson,
Are you aware that the source-code for www.jspbook.com isn't available on-line? How can I get a copy?

I get asked the above question almost daily, and people are fairly asking it. The short answer is http://www.jspbook.com/jspbook_site.war. And if www.jspbook.com is replaced with www.jspinsider.com, the answer is http://www.jspinsider.com/showsource.jsp.

The reason I posted this on java.net is because I think it will help others find the code without needing the middle man (me), and I realized maybe other JSP/Servlet developers would like something in addition to the source-code.

Let me explain. As a JSP/Servlet developer all of the code I write I try to make freely available for others to use as they wish. The goal is to promote the use of helpful Servlet/JSP/Java code. I think it is silly to expect others to learn when all they have is the API documentation. I wrote a book with this in mind, and one of the book's examples is building a real website (http://www.jspbook.com), which also funtions as the book support site. Although sadly, roughly a person a day can't figure out where the link is to the source-code for the site, and that I assume is the reason for all the e-mail I get with the above two lines. Hopefull this post will help reduce the average to at least a person per week.

About the other bit. I recently realized that putting source-code on-line by itself isn't overly helpful to people who don't buy the book that goes with it. I've decided to try and write up some nice, free on-line guides to why the source-code I provide is helpful. The idea is that I can demonstrate some code, say a compression filter, give you the source-code, and leave you feeling good because you've got something cool that you can hack away at as you please. Give me some ideas; what would you like?

Please direct suggestions to the feedback for this blarg, and I'll take the most popular ideas and make something of them in the weeks to come.



Blarg #4: Good Web Application Cache and Compression Support

Posted by jfalkner on November 21, 2003 at 08:39 AM | Permalink | Comments (1)

Here is a write up I did about probably the best solution to providing cache and compression support for your web application. If you don't know what a cache or compression filter is, read this article, now. If you do, it is still worth taking a look. Several questions have been asked and answered about the practical use of these filters and how they compare to alternative choices that offer the same functionality.

In short, I'm arguing that this is something every Java web app developer should use, and I'm showing exactly how in general it should be done. Don't you think that is worth a quick look? Not to mention free, open-source code compliments the O'Reilly quality article.

Cheers,

Jayson Falkner - jayson@jspinsider.com



Blarg #3: About the new JSP EL, who is using it? Plus a few other questions.

Posted by jfalkner on October 23, 2003 at 03:46 PM | Permalink | Comments (3)

Jayson,
Maybe you can make sense of this EL question. Background is after the questions.

1.) Who is the EL audience?
2.) How is Sun marketing EL to PHP and non-java web developers?
3.) Is this more fashion than function?
4.) Are non-java developers using EL?
5.) Does EL make it harder for java developers?

At a recent JUG, people unanimously said Java code in JSP is bad. In a JSF example involving database access, the group, with the exception of one lady, said that it was OK to use SQL in your JSF/JSP despite the recommendation against it. (She asked "what if your table name changes and you need to change the SQL", to which the group replied "you have a dba/design issue if they change table names on you").

My opinion is that <%//Some business/data logic%> and are about the same to non-developer web designers. They both basically say "stay away from this chunk here".To the extent that you can push code out of pages, it's a good thing.But then again, I was a roll-your-own-JDBC guy until I started using hibernate extensively. Now I cringe if I have to type Class.forName("jdbc.xyz...");
-Don

Good question Don, thanks for asking it.

I'll answer your five points then address your background information. It seems you are asking a little about the new JSP (i.e. what is it good for -- why would one want to use it) and you are also touching on the ever popular topic of good JSP programming practices.

1.) Who is the EL audience?

JSP 2.0 and above developers is the easy answer. The more practical answer is, anyone who understands good JSP coding practices -- basically, anyone who wants to more easily code and maintain a JSP, especially when working with more than one developer. Of course, I'll expand on this later, during your third point.

I think it is also worth saying that assuming the JSP EL is targeted only to scripters, such as PHP or Perl programmers, is a poor assumption. In my opinion, you are best off thinking of the JSP EL as allowing JSP to work as a template in a Model II (ish) design. Remember the JSP EL only evaluates simple expressions (well, as of the unofficial 2.0 spec), you can't dump lines of code in the middle of a JSP EL expression.

2.) How is Sun marketing EL to PHP and non-java web developers?

As far as I know, Sun is not making serious efforts to market the EL to PHP and non-Java web developers. Although, remember I am not working for Sun...my opinion comes just from what I've seen. I think JSP itself is the thing Sun is marketing to non-Java web developers, the EL is a perk that will allow for cleaner JSP.

3.) Is this more fashion than function?

Absolutely not. Personally I use the EL extensively in all my JSP projects and I'll never go back to custom tags or scriptlets for showing the value of a request-scoped variable. Why? In short, using something like ${foo} or ${foo.bar} anywhere in a JSP is way too convenient, especially if you consider that you can access an object in any scope (i.e. request, session, application) and that you can disable scripting while doing it.

For the long reasoning why, check out my book, Servlets and JavaServer Pages; the J2EE Web Tier. It walks through what the EL is, how to use it, and why it works a heck of a lot better than scriptlets and custom tags.

4.) Are non-java developers using EL?

Maybe, but I think they are hanging out with the JSP developers that are using non-Java languages in the scriptlets.

Seriously, no one that I know of is actually using the JSP EL outside of Java. However, I think you might have phrased the question slightly off. The JSP EL for a long time was rumored to be made in a fashion that would allow it to be used in any Java app (or just about any non-Java app), and some Java classes that could make sense of EL expressions would be made readily available to all developers. Meaning any Java app could use the EL, not just JSP apps. I think this idea is silly, and isn't worth dwelling on. Things like the EL are good for lots of things, but optimizing the JSP EL for things JSP developers do is what makes it helpful to use. As is, I consider the JSP EL optimized for JSP development.

If you meant, are things like the JSP EL used outside of Java and JSP. Absolutely. The JSP EL is pretty much an adoption of expressions used by other popular projects such as Ant and Velocity. The important concept is that you can split a dynamic web page in to two parts, code to generate dynamic values and a template to display those dynamic values through. The EL is the component that allows a template to take and display a dynamic value. Also, it is important that languages like the EL only allow for simple expressions, not full blown chunks of code such as scriptlets allow for. This helps ensure one is forced to keep business/database code and presentation code separate. Other non-Java technologies pioneered these concepts, and they use EL equivalents.

5.) Does EL make it harder for java developers?

Not really. In the case of JSP, the whole idea is that Java developers don't have to care about the EL. Coding Java is the same as coding Java has always been. However, accessing dynamic values that are placed in request, session, or application scope by Java code in JSP is now trivial thanks to the EL. This is helpful because if you are an HTML developer you can get away with skipping Java knowledge all together. If you assume your buddy the Java developer correctly populates the request-scope variable named "name", you can access it with an EL expression, e.g.:

<html>
Hello ${name}, welcome to the website.
</html>

And teaching someone who knows how to use HTML how to use ${name} takes about two seconds. Likewise, you can generalize this example by assuming the HTML/interface people meet with the Java people and agree upon a set of request-scoped variables, e.g. name, date, favoriteColor, etc. Coding the Java to populate request-scoped variables is the same as it ever was -- if anything it might be made simpler because of how the '.' character does all sorts of great things in the JSP EL.

At a recent JUG, people unanimously said Java code in JSP is bad. In a JSF example involving database access, the group, with the exception of one lady, said that it was OK to use SQL in your JSF/JSP despite the recommendation against it. (She asked "what if your table name changes and you need to change the SQL", to which the group replied "you have a dba/design issue if they change table names on you").

About Java code in JSP. Yeah, pretty much bad, but not always. Remember two things. JSP EL isn't Java code, EL expressions are simple, one-line expressions -- often just something such as ${foo}. The second thing, remember design patterns such as Model 1 1/2 still work really well and they allow for as much Java code in JSP as you want. The drawback is you aren't enforcing that pure Java code is kept away from the HTML. See the book if you don't know about Model 1 1/2 or ask it to be a blarg topic.

About SQL code in JSF/JSP. I have really strong opinions about this. I think you can't ever justify putting SQL in your JSP when you are building a real web app. It just mucks things up in the long run. You'll note, I wrote several paragraphs on why I think this in my book, and I even explain why it isn't worth your time to even consider using stuff such as the JSTL SQL tags. In short, your JUG response is a good one, and if you ever hear someone rambling on about putting SQL in your JSP, ignore them. Odds are they don't really build web applications.

A funny note is that I once made a fool of myself while harboring the above mindset. I was talking to some Sun buddies at JavaOne and I basically explained why I thought it was a horrible idea to have ever considered making the JSTL SQL tags. The argument was well received, but it just so happened the person who put the JSTL SQL tags in the JSTL was part of the discussion...oh how sweet my foot tastes. Sorry queen of taglibs!

My opinion is that <%//Some business/data logic%> and are about the same to non-developer web designers. They both basically say "stay away from this chunk here".To the extent that you can push code out of pages, it's a good thing.But then again, I was a roll-your-own-JDBC guy until I started using hibernate extensively. Now I cringe if I have to type Class.forName("jdbc.xyz...");

I'm taking a guess at what you mean by this. If non-developer web designers (i.e. the HTML folks) see either scriptlets or custom tags they shouldn't touch the code. Fair point, and I think it merits some agreement. However, I think you should always assume the worst, e.g. assume the HTML folks could care less about your code. The best approach is to ensure non-developer web designers can not touch code that they shouldn't be allowed to change. In other words, do not put Java code on a JSP. Give HTML/CSS coder equivalents free reign over the entire presentation page and train them -- in the simplest possible way -- to display dynamic information. Basically, teach them the just of the JSP EL and teach them how the JSTL iteration tag works. Then disable JSP scripting all together, which you can do in JSP 2.0 -- note, JSP EL is not scripting for this case. As for how dynamic values are put in to request, session, or application scope, that is up to you. Look in to Model II.

About Hibernate versus Class.forName(...). That is a really good point. If anyone who is reading this is using Class.forName() with JDBC device drivers, stop...stop now. At least use a DataSource object or at most look in to a full framework for abstracting database connectivity. A little more of a stretch but still a good analogy is comparing scriptlets versus Model II combined with the new EL. Stop using scriptlets, stop now. If you don't know what I'm talking about, ask a blarg or read a good book.

Cheers,
Jayson Falkner - jayson@jspinsider.com



Blarg #2: What do you think about weblogs?

Posted by jfalkner on October 14, 2003 at 03:38 PM | Permalink | Comments (3)

Hi,

I saw your blog on java.net and thought I'd ask a couple of questions....

Do you think all Java/J2EE developers should be blogging, or just those that are senior, or in consultant roles?

Should blog-reading be for general education/feel of the "community", or do you think blogs are only useful when searching for answers to specific problems?

If everyone should blog, where do I go to get blogging? Is it necessary to setup blog software on my own site, or are there loads of sites offering blog capabilities to Java developers that I've so far managed to miss?

Regards,
lee

Hi lee, thanks for asking. I don't think I can fully answer your question, but hopefully I can provide a solid opinion and provide a place where others can add their thoughts. Since you squeezed a few questions in to one e-mail, I'll try to break them up before answering.

Do you think all Java/J2EE developers should be blogging, or just those that are senior, or in consultant roles?

I don't think it is my business to be saying who should and who shouldn't blog. As I understand it, part of blogging is that it is something anyone can do, and I think that implies anyone who wants to blog should blog. However, I would answer the question completely differently if you were asking if I think all blogs are helpful. I have formed the general opinion that most blogs are not good for trying to get work done.

Should blog-reading be for general education/feel of the "community", or do you think blogs are only useful when searching for answers to specific problems?

Again, I don't think I am the one to say what I think blogging should be for. Blogging is popular because anyone can do it and usually there is little to no peer review or editing of what someone blogs. That means blogging is useful for just about whatever a person can blog well about.

However, if we narrow down the question to only consider blogging as a tool to aid Java/J2EE developers. I would say blogging isn't really helpful for either of your options. Once a developer starts searching the web it usually means they have no clue as to what they need to get done, and they are looking for some free, quick answer to their solution. Blogs aren't about that, and that is also why I'm playfully naming these answers "blargs". Blogs are usually just a kind-of popular Java/J2EE figure venting some thoughts. Hopefully my blargs will be popular enough to make people start to think blogs can be helpful for your second option, answers to specific problems. But really, I'm just doing free, no-liability consulting and it happens to be getting publicized via blogging. I don't think that will ever go mainstream.

If we consider the case where you are a Java/J2EE developer who has some spare time on his or her hands, then I think it is fair to say blogs are a good way to feel out the current state of things in the Java/J2EE community. I would equate it to something like slashdot.org. If you are a geek drinking some coffee and killing some time, slashdot is a fun way to feel like you are hip to the tech community. Likewise, if you are a Java person who is just killing time in front of your computer, Java/J2EE blogs can make you feel like you are hip to the current happenings of other developers. Although in both cases it doesn't mean you will be any more productive at work.

If everyone should blog, where do I go to get bloggin? Is it necessary to setup blog software on my own site, or are there loads of sites offering blog capabilities to Java developers that I've so far managed to miss?

If you want to blog you have several options. No, you don't need to set up software on your own site, but you could if you wanted. Usually if you have your own site you can simply edit an HTML page to include your thoughts and call it a blog. But, if you want to have flashy user feedback and such you will need to either do some coding or install an existing package.

In general if you just want to blog you can find a site that will let you do it for free. Off the top of my head I know this site does it (although I never figured out if anyone can start blogging for free) and JavaLobby provides JRoller, http://www.jroller.com/, which you can also get the source-code for if you like. Outside of those two I can't say much beside that I have heard of tons of other free open-source weblog packages, but I don't know any names or links. I think this is a question best left to others to help with. I'm sure a good deal of the people that read this will have a link or two to suggest, and if that is you, please post the link in the talk-back.

Cheers,
Jayson Falkner (jayson@jspinsider.com)



Blarg #1: Are JSP Still Relevant?

Posted by jfalkner on October 09, 2003 at 10:43 AM | Permalink | Comments (23)

Blarg #1: Why are JSPs still relevant?

You seem like the perfect guy to ask.

Let me explain the question;
I'm in projects that run for a very long time, we have to maintain them and add features for at least a year, but probably longer. Having bare JSPs (or even really nice tagged ones) makes this hard to maintain and keep bug-free for a very simple reason; The application programmer has to do the work since there is no clear seperation of content and code. Plus the obvious code duplication etc etc etc.

When I came accross WebMacro/Velocity etc my idea was that JSPs would be considered like c. Nice to hack in, but really not material to write full applications with anymore. I.e they seem like the natural next-step and the old would soon die out.

Are JSP programmers not just holding on to ancient technologies like c-programmers (or pascal, or cobol) are to their unmaintainable stuff?

So; if they are, then why are JSPs still relevant?


Great question zander, and it is one I just so happen to have a lot to say about. You would be surprised how often this type of question seems to pop up, not just about JSP, but about just about any J-starting acronym the marketing folks throw to the masses. In some cases it is valid to ask, say the technology in question really is dated...or it was just pretty worthless in general. However, in the case of JSP, there are several great reasons it is still relevant. I'll address a few of the particular reasons I think are most important, and I'll try to phrase things assuming you don't know much about JSP. I don't mean to be condescending, but far too often this type of question is asked simply because the person doesn't really understand what the J-starting acronym really describes. If you aren't that type of developer, then please bear with me, I'm assuming there are plenty of other developers who will certainly appreciate an answer that doesn't assume much.

My reasons for why JSP is still relevant.

  1. JSP is a key part of the J2EE Web Tier
  2. JSP is The standard
  3. It is easy to use JSP in amazing ways

JSP is a key part of the J2EE Web Tier

J2EE is huge, and almost all of it is good for at least one particular task. People do spend a lot of time (namely JSR expert group people) designing each and every J2EE related technology, which means in general something helpful is made. Note, this does not imply that your work will benefit from every J2EE technology, say JSP in particular. So let us be clear on what JSP is good at, and then you can decided if you are trying to do that, or if you could care less -- either way we should hopefully agree JSP is a technology worth keeping around.

So what is JSP good for? JSP is great for generating dynamic web pages, think any web page that uses markup, e.g. HTML, XHTML, WML, or even just plain text. When I say "dynamic" I mean something that changes. A good example would be an on-line store like Amazon.com that takes a little bit of information from you, say a title of a book, and automatically generates tons of HTML-based web pages that try to get you to purchase something. This is dynamic because Amazon.com certainly doesn't have billions of HTML files saved on their servers, it wouldn't be practical. Amazon.com only keeps around key information about books, and when needed uses JSP to generate HTML on the fly. A bad example of dynamic is something like my personal resume. It is nothing more than an HTML page I update maybe twice a year. It makes a lot of sense to simply code my resume by hand, using only HTML, and let people download it as is.

JSP is really the only good technology to do this in the standard set of Java/J2EE tools. Now that is an over-simplified statement, but it is true. There are several other technologies such as Servlets and JDBC that are almost always used with JSP to get the job done, but if you try to make dynamic web pages without JSP it takes a lot more time and effort.

In summary, I'm saying if you want to make dynamic HTML, XHTML, or text and send it over the World Wide Web, JSP is what you should use. That is why it is important. If you don't want to believe me I'll give a link at the end that does a proper job of arguing this point against the millions of common counter-points developers have. Now to move on....

JSP is The standard

A key thing to understand is that JSP is a standard. It has been around for good deal of time, lots of companies have dumped lots of money in to it, several other technologies are based on JSP, and there are tried and proved successful uses of the technology. In short, I'm saying any other Java technology that is trying to compete with JSP and isn't part of the standard J2EE API is more or less worthless. I don't care if you want to argue that something is more elegant, or that you can show me an open-source project that has a few top quality hacks working on it. None of that matters. JSP does get the job done, JSP can do a great job, and you can make a good living off of programming JSP/J2EE knowing Sun, IBM, Oracle, and a slew of other companies will keep the money flowing. Other projects like WebMacro/Velocity have lost. They are bitter, and they should be. Some really neat ideas and some great code might have been produced, but they certainly won't get much credit when the next version of JSP incorporates those features.

In summary, I'm saying JSP is relevant because it is a standard. As an average developer you should forget anything you hear from other non-standard Java technologies. Sad, but true, especially if you only care about making a living as a Java web programmer.

JSP is easy to use in amazing ways

JSP can be used well, and it can do amazing things. I've spent several years of my life figuring this out. I've tried the alternatives. I know about the other open-source projects. I've helped the JSP expert group. And I've spent a year of my life writing a book about this very topic. If you want to build a good web application that is fast, efficient, and easy to maintain, JSP can do it. If you don't believe me the best I can do is tell you to do some reading. Check out Sun's website, read java.net, read JSP Insider, or simply read my book. And you are right if you are thinking I'm just pushing what I like. I like JSP, but I say that because I've tried just about every other solution to building web applications. I've dealt with the poorly funded open-source solutions, the hyped commercial solutions, and even some home-brewed attempts to improve the state of things. But I think JSP is the best.

In summary, I'm saying that I honestly think JSP is a great technology, and I think I have the experience to fairly say so. Especially considering JSP 2.0, there are far too many helpful things that you can do easily with JSP. If you understand the technology, you will get the job done and you can certainly get the job done well.

And that is why JSP is still a relevant technology. I really wish I had the time to type out each and every bit of knowledge I have on the subject, in particular some of the really slick coding tricks that would completely solve your hard to maintain JSP problems, or reasons you shouldn't bother with stuff like WebMacro/Velocity, but I seriously just got done doing this in a JSP 2.0 and Servlet 2.4 book that went on sale a few days ago. Go buy it if you want an instant fix, or try to ask some specific questions on my points above if you want a slower, free-loader fix. I'll try to answer as many questions as I can as long as you keep sending them to me -- feel free to make them specific so I can try to show some code or talk about JSP 2.0 features.

Jayson Falkner - jayson@jspinsider.com



Blog, blog, blog, why would a professional J2EE developer do this?

Posted by jfalkner on October 08, 2003 at 01:16 PM | Permalink | Comments (13)

Blogging, the shameless method of displaying ones opinions on the net. It makes a person feel important, authoritative, as if the whole world is taking the time to read what they write. I don't like blogs. I fail to see them as much more than another time-leaching distraction on the web. Sure, sometimes you will find a gem or two, but overall it is just another quick information fix for us net junkies.

But wait...what is this? Am I not working on a fix for the community, flicking the web's veins and preparing a sweet dose of subjective writing? No, I'm blargging. Blarg. I don't want to take any of your time. I want to return it. I want to help you get your job done. I want to help you to bedazzle your boss, and I want to send you home satisfied and ready to spend quality time with your family.

What can I do and why would I do it? Well, I can't do everything, but I can help with Servlets, JavaServer Pages, Tomcat, and most all of J2EE. If you are building a Web Application, I'm your man. Why? Well, I'm one of those guys that works full time consulting, helps with JSRs, codes open-source projects, and writes tech material. I am the guy that actually does this stuff all the time; I am a lost cause. I realize this, yet I'm not going to stop. I like this addiction. I like living in front of my laptop, and I like attempting to dispense advice from my quirky knowledge base. Use me. Ask me to help get your work done. Lean on one of the piers of the J2EE Web Tier.

Seriously, this blarg is for you. Send me questions about what I know. I'll answer them in a completely subjective and practical manner. You can find me here, at JSP Insider, at JSPBook.com, or at home. Any of the above will do, but lets see if we can blarg a dent in these java.net blogs.





Powered by
Movable Type 3.01D
 Feed java.net RSS Feeds