blog.Ring.idv.tw

Servlet

Jetty - Java HTTP Servlet Server

.2008-12-15 新增Apache Commons DBCP範例

大約六、七年前剛開始初學Web Application的時候~ 那時常聽到的是TomcatResin~ 至於Jetty... 嗯~ 我聞不見其名...XD

Jetty.是一個100%以Java撰寫而成並開放源碼的HTTP Server & Servlet Container~ 從三年前的「Jetty vs. Tomcat vs. Resin: A Performance Comparison」這篇文章來看~ 它的效率似乎表現不錯~ 好了~ 回歸重點~ 為什麼我對它燃起了興趣?... 二個原因,其一,到目前Hadoop 0.19.0版所內建的Servlet Container就是採用Jetty 5.1.4~ 不過根據「(#HADOOP-1650) Upgrade Jetty to 6.x - ASF JIRA」這個issue來看~ 0.20版就會變成Jetty 6.x版了~

另一個原因,由於今年年初有協助老師將一個「English Collocations」的雛型系統改寫成Web版~ 而這樣的系統其實只需要「唯讀」資料庫的內容即可~ 想將整個這樣的系統都做成「DVD-ROM」版本~ 這樣就變成可以帶著跑的Web Application了~ 方便性大大的提高~ 所以Jetty相當適合這樣的應用!!

下面簡單地記錄一下一些常用的設定及步驟:

啟動Jetty Sever

java -jar start.jar etc/jetty.xml

手動增加一個新的Web Application (含VirualHost設定)

請修改「/etc/jetty.xml」。

<New class="org.mortbay.jetty.webapp.WebAppContext">
	<Arg><Ref id="Contexts"/></Arg>
	<Arg><SystemProperty name="jetty.home"/>/webapps/webapp</Arg>
	<Arg>/webapp</Arg>
	<Set name="defaultsDescriptor"><SystemProperty name="jetty.home" default="."/>/etc/webdefault.xml</Set>
	<Set name="VirtualHosts">
	<Array type="java.lang.String">
		<Item>localhost</Item>
	</Array>
	</Set>
</New>

測試Servlet - Hello World

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

public class Test extends HttpServlet
{
	public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
	{
		res.setContentType("text/html");
		PrintWriter out = res.getWriter();
		out.println("<html>");
		out.println("<head><title>Hello</title></head>");
		out.println("<body>");
		out.println("HIHI");
		out.println("</body>");
		out.println("</html>");
	}
}

修改「web.xml」

<servlet>
	<servlet-name>Hello</servlet-name>
	<servlet-class>Test</servlet-class>
</servlet>
<servlet-mapping>
	<servlet-name>Hello</servlet-name>
	<url-pattern>/Hello.do</url-pattern>
</servlet-mapping>

最後開啟「http://localhost:8080/webapp/Hello.do」即可。

PostgreSQL - ConnectionPoolDataSource

請修改「/etc/jetty.xml」。

<New id="DSTest" class="org.mortbay.jetty.plus.naming.Resource">
	<Arg>jdbc/DSTest</Arg>
	<Arg>
	<New class="org.postgresql.ds.PGConnectionPoolDataSource">
		<Set name="User">postgres</Set>
		<Set name="Password">xxx</Set>
		<Set name="DatabaseName">test</Set>
		<Set name="ServerName">localhost</Set>
		<Set name="PortNumber">5432</Set>
	</New>
	</Arg>
</New>

修改「web.xml」。

<resource-ref>
	<description>My DataSource Reference</description>
	<res-ref-name>jdbc/DSTest</res-ref-name>
	<res-type>javax.sql.DataSource</res-type>
	<res-auth>Container</res-auth>
</resource-ref>

一個簡單的測試程式如下:

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

public class PostgresDBTest extends HttpServlet
{
	public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
	{
		res.setContentType("text/html");
		PrintWriter out = res.getWriter();
		
		Connection con = null;
		Statement stmt = null;
		ResultSet rs = null;
		
		try
		{
			ConnectionPoolDataSource source = (ConnectionPoolDataSource)new InitialContext().lookup("jdbc/DSTest");
    			con = source.getPooledConnection().getConnection();  
    			stmt = con.createStatement();
    			rs = stmt.executeQuery("select * from test");
    			while(rs.next())
    			{
    				out.println("Title:"+rs.getString(1)+"<br/>");
    			}
		} catch(Exception e){
    			e.printStackTrace();
		} finally {
    			if(con != null)
    			{
        			try {
       	 				con.close();
        			}catch(SQLException e)
        			{
        				e.printStackTrace();
        			}

    			}
		}		
	}	
}

修改「web.xml」。

<servlet>
	<servlet-name>PostgresDBTest</servlet-name>
	<servlet-class>PostgresDBTest</servlet-class>
</servlet>
<servlet-mapping>
	<servlet-name>PostgresDBTest</servlet-name>
	<url-pattern>/PostgresDBTest.do</url-pattern>
</servlet-mapping>

最後開啟「http://localhost:8080/webapp/PostgresDBTest.do」即可。

Apache Commons DBCP - PostgreSQL

下載下述這三個Library,並複製到「Jetty_Home/lib」底下。

commons-dbcp.jar

commons-pool.jar

commons-collections.jar

請修改「/etc/jetty.xml」。

<New id="pgsqldbcp" class="org.mortbay.jetty.plus.naming.Resource">
	<Arg>jdbc/Blog</Arg>
	<Arg>
	<New class="org.apache.commons.dbcp.BasicDataSource">
	<Set name="driverClassName">org.postgresql.Driver</Set>
	<Set name="url">jdbc:postgresql://localhost/Blog</Set>
	<Set name="username">postgres</Set>
	<Set name="password">1234</Set>
	<Set name="maxActive">10</Set>
	</New>
	</Arg>
</New>

修改「web.xml」。

<resource-ref>
	<description>My DataSource Reference</description>
	<res-ref-name>jdbc/DSTest</res-ref-name>
	<res-type>javax.sql.DataSource</res-type>
	<res-auth>Container</res-auth>
</resource-ref>

測試程式如下:

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

public class PostgresDBTest extends HttpServlet
{
	public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
	{
		res.setContentType("text/html");
		PrintWriter out = res.getWriter();
		
		Connection con = null;
		Statement stmt = null;
		ResultSet rs = null;
		
		try
		{
			InitialContext ic = new InitialContext();
			DataSource source = (DataSource)ic.lookup("jdbc/Blog");
			con = source.getConnection();  
			stmt = con.createStatement();
			rs = stmt.executeQuery("select * from test");
			while(rs.next())
			{
    				out.println("Title:"+rs.getString(1)+"<br/>");
			}
		} catch(Exception e){
			e.printStackTrace();
		} finally {
			if(con != null)
			{
				try {
					con.close();
				}catch(SQLException e)
				{
					e.printStackTrace();
				}
			}
		}
	}		
}

2008-12-07 21:36:29 | Comments (5)

Flash Webcam 線上拍照存檔!~

.2008/12/10 新增範例下載

今天試著用Flash CS3寫一個Flash Webcam 線上拍照存檔的範例~

大致上分成兩部份來處理~一部份為Flash的前端,用來截取Webcam的畫面並將它存進BitmapData中,以供透過URLRequest來上傳處理~

而這部份比較關鍵的是,我們利用「as3corelib」所提供的「JPGEncoder」來進行壓縮,以增進傳送速度~

想當然而,後端就是直接將它讀出並存進一個影像檔即可。

程式碼如下所示:

ActionScript 3

import com.adobe.images.JPGEncoder;

var camera:Camera = Camera.getCamera("0");
camera.setMode(320,240,30);
var video = new Video(320, 240);
video.attachCamera(camera);
stage.addChild(video);
stage.addEventListener(MouseEvent.MOUSE_DOWN,clickHandler);
function clickHandler(event:MouseEvent)
{
	var bd:BitmapData = new BitmapData(320, 240);
	bd.draw(video);
	var encoder:JPGEncoder = new JPGEncoder(100);
	var bytes:ByteArray = encoder.encode(bd);
	var req:URLRequest = new URLRequest("http://localhost/WebCamHandler.as3");
	req.data = bytes;
	req.method = URLRequestMethod.POST;
	req.contentType = "application/octet-stream";
	var loader:URLLoader = new URLLoader();			
	loader.addEventListener(Event.COMPLETE, completeHandler);
	loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
	loader.load(req);
}
function completeHandler(event:Event):void
{
	trace("上傳成功");
}
function errorHandler(event:IOErrorEvent):void
{
	trace("上傳失敗");
}

Servlet

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class WebCamHandler extends HttpServlet
{
    private String base;
    
    public void init(ServletConfig sc) throws ServletException
    {
        ServletContext sco = sc.getServletContext();
        base = sco.getRealPath("/");
    }
    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
    {   
        int readed;
        try
        {
            String filePath = base+new Date().getTime()+".jpg";
            BufferedInputStream bis = new BufferedInputStream(req.getInputStream());
            FileOutputStream fos = new FileOutputStream(new File(filePath));
            byte[] bytes = new byte[2048];
            while((readed=bis.read(bytes)) != -1)
            {
                fos.write(bytes, 0, readed);
            }
            fos.close();
            bis.close();
            
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

範例下載

WebCamHandler(CS4、Webapp)

2007-08-19 15:19:20 | Comments (17)

檔案上傳-「commons fileUpload」

一般我們常見的HTML輸入型態(例如:text、radio、select…)都是使用「application/x-www-form-urlencoded」的編碼方式,但要傳送檔案至伺服端時,編碼方式則是要仰賴「multipart/form-data」,由於兩者的編碼方式不同,所以這裡提供一個「FileUpload」的小範例~

必要的package如下:

commons fileUpload

commons IO

HTML

<%@page language="java" contentType="text/html;charset=utf-8"%>
<html>
<head>
<title>檔案上傳</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<b>檔案上傳</b></font></p>
<form name="UploadForm" enctype="multipart/form-data" method="post" action="fileupload.dan">
    <input type="file" name="File1" size="20" maxlength="20"> <br>
    <input type="text" name="File2" size="20" maxlength="20"> <br>
    <input type="submit"value="上傳">
</form>
</body>
</html>

Servlet

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUpload extends HttpServlet
{
    private String base;
    
    public void init(ServletConfig sc) throws ServletException
    {
        ServletContext sco = sc.getServletContext();
        base = sco.getRealPath("/");
    }
    
    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
    {   
        boolean isMultipart = ServletFileUpload.isMultipartContent(req);
        try
        {
            if(isMultipart)
            {
                DiskFileItemFactory factory = new DiskFileItemFactory();
                factory.setSizeThreshold(4096);
                factory.setRepository(new File(base+"temp"));
                ServletFileUpload upload = new ServletFileUpload(factory);
                upload.setSizeMax(10000000);
                List items = upload.parseRequest(req);
                Iterator iter = items.iterator();
                while(iter.hasNext())
                {
                    FileItem item = (FileItem) iter.next();
                    if (item.isFormField())
                    {
                        String name = item.getFieldName();
                        String value = item.getString();
                        System.out.println("name:"+name+" value:"+value);
                    } else {
                        String fieldName = item.getFieldName();
                        String fileName = item.getName();
                        String contentType = item.getContentType();
                        boolean isInMemory = item.isInMemory();
                        long sizeInBytes = item.getSize();
                        System.out.println("fieldName:"+fieldName+" fileName:"+fileName);
                        File to = new File(base+"upload",fileName);
                        item.write(to);
                    }
                }
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

2007-08-10 14:52:00 | Comments (2)

Copyright (C) Ching-Shen Chen. All rights reserved.

::: 搜尋 :::

::: 分類 :::

::: Ads :::

::: 最新文章 :::

::: 最新回應 :::

::: 訂閱 :::

Atom feed
Atom Comment

::: 人氣指數 :::

今日人氣:134

累積人氣:2979374


::: 線上人數 :::

counter