ajax這是一個最近炒的挺熱的話題
目前是對這個工具還沒完全了解
以下做個簡單的紀錄
1st step:
雖然在寫網頁時是用不到 JSP的語法(至少我在第一個example裡沒用到)
首先是要先下載dwr.jar 這個核心 下載
將下載的dwr.jar放到 WebApp/WEB-INF/lib下
2rd step:
撰寫我們的網頁UI
<p>Messages:</p>
<div id="chatlog"></div>
<p>
Your Message:
<input id="text"/>
<input type="button" value="Send"
onclick="sendMessage()"/>
</p>
以及java code
Message.java
package testdwr.bean;
public class Message
{
public Message(String newtext)
{
text = newtext;
if (text.length() > 256)
{
text = text.substring(0, 256);
}
text = text.replace('<', '['); text = text.replace('&', '_'); } public long getId() { return id; } public String getText() { return text; } long id = System.currentTimeMillis(); String text; }
Chat.java
package testdwr.bean;
import java.util.List;
import java.util.LinkedList;
public class Chat
{
public List addMessage(String text)
{
if (text != null &&
text.trim().length() > 0)
{
messages.addFirst(new Message(text));
while (messages.size() > 10)
{
messages.removeLast();
}
}
return messages;
}
public List getMessages()
{
return messages;
}
static LinkedList messages =new LinkedList();
}
將這二個class加到WEB-INF下
3nd step:
在web.xml加上這段宣告
WebApp/WEB-INF 增加一個dwr.xml
<servlet>
<servlet-name>dwr-invoker</servlet-name>
<display-name>DWR Servlet</display-name>
<servlet-class>uk.ltd.getahead.dwr.DWRServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dwr-invoker</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
接著再<?xml version="1.0" encoding="UTF-8"?>
testdwr.bean
<!DOCTYPE dwr PUBLIC
"-//GetAhead Limited//DTD Direct Web Remoting 1.0//EN"
"http://www.getahead.ltd.uk/dwr/dwr10.dtd">
<dwr>
<allow>
<create creator="new" javascript="Chat">
<param name="class" value=".Chat"/>
testdwr.bean
</create>
<convert converter="bean" match=".Message"/>
</allow>
</dwr>
4th step:
在browser 輸入 http://localhost:8080/WebApp/dwr
會出現剛定義的 Chat的hyperlink
點選進入後
把<
script type='text/javascript' src='/JSFExample/dwr
/interface/Chat.js'>
</
script>
<
script type='text/javascript' src='/JSFExample/dwr
/engine.js'>
</
script>
<
script type='text/javascript' src='/JSFExample/dwr
/util.js'>
</
script>
<script type="text/javascript">
function sendMessage(){
var text = DWRUtil.getValue("text");
DWRUtil.setValue("text", "");
Chat.addMessage(text);
DWRUtil.setValue("chatlog", text);
}
</script>WebApp
把這以上java script放到UI上
最後在輸 http://localhost:8080/
即可測試
沒有留言:
張貼留言