Showing posts with label web development. Show all posts
Showing posts with label web development. Show all posts

Saturday, 25 June 2011

We saw how a Servlet handles a Http Request that comes from a web browser here. We also saw that there are many doXXX() methods inside a Servlet that serve a specific purpose. In this chapter we are going look at the XXX part of the Servlet code.

So, lets get started!!!

The doXXX Methods

There are 3 main types of requests that get processed by a Servlet. They are:
  • Get
  • Post
  • Put
Each of them have a corresponding doXXX() method in the Servlet class which would be:
  • doGet
  • doPost
  • doPut

These methods are called by the service method in your Servlet.

Let us now take a look at a sample Servlet that has these 3 doXXX methods.

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

public class OurSecondServlet extends HttpServlet
{
// doGet()
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
requestType("GET", response);
}

// doPost()
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
requestType("POST", response);
}

// doPut()
public void doPut(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
requestType("PUT", response);
}

public void requestType(String requestType,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("< html >");
out.println("< head >");
out.println("< title >Our Second Servlet" +
"< / title >");
out.println("< / head >");
out.println("< body >");
out.println("< h1 >Servlet Request< / h1 >");
out.println("The Submitted Request type is : " + requestType);
out.println("< / body >");
out.println("< / html >");
}
}

How this code works?

As you can see, we have 3 different doXXX methods in our servlet, each of them calling the same method with just one parameter that differentiates them. Ideally in most cases, our code would be like this too. The logic that gets executed is mostly the same irrespective of the type of request submission. So, the doXXX methods, just receive the request, add some identifier that can be used to identify what request is submitted and then calls another method which will eventually be called by the other doXXX methods too.

The delegate method does the actual processing and returns the results.

Friday, 24 June 2011

A sample JSP

We looked how servlet look here. Here, we are going to take a look at a sample JSP file and the contents of the file.

A JSP File Contents:

A JSP file can contain the following:
a. HTML contents
b. JavaScript
c. Java Code

Combining the features of the above 3 mentioned items; we get a powerful entity called the JSP. JSPs are used for the User Interface layer or the more colloquially called Front End layer of any J2EE application.

JSP Skeleton

Below is how a Skeleton JSP File would look like. (The file has to be saved as .jsp)
// Page Imports
<%@ page import = “com.xyz.ClassName %>

// Tag Library References
<%@ taglib URI = “path to Taglib file” prefix = “xx” %>
// here xx refers to the prefix with which the tag library will be referred to

// HTML Head & Title Content

// Java Script Content



// HTML Body & Form Contents

Note: Java code can be placed within the <% %> tags in the body part of the JSP page within the Body tags.

As you can see, a JSP file is pretty straightforward. Also, an important point to note here is the fact that, not all of the entities mentioned above are mandatory. You can include or exclude any of the entities mentioned above, based on your requirement and convenience.

Tomcat will now convert the Java embedded in the JSP to the following:

// begin [file="/jsp/my_first_jsp.jsp";from=(7,3);to=(7,31)]
int val1 = 10, val2=5;
// end

It also generates this version of the try block, which differs slightly from the previous servlet code:

