Archive for July, 2009

Example of simple tag with dynamic row data: iterating the body

Here are all the code for demonstrating how to use a simple tag with dynamic row data.
1. TLD file “test.tld” under WEB-INF directory. I saw many people asking how to make TLD file online, you just create a file named .tld, that’s all. Eclipse doesn’t provide IDE tools to help.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
	<jsp-version>2.0</jsp-version>
	<short-name>testing</short-name>
	<uri>simpleTags</uri>
	<description>This is a demonstration tag library</description>
	<tag>
		<name>simple4</name>
		<tag-class>com.programcreek.test.SimpleTagTest</tag-class>
		<body-content>scriptless</body-content>
	</tag>
</taglib>

2. A JSP page “result.jsp”

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="myTags" uri="simpleTags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Testing Custom Tag</title>
</head>
<body>
	<table border="1">
		<myTags:simple4>
		<tr>
			<td> 
				${movie}
			</td>
		</tr>
		</myTags:simple4>
	</table>
</body>
</html>

3. Tag handler class “SimpleTagTest”

package com.programcreek.test;
 
import java.io.IOException;
 
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
 
public class SimpleTagTest extends SimpleTagSupport {
	String[] movies = {"monsoon Wedding", "Saved", "Fahrenheit 9/11"};
 
	public void doTag() throws JspException, IOException{
		for(int i = 0; i < movies.length; i++){
			getJspContext().setAttribute("movie", movies[i]);
			getJspBody().invoke(null);
		}
 
	}
}

Java file upload in Servlet using Apache commons FileUpload component (sample code)

This should be a very simple program, but it took me some time to figure out how to use Apache commons FileUpload component. Since nobody will read this, I put it here only for my own reference. Be careful about how to save the uploaded files to server. The HTML code for Form is too simple and can find everywhere, so the following is only the code of doPost method in servlet.

protected void doPost(HttpServletRequest res, HttpServletResponse response)
			throws ServletException, IOException {
 
		// Commons file upload classes are specifically instantiated
		FileItemFactory factory = new DiskFileItemFactory();
 
		ServletFileUpload upload = new ServletFileUpload(factory);
		ServletOutputStream out = null;
 
		try {
			// Parse the incoming HTTP request
			// Commons takes over incoming request at this point
			// Get an iterator for all the data that was sent
			List items = upload.parseRequest(res);
			Iterator iter = items.iterator();
 
			// Set a response content type
			response.setContentType("text/html");
 
			// Setup the output stream for the return XML data
			out = response.getOutputStream();
 
			// Iterate through the incoming request data
			while (iter.hasNext()) {
				// Get the current item in the iteration
				FileItem item = (FileItem) iter.next();
 
				// If the current item is an HTML form field
				if (item.isFormField()) {
					// Return an XML node with the field name and value
					out.println("this is a form data " + item.getFieldName() + "<br>");
 
					// If the current item is file data
				} else {
					// Specify where on disk to write the file
					// Using a servlet init param to specify location on disk
					// Write the file data to disk
					// TODO: Place restrictions on upload data
					File disk = new File("C:\\uploaded_files\\"+item.getName());
					item.write(disk);
 
					// Return an XML node with the file name and size (in bytes)
					//out.println(getServletContext().getRealPath("/WEB_INF"));
					out.println("this is a file with name: " + item.getName());
				}
			}
 
			// Close off the response XML data and stream
 
			out.close();
			// Rudimentary handling of any exceptions
			// TODO: Something useful if an error occurs
		} catch (FileUploadException fue) {
			fue.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
 
	}

Put Database Connection to ServletContextListener

ServletContextListner is helpful in informing about context Initilazation and destruction. In a typical content management web system, there is always a database behind. The example demonstrate how to connect MySQL database during context initialization stage.
Tools and packages:
eclipse and JDBC MySQL Connector.

1. Create a dynamic web project TestServlet, import the connector .jar file to the project. The jar file will be in the lib directory.
Create a database “testdb” and a table “user”. Put some records inside for testing connection later.

2. Put a listener element in the web.xml Deployment Descriptor and also put the database configuration in it.

< ?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>TestServlet</display>
  <welcome -file-list>
    </welcome><welcome -file>index.html</welcome>
    <welcome -file>index.htm</welcome>
    <welcome -file>index.jsp</welcome>
    <welcome -file>default.html</welcome>
    <welcome -file>default.htm</welcome>
    <welcome -file>default.jsp</welcome>
 
  <listener>
    </listener><listener -class>com.programcreek.testservletlistener.myServletListener</listener>
 
  <context -param>
    <param -name>url</param>
    <param -value>jdbc:mysql://localhost/</param>
  </context>
  <context -param>
  	<param -name>database</param>
  	<param -value>testdb</param>
  </context>
  <context -param>
  	<param -name>user_name</param>
  	<param -value>xiaoran</param>
  </context>
  <context -param>
  	<param -name>password</param>
  	<param -value>xiaoran</param>
  </context>
  <servlet>
    <description></description>
    <display -name>testClass</display>
    </servlet><servlet -name>testClass</servlet>
    <servlet -class>edu.uams.testservlet.testClass</servlet>
 
  <servlet -mapping>
    </servlet><servlet -name>testClass</servlet>
    <url -pattern>/testClass</url>
 
 
</web>

3. Create a listener class “myServletListener” Continue »