try {

if (_jspx_inited == false) {
synchronized (this) {
if (_jspx_inited == false) {
_jspx_init();
_jspx_inited = true;
}
}
}
_jspxFactory = JspFactory.getDefaultFactory();
response.setContentType("text/html;charset=ISO-8859-1");
pageContext = _jspxFactory.getPageContext(this,
request, response,
"", true, 8192, true);

application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();

// HTML // begin [file="/jsp/my_first_jsp.jsp"...]
out.write("" +
"\r\n< html >\r\n< body >\r\n" +
"I Like Cars, Especially < b > Ferrari < / b >.
\r\n");

// end
// HTML // begin [file="/jsp/my_first_jsp.jsp";from=...]
out.write("\r\n ");

// end
// begin [file="/jsp/my_first_jsp.jsp";from=...]
out.print(val1 * val2);
// end
// HTML // begin [file="/jsp/my_first_jsp.jsp";from=...]
out.write("\r\n\r\n\r\n\r\n");

// end

}

As you can see, Tomcat now takes our val1 and val2 variables that were declared at the top of our JSP page and generates declarations as class variables in the servlet.

So, < % - val1 & val2 % > becomes

out.print(val1*val2);

Once the conversion is complete, this servlet will be compiled and loaded to memory. Every call to invoke this JSP will make Tomcat compare the modification date of the loaded servlet with the date of the JSP. If it is the same, the compiled servlet is executed and contents displayed on screen. Else, if it sees that the JSP has changed, it will recompile the JSP and load the newly converted Servlet instead of the older version.

JSP to Servlet conversation

In the previous chapter, we took a look at how a JSP file looks like and the contents that can be present inside a typical JSP file.

As you might already know (If you have J2EE programming experience) a JSP file gets converted into a Servlet at runtime and then gets executed. Well, if you did not know this, don't worry. That is what this chapter is for. To tell you the fact that JSPs get converted into Servlets for execution and also to tell you how that happens.

So, lets get started!!!

JSP to Servlet Conversion

JSPs are converted to servlets before the container runs them. This is actually cool because you don't need hardcore java programming skills to create a JSP page whereas you’ll need them to write a servlet. Moreover, all you’ll need to write a JSP is some expertise in creating HTML files and in using JavaScript. You can create front-end JSP pages without having much expertise in Java at all. Although JSP reduces the required skill level, JSP becomes a servlet, with the nice performance and portability benefits.

Below is how the conversion happens.

First lets look at a sample JSP page that we will consider for this conversion process. It's the same sample JSP we saw in the previous chapter. Lets name this guy my_first_jsp.jsp
Sample JSP File Code:

<html>
<body>
I Like Cars, Especially Ferrari .
</body >
</html >


This JSP file has to be placed in the …\jakarta-tomcat-4.0.1\webapps\examples\jsp folder in our system. To access this JSP through the tomcat server we can use the below URL:

http://localhost:8080/examples/jsp/my_first_jsp.jsp.

When you hit enter after typing the contents above in the browsers address bar, tomcat covnerts this JSP into a servlet, compiles it and then invokes it.

The servlet that gets created will be placed in …\jakarta-tomcat-4.0.1\work\localhost\examples\jsp as my_0005fservlet$jsp.java.

The contents of this converted Servlet would be as below:

package org.apache.jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import org.apache.jasper.runtime.*;

public class my_0005fservlet$jsp extends HttpJspBase {

static {
}
public my_0005fservlet$jsp( ) {
}

private static boolean _jspx_inited = false;

public final void _jspx_init()
throws org.apache.jasper.runtime.JspException {
}

public void _jspService(HttpServletRequest request,
HttpServletResponse response)
throws java.io.IOException, ServletException {

JspFactory _jspxFactory = null;
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
String _value = null;
try {

if (_jspx_inited == false) {
synchronized (this) {
if (_jspx_inited == false) {
_jspx_init();
_jspx_inited = true;
}
}
}
_jspxFactory = JspFactory.getDefaultFactory();
response.setContentType("text/html;charset=" +
"ISO-8859-1");
pageContext = _jspxFactory.getPageContext(this,
request, response, "",
true, 8192, true);

application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();

// HTML // begin [file="/jsp/my_first_jsp.jsp"]
out.write(">
\r\n< html >\r\n< body >"+
"\r\nI Like Cars, Especially Ferrari ."+
"\r\n\r\n\r\n");

// end

} catch (Throwable t) {
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (pageContext != null)
pageContext.handlePageException(t);
} finally {
if (_jspxFactory != null)
jspxFactory.releasePageContext(pageContext);
}
}
}

A point to note here is that, the exact code that gets generated for your Servlet might vary slightly and may not exactly match what is given above.

As you can see, Tomcat does a lot of work when it converts our JSP into a servlet. If you look at the source that is sent to your browser, you will see the original HTML in the JSP file.
Well, the above example was a little too easy and in reality we will have some Java code too in our JSP. So, lets take a look at how the conversion happens if we put some java code into our earlier example.

Our Modified JSP:

<html>
<body>
I Like Cars, Especially Ferrari .

<% ! int val1 = 10, val2=5; %>
<% = val1 * val2 %>

//Close the html and body tags here too


Saturday, 18 June 2011

A Sample Servet

We saw what the purpose of a Servlet Container and a Web server is, in the previous chapter. In this chapter, we are going to look at how a Servlet code would look like.
So, lets get started!!!
Servlet Skeleton
If I ask you, what are the components of a Java class, you’ll happily tell me that, there are first package statements and then imports and then the class declaration. Within the class brackets, we have constructors, instance variables, methods etc. That was easy, wasn’t it?
The same way, every Servlet has a certain set of components that are mandatory for its well-being. (I just got carried away a bit) Or I must say, for its proper functioning.
A Servlets skeleton would look like below:

/*
* servlet name
*
* servlet description
* All other stuff that is part of a Standard Class comment section
*/

//package declarations

//import statements

public class ServletName extends HttpServlet {

// Instance Variables

/**
* Code to Initialize the Servlet
*/
public void init() throws ServletException
{
// Servlet Initialization Code goes here
}

/**
* The Service Method
* Gets invoked for every request submitted to the Servlet
* This method is optional. We mostly use doGet, doPost Methods
*/
protected void service(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException
{
// Code for the Service Method goes here
}


/**
* Process a GET request
*
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
// Code for the doGet() method goes here
}

/**
* Process a POST request
*
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
// Code for the doPost() method goes here
}

/**
* Process a PUT request
*
*/
protected void doPut(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException
{
//Code for the doPut() method goes here
}

/**
* You can have any number of methods for your processing
* here. There is no limit as to the number of methods or
* any restrictions on what you can name them.
* Since this is all java code, you need to keep them
* syntactically correct as per Java Coding Standards.
*/

/**
* Clean-Up
*/
public void destroy()
{
// clean up activities before the Servlet is put to death
}
}
The above is what a Servlets skeleton would look like. Now let us take a look at some sample code as to how a properly coded Servlet would look like:


import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.PrintWriter;
import java.io.IOException;


public class OurFirstServlet extends HttpServlet
{

public void service(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("< html >");
out.println("< head >< title >Servlet Example " +
" ");
out.println("< body >");
out.println("Not Much code, but this is enough for a Servlet.");
out.println("");
out.println("");
}
}


The above is a simple Servlet. It would display an almost blank HTML page that contains the message we put in “Not Much code, but this is enough for a Servlet.”
Note: A Servlet is not a simple java class, that you can run using a main() method. You have deploy this Servlet on a web server in order to view the output. Lets not get too ahead of ourselves here. We’ll be looking at all that later in detail. For now, this is how a Servlet would look like and that wraps up our current chapter.


Web Servers and servlet containers

In the previous chapter we looked at the history of the Web (Internet) and how JSPs and Servlets came into being. As you might have already guessed by now, any J2EE application needs a server on which it runs. It is called a Web Server. Also, the Servlet needs something in which it would run (Think of the JVM in which all java applications run) and that is called the Servlet container.
In this chapter, we are going to take a look at these two entities.
So, lets get started!!!
Web Servers and Servlet Containers
A servlet is nothing but Java code that runs in a container. It generates HTML & other contents that get displayed in the web page that we see. It is purely coded in Java, so the benefits and restrictions of all regular Java classes apply here too. Servlets are compiled to form a platform neutral bytecode (All java code is platform neutral, isnt it? Serlvet is no different). Upon request, this bytecode file is loaded into a container. Some containers (servlet engines) are integrated with the Web server, while others are plug-ins or extensions to Web servers that run inside the JVM. Servlets look the same as static Web pages to the client, but they really are complete programs capable of complex operations.
The servlet container is an extension of a Web server in the same way CGI, ASP, and PHP are. A servlet functions just like them, but the language in which it is written is Java. That's the main difference. The servlet doesn't talk to the client directly. The Web server functions as the intermediary that does it for the servlet. In a chain of processes, the client sends a request to the Web server, which hands it to the container, which hands it to the servlet. The Servlet processes the request and generates a response. The response starts from the servlet and goes to the container and then to the Web server and back to the client. Of course there are several other steps that happen too but this is just the introduction so this much would suffice I believe.
The servlet architecture makes the container manage servlets through their lifecycle. The container invokes a servlet upon receiving an HTTP request, providing that servlet with request information and the container configurations. The servlet uses this to do its job which is processing the data it received as part of the request. When finished, it hands back HTML and objects that hold information about the response. The container then forms an HTTP response and returns it to the client which inturn displays the stuff sent by the Servlet on screen in the web browser.
Below is a simple illustration of the flow of control that starts and ends at the Web Browser. Control starts at the browser, goes to the server and then to the container which in turn invokes the Servlet. Our Servlet happily does the processing (which might involve hitting a database) and returns the data to the container which in turn passes it on to the web server which finally displays the contents on the web browser.

The Servlet container is often written in Java, since it eventually runs inside a JVM. However, some vendors implement their containers in different languages (they aren’t essentially bound to Java). The point here is the fact that, all we need is a servlet container that can read and execute our servlets. The language in which it is implemented is not necessarily important for us.

Servlet and JSP history

Early in the 1950’s computer scientists in USA were working their backsides off in order to compete with Soviet Unions (The late USSR) advancements in superpower computing. They formed the Advanced Research Projects Agency (ARPA) in the year 1957. In those they still had powerful computers, but they weren’t able to talk or communicate with one another. In 1966 Lawrence G. Roberts (From MIT) proposed the first computer network which was named the ARPANET. The US Department of Defense (DoD) funded the venture and it took them 3 years to implement the network. The ARPANET team rewarded the DoD by establishing the Network Control Protocol (NCP), the first host to host protocol, which made possible for the university and the research center PC’s to communicate with one another.
With the success of the NCP, telco major AT&T installed the first cross country link between UCLA and BBN. It was a humble beginning and by 1973 hundreds of computers were talking to one another.
The real big breakthrough came in the year 1982 when the TCP/IP standard was established by Vint Cerf and Bob Kahn. Based on this development, the Domain Name System was established and by 1984 there were over 1000 hosts registered.
This was the backbone of the current day Internet. It was called NSFNET originally and with multiplying hosts it was becoming difficult to manage. By 1991 there were over a hundred thousand hosts and the system was getting out of control. There was nobody incharge and there was utter chaos all around.
In 1991, Tim Berners Lee created hyperlinks. He invented the whole protocol that made links communicate with one another and the World Wide Web was born. Telnet, email and many other services started using the networks.
In 1993, Marc Anderson and his friends wanted to see what was on the Internet, so they developed a new program called the NCSA Mosaic at the University of Illinois based on Berners Lee’s ideas. (NCSA stands for National Center for Supercomputing Applications)
Mosaic was the catalyst that caused the internet to explode. Nearly 200 million hosts were in use by the end of the decade and more than 1 billion users were using it.
This was not the end of it. Mobile phones, PDAs, GPS, Cars etc started connecting to the internet and the number of users began growing beyond numbers that we can write down or calculate.
It all started with basic HTML pages and hungry scientists created more and more advanced technologies whose powers were unbelievable. JSPs and Servlets just changed the landscape catastrophically and here we are, studying them to become better J2EE web programmers!!!
History of JSP & Servlets
The Internet's original purpose was to access and copy files from one computer to another. While TCP/IP provided a highway layer, the File Transfer Protocol (FTP) specification provided a standard way to exchange those files. It defined a way of shuttling them back and forth, but said nothing about looking at the content. HyperText Markup Language (HTML) allowed us to see the documents on the Internet. FTP can transmit HTML files just as easily as HTTP can. But we use Hypertext Transfer Protocol (HTTP) to act as an FTP specifically for HTML documents because it is a stateless protocol which makes having many short connections more efficient.
HTTP is the plumbing that connects the various computers. Now it is time to discuss about the fluid that flows through it “JSP & Servlets”
Note: JSP & Servlets arent the only technologies that are used in J2EE applications. Struts, Hibernate, Springs etc are other technologies that are used in J2EE Web applications. But, don't worry about them because they arent in the exam.
Using HTTP and HTML people were able to view/browse files and contents on a remote server. This is very useful, but people wanted live data. This is where the CGI (Common Gateway Interface) specification helped us. It helped us connect to databases and display stuff on the fly. The CGI specification was a major breakthrough in Web Application Development. The CGI standards made sure that the same CGI program worked on different Web servers.
CGI became the bread and butter of web developers. It was the most common means of displaying dynamic content on the internet. Though it was good, it wasn't good enough. It was not able to handle the performance requirements of the bursting Internet users. It was literally too much for it.
If you are asking me why CGI couldn't handle the load, the answer is simple. CGI spawned a separate process for every request that it receives. This design was able to sustain during off-peak hours but ate off server resources during peak loads which was eventually too much for it.
With growing numbers of users of web applications, scalability became a key consideration which wasn't CGI’s Middle Name and hence people started exploring other options.
Many CGI derivatives came up as server-side programming solutions that implement business logic, including ASP, ColdFusion, PHP, and Perl. Java surpassed them all due to portability and its object oriented programming design.
Alas, he we are, learning JSPs and Servlets that are the children of the Java Family which make our lives all the more easier in the world of Web Development.
Java was conceptualized in 1991 but it wasn't in the internet programming world until 1997. Servlets were the alternative to CGI and were released in 1997. Unlike CGI, which starts a process for each request, Servlets just spawn a new thread. Servlets had a better or rather efficient architecture which was able to handle the loads of the internet.
Though Servlets were awesome when compared to CGI, they still had some issues when it came to displaying dynamic content on a web page. Thankfully, Sun released the JSP (Java Server Pages) specifications in 1998, which solved all our UI woes. JSPs enabled programmers to display dynamic HTML content that could also use Java features. The combination of JSPs and Servlets was just what the Doctor Prescribed and it just revolutionized the Web Programming industry.
That's it for the history lesson. Now we are all set to dive deep into the world of magical Servlets and JSPs.

Sunday, 15 May 2011

JSP compilers

We can compile a JSP manually.
The JSP compiler(JSPC) depends on the Web Container. Eg. take, BEA WebLogic Application Server.

  • goto DOS Shell and run "setEnv.cmd"
  • using cd command move to the JSP file directory.
  • run " java weblogic.jspc -keepgenerated JspOne.jsp "

Note : if " -keepgenerated " is not used on above command, the JSPCompiler removes the .java file which is generated by JSPC.

Wednesday, 27 April 2011

Jetty tutorial

Jetty is a lightweight Servlet container which we suggest you use if you are going to develop servlets on your local machine, please don't run it on eniac.

Getting Jetty

  1. Make sure you have a Java SDK installed, you can download one here.
  2. Download the latest version of Jetty (6.1.11).
  3. Extract the zip archive to somewhere on your computer.
  4. Open a command line terminal and navigate to the directory where you extracted the archive.
  5. Run the command:
    java -jar start.jar
    The server will start and log messages should start appearing in the terminal.
  6. Open a web browser and enter "http://localhost:8080" in the address bar.
  7. If you see a "Welcome to Jetty 6" page then the server is successfully set up. Return to the terminal and press Control-C to stop the server.

Writing a Simple Web Application

The Jetty server has a directory called "webapps" which contains a directory for every website (web application) it hosts. We will create a simple application and place it in this directory.
  1. Make a new directory called "hello" in "webapps". Files in this directory will be accessible as "http://localhost:8080/hello".
  2. Make a new directory called "WEB-INF" in "hello". This directory will contain configuration information for your application.
  3. Make a new directory called "classes" in "WEB-INF". This directory will contain the .class files for all your servlets.
  4. Create a file "index.html" in "hello". This is the page you will get when you go to "http://localhost:8080/hello". The file should contain the following:
    <html>
    <head><title>Example Web Application</title></head>
    <body>
    <p>This is a static document with a form in it.</p>
    <form method="POST" action="servlet"/>
    <input name="field" type="text" />
    <input type="submit" value="Submit" />
    </form>
    </body>
    </html>
    If you start the server at this point and click here you will see this new page.
  5. Next we will create the handler for this form, which will be a Java Servlet. Create a file called HelloServlet.java with the following code:
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;

    public class HelloServlet extends HttpServlet
    {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
    {
    String q = req.getParameter("q");
    PrintWriter out = resp.getWriter();

    out.println("<html>");
    out.println("<body>");
    out.println("The paramter q was \"" + q + "\".");
    out.println("</body>");
    out.println("</html>");
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
    {
    String field = req.getParameter("field");
    PrintWriter out = resp.getWriter();

    out.println("<html>");
    out.println("<body>");
    out.println("You entered \"" + field + "\" into the text box.");
    out.println("</body>");
    out.println("</html>");
    }
    }
  6. To compile this class we need the servlet libraries, which are not part of the Java SDK, but can be found in Jetty. Use the following command (in the directory with HelloServlet.java) to compile your servlet:
    javac -cp PATH_TO_JETTY/lib/servlet-api-2.5-6.1.11.jar HelloServlet.java
    The "-cp" option adds the given jar file to the list of places to search for other classes your code requires. Copy the resulting HelloServlet.class file into the "hello/WEB-INF/classes" directory.
  7. Now, we must tell Jetty that this class should be used to handle requests. The following "web.xml" file, which goes in the WEB-INF directory, describes these mappings:
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app>
    <display-name>Example</display-name>

    <!-- Declare the existence of a servlet. -->
    <servlet>
    <servlet-name>HelloServlet</servlet-name>
    <servlet-class>HelloServlet</servlet-class>
    </servlet>

    <!-- Map URLs to that servlet. -->
    <servlet-mapping>
    <servlet-name>HelloServlet</servlet-name>
    <url-pattern>/servlet</url-pattern>
    </servlet-mapping>
    </web-app>
  8. If you restart the server you should be able to click here, enter something in the form, and the servlet will respond when you click "Submit".
Note, there are two methods in a servlet class, doGet() and doPost(). These correspond to the two types of HTTP requests. The form we have uses the POST method. It could also use the GET method. The difference is that in the GET method the parameters are passed as part of the URL, which is inappropriate for most web forms. Try entering "http://localhost:8080/hello/servlet?q=Hello" into your browser to see how passing parameters with the GET method works.
If you have any questions, please post to the class newsgroup so others can benefit from the answer.


References:
http://wiki.eclipse.org/Jetty/Tutorial/Embedding_Jetty
http://wiki.eclipse.org/Jetty/Tutorial/Jetty_HelloWorld

Monday, 25 April 2011

Java PrintWriter character encoding example

Some peculiarities about Java PrintWriter:
  1. PrintWriter never throws any exceptions. From JavaDoc:

    Methods in this class never throw I/O exceptions, although some of its constructors may. The client may inquire as to whether any errors have occurred by invoking checkError().

    When error occurs, you'll never know anything more than that it occured, because checkError returns boolean.
  2. When a character is out of the range of the character encoding of the PrintWriter, it prints a question mark (?). But this is not an error.


Test code:
import java.io.*;

public class TestPrintWriter {
public static void main(String[] args) throws Exception {
// abçdef
String latin1 = "ab\347def";

// Unicode for Chinese characters for welcome
String chinese = "\u6B22\u8FCE";

PrintWriter pw;
if (args.length > 0) {
pw = new PrintWriter(
new OutputStreamWriter(
System.out,
args[0]
)
);
}
else {
pw = new PrintWriter(System.out);
}

// print out strings with default encoding, or encoding
// specified as argument.
pw.println(latin1);
pw.println(chinese);
System.out.println("Any error? " + pw.checkError());
}
}


Latin1 test result:
java TestPrintWriter iso-8859-1 | od -bc
0000000 141 142 347 143 144 145 146 015 012 077 077 015 012 101 156 171
a b 347 c d e f \r \n ? ? \r \n A n y
0000020 040 145 162 162 157 162 077 040 146 141 154 163 145 015 012
e r r o r ? f a l s e \r \n
0000037


UTF-8 test result:
java TestPrintWriter utf-8 | od -bc
0000000 141 142 303 247 143 144 145 146 015 012 346 254 242 350 277 216
a b 303 247 c d e f \r \n 346 254 242 350 277 216
0000020 015 012 101 156 171 040 145 162 162 157 162 077 040 146 141 154
\r \n A n y e r r o r ? f a l
0000040 163 145 015 012
s e \r \n
0000044


Also, the constructor throws a FileNotFoundException when you try to write to a read-only file:
C:\work>java TestPrintWriter
Exception in thread "main" java.io.FileNotFoundException: C:\tmp\ReadonlyFile.txt (Access is denied)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:179)
at java.io.FileOutputStream.<init>(FileOutputStream.java:70)
at java.io.PrintWriter.<init>(PrintWriter.java:146)
at TestPrintWriter.main(TestPrintWriter.java:25)

Servlet filter mapping exclude pattern

Once you apply a filter to a URL pattern:
<filter-mapping>
<filter-name>theFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

there's no option in web.xml to exclude a more specific pattern such as: /public/*.

But you can put the exclusion logic in the filter itself:
<filter>
<filter-name>theFilter</filter-name>
<filter-class>org.demo.CustomServletFilter</filter-class>
<init-param>
<param-name>excludePatterns</param-name>
<param-value>public/*</param-value>
</init-param>
</filter>


And in the filter code:
public void init(FilterConfig cfg) throws ServletException {
this.excludePatterns = cfg.getInitParameter("excludePatterns");
.
.
.
}

public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
String url = request.getRequestURL().toString();
if (matchExcludePatterns(url)) {
chain.doFilter(request, response);
return;
}
.
.
.
}

Saturday, 16 April 2011

Getting Started with AJAX using Java (contd.)

web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"id="WebApp_ID" version="2.5">
<display-name>Getting Started with AJAX using JAVA</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>helloWorld</servlet-name>
<servlet-class>com.vaani.sample.ajax.HelloWorld</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>helloWorld</servlet-name>
<url-pattern>/helloWorld.do</url-pattern>
</servlet-mapping>
</web-app>


Output of Hello World AJAX
Before AJAX call:

After AJAX call:
I have used text response to demonstrate AJAX.

Getting Started with AJAX using Java


AJAX is an acronym for Asynchronous JavaScript And XML. AJAX provides an ability to communicate with the server asynchronously. Here asynchronous is the keyword. To explain that in simple terms, you can send a request to server and continue user interaction with the user. You need not wait for response from the server. Once the response arrives, a designated area in UI will update itself and reflect the response information. Whole page need not be reloaded.
This is achieved by AJAX using XMLHttpRequest object. Your browser provides the capability for XMLHttpRequest object. Most modern browsers provides support for XMLHttpRequest. This object helps for http request and process XML response. It is not mandatory that you should use only XML. Simple text can also be used in Ajax but which is uncommon.
Before continuing with the article, I assume that you have basic knowledge about http headers, request response mechanism, different method types and response codes. If you lack knowledge in these areas, it is better to update them before proceeding. If you cant read GET, POST, HTTP status 200 OK and response Content-Type: text/html, xml then you must know these topics before learning AJAX. I am not writing in detail about them here, because each one of them calls for a detailed separate article.
Let me write a HelloWorld ajax web application to demonstrate basics. We shall have a button with name ‘Say Hello!’ On click of that button, without reloading the whole page we will display “Hello World!” by replacing the ‘Say Hello!’ button. Following source code listing contains complete code of sample web application.


index.jsp


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Getting Started with AJAX using JAVA</title>
  <meta http-equiv="Content-Type"content="text/html; charset=utf-8" />
  <script type="text/javascript"language="javascript" src="ajax.js"></script>
</head>
<body>
  <div>Getting Started with AJAX using JAVA: Hello World!</div>
  <div id="hello"><button type="button"onclick="makeRequest()">Say Hello!</button></div>
</body>
</html>

index.jsp contains a div ‘hello’. That is the div which XMLHttpRequest object is going to overwrite with response from Servlet. On click of the button we call a java script function makeRequest(). Until now, there is nothing special. Its usual jsp and javascript call. Ajax is not in the picture.

Now go through makeRequest() given below. Inside that we call getXMLHttpRequest() which returns a XMLHttpRequest object. That can be used as a utility method in all your AJAX programs. Thats an attempt to standardization. Different versions of browsers provide different ways of creating XMLHttpRequest. We are covering all possible combinations inside that method.

Once we get XMLHttpRequest object, we need to register a function which will be called on state change. Now its time to explain in detail about XMLHttpRequest object.


XMLHttpRequest properties and events

XMLHttpRequest consists of properties readyState, status, statusText, responseText and responseXML.
  • readyState denotes states as 0 – UNINITIALIZED, 1 – LOADING, 2 – LOADED, 3 – INTERACTIVE, 4 – COMPLETE.
  • status is HTTP status code for the response
  • statusText is HTTP status message for the status code
  • responseText is response text from server
  • responseXML is DOM document object of reponse XML document from server
XMLHttpRequest contains an event ‘onreadystatechange’. It is invoked whenever ‘readyState’ property given above changes.
We need to register a function for the above event ‘onreadystatechange’. In our makeRequest(), after getting xmlHttpRequest object we register getReadyStateHandler(xmlHttpRequest). Therefore whenever there is a state change, this function will be called by the XMLHttpRequest / browser.
After registering the callback funtion we set the request url as the HelloWorld servlet. In web.xml we have done the servlet mapping for that servlet.
In getReadyStateHandler function, if readyState is 4 and http status code is 200 then we set the reponse text from XMLHttpRequest object to the div hello in index.jsp.


ajax.js


/*
 * creates a new XMLHttpRequest object which is the backbone of AJAX,
 * or returns false if the browser doesn't support it
 */
function getXMLHttpRequest() {
  var xmlHttpReq = false;
  // to create XMLHttpRequest object in non-Microsoft browsers
  if (window.XMLHttpRequest) {
    xmlHttpReq = new XMLHttpRequest();
  else if (window.ActiveXObject) {
    try {
      // to create XMLHttpRequest object in later versions
      // of Internet Explorer
      xmlHttpReq = newActiveXObject("Msxml2.XMLHTTP");
    catch (exp1) {
      try {
        // to create XMLHttpRequest object in older versions
        // of Internet Explorer
        xmlHttpReq = newActiveXObject("Microsoft.XMLHTTP");
      catch (exp2) {
        xmlHttpReq = false;
      }
    }
  }
  return xmlHttpReq;
}
/*
 * AJAX call starts with this function
 */
function makeRequest() {
  var xmlHttpRequest = getXMLHttpRequest();
  xmlHttpRequest.onreadystatechange = getReadyStateHandler(xmlHttpRequest);
  xmlHttpRequest.open("POST","helloWorld.do"true);
  xmlHttpRequest.setRequestHeader("Content-Type",
      "application/x-www-form-urlencoded");
  xmlHttpRequest.send(null);
}
/*
 * Returns a function that waits for the state change in XMLHttpRequest
 */
functiongetReadyStateHandler(xmlHttpRequest) {
  // an anonymous function returned
  // it listens to the XMLHttpRequest instance
  return function() {
    if (xmlHttpRequest.readyState == 4) {
      if (xmlHttpRequest.status == 200) {
        document.getElementById("hello").innerHTML = xmlHttpRequest.responseText;
      else {
        alert("HTTP error " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText);
      }
    }
  };
}
A simple Hello World servet sending response as Hello World! as text.


HelloWorld.java


package com.vaani.sample.ajax;
import javax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
public class HelloWorld extends HttpServlet {
  /**
   * A simple HelloWorld Servlet
   */
  public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws java.io.IOException {
    res.setContentType("text/html");
    res.getWriter().write("Hello World!");
  }
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws java.io.IOException {
    doPost(req, res);
  }
}

See web.xml and response here.