
2011年3月18日
摘要: JSF學(xué)習(xí)筆記 JSF事件驅(qū)動(dòng)型的MVC框架,與流行的struts比較學(xué)習(xí),易于理解。jsf component event事件是指從瀏覽器由用戶操作觸發(fā)的事件,Struts application event 是用Action來(lái)接受瀏覽器表單提交的事件,一個(gè)表單只能對(duì)應(yīng)一個(gè)事件,application event和component event相比是一種粗粒度的事件。優(yōu)點(diǎn):事件...
閱讀全文
Struts2 的UITag原理:
Struts2 UITag分三部份組成,一部份用于定義Tag的內(nèi)容與邏輯的UIBean,一部份用于定義JSP Tag,也就是平時(shí)我們定義的那種,最后就是Template,它存放在你的theme目錄之下,是一個(gè)FreeMarker模板文件。
我現(xiàn)在輯寫一份MMTag,它主要是用于輸出帶鏈接的文字,比如像這樣:
<cur:mm message="'I am a boy.'" />
就會(huì)輸出:
<a href="http://m.tkk7.com/natlive">I am boy.</a>
我們先寫UIBean部份:我們把它定義為MM,它繼承于 org.apache.struts2.components.UIBean:
package limitstudy.corestruts2.tag;
import org.apache.struts2.components.UIBean;
import org.apache.struts2.views.annotations.StrutsTag;
import org.apache.struts2.views.annotations.StrutsTagAttribute;
import com.opensymphony.xwork2.util.ValueStack;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@StrutsTag(name="mm", tldTagClass="limitstudy.corestruts2.tag.MMTag", description="MM")
public class MM extends UIBean {
private String message;
public MM(ValueStack stack, HttpServletRequest request, HttpServletResponse response) {
super(stack, request, response);
}
@Override
protected String getDefaultTemplate() {
return "mm";
}
@StrutsTagAttribute(description="set message", type="String")
public void setMessage(String message) {
this.message = message;
}
@Override
protected void evaluateExtraParams() {
super.evaluateExtraParams();
if (null != message) {
addParameter("message", findString(message));
}
}
}
* strutsTag注解指明了該UIBean的名字 和Tag類的類名。
* getDefaultTemplate()方法用于返回模板的名 字,Struts2會(huì)自動(dòng)在后面加入.ftl擴(kuò)展名以找到特定的模板文件。
* setXXX,設(shè)置UIBean的屬性,一般Tag中有幾個(gè)這樣的屬性,這里就有幾個(gè)。@StrutsTagAttribute(description="set message", type="String") 注解,說(shuō)明該屬性是字符串(也可以是其它),這一步很重要。
* 覆寫evaluateExtraParams() 方法,在UIBean初始化后會(huì)調(diào)用這個(gè)方法來(lái)初始化設(shè)定參數(shù),如addParameter方法,會(huì)在freemarker里的parameters里加 入一個(gè)key value。這里要注意findString,還有相關(guān)的findxxxx方法,它們是已經(jīng)封裝好了的解釋ognl語(yǔ)法的工具,具體是怎么樣的,大家可以 查看一下UIBean的api doc。
然后是Tag部份:
package limitstudy.corestruts2.tag;
import org.apache.struts2.views.jsp.ui.AbstractUITag;
import org.apache.struts2.components.Component;
import com.opensymphony.xwork2.util.ValueStack;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MMTag extends AbstractUITag {
private String message;
@Override
public Component getBean(ValueStack stack, HttpServletRequest request, HttpServletResponse response) {
return new MM(stack, request, response);
}
@Override
protected void populateParams() {
super.populateParams();
MM mm = (MM)component;
mm.setMessage(message);
}
public void setMessage(String message) {
this.message = message;
}
}
* getBean()返回該Tag中的UIBean。
* populateParams()初始化參數(shù),一般用來(lái)初始化UIBean(Component)。
* setXXXX設(shè)置屬性,和jsp tag是一樣的。
在/WEB-INF/tlds/下建立current.tld文件(文名隨你喜歡):
<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd">
<description>test</description>
<tlib-version>2.0</tlib-version>
<short-name>cur</short-name>
<uri>/cur</uri>
<tag>
<name>mm</name>
<tag-class>limitstudy.corestruts2.tag.MMTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<name>message</name>
<required>true</required>
</attribute>
</tag>
</taglib>
在源代碼目錄中建立template/simple目錄(這個(gè)目錄名和你的theme有關(guān)),然后在里面建一個(gè) mm.ftl文件:
<a href="http://www.yinsha.com">${parameters.message?html}</a>
建一個(gè)action測(cè)試一下,視圖文件:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ taglib prefix="cur" uri="/cur" %>
<html>
<head>
<title><s:property value="message" /></title>
</head>
<body>
<cur:mm message="haoahahhahaha" />
</body>
</html>
完。
PS: 寫得有些粗鄙,所以,如有問(wèn)題的,可以留言。
http://devilkirin.javaeye.com/blog/427395
http://xiaojianhx.javaeye.com/blog/482888
Page
The following is register.jsp, which takes required information from user regarding registration. For this example, we focus only on validation of username and not the actual registration process.
The most important thing is to know how to access JSF component from JQuery. The id given to inputText is consisting of formid:componentid. So in this example the id given to textbox is registerform:username. But the presence of : (colon) causes problem to JQuery. So, we need to escape : (colon) using two \\ characters before colon - registerform\\:username.
//register.jsp
<%@page contentType="text/html" %>de">
<%@page contentType="text/html" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script language="javascript" src="jquery-1.4.2.js"></script>
<script language="javascript">
function checkUsername(){
$.get( "checkusername.jsp",{username : $("#registerform\\:username").val()},updateUsername);
}
function updateUsername(response)
{
if (response) {
$("#usernameresult").text(response); // update SPAN item with result
}
</script>
<title>Registration</title>
</head>
<body>
<%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<f:view>
<h2>Registration </h2>
<h:form id="registerform">
<table>
<tr>
<td>Username : </td>
<td><h:inputText id="username" value="#{userBean.username}" required="true" onblur="checkUsername()" />
<h:message for="username" />
<span id="usernameresult" />
</tr>
<tr>
<td>Password : </td>
<td><h:inputSecret id="password" value="#{userBean.password}" required="true" /> <h:message for="password" /> </td>
</tr>
<tr>
<td>Re-enter Password : </td>
<td><h:inputSecret id="confirmPwd" value="#{userBean.confirmPwd}" required="true" /> <h:message for="confirmPwd" /> </td>
</tr>
<tr>
<td>Email Address : </td>
<td><h:inputText id="email" value="#{userBean.email}" required="true" onblur="checkEmail()" /> <h:message for="email" /> </td>
<span id="emailresult" />
</tr>
</table>
<p/>
<h:commandButton actionListener="#{userBean.register}" value="Register" />
<p/>
<h3><h:outputText value="#{userBean.message}" escape="false" /> </h3>
<p/>
</h:form>
</f:view>
</body>
</html>lt;/f:view>
</body>
</html>
Bean
The above JSF Form uses
userBean, which is the name given to
beans.UserBean class. The class and its entries in
faces-config.xml file are given below.
UserBean is the managed bean that stores data coming from JSF form. It contains an action listener - register(), which is supposed to process the data to complete registration process. We don't deal with it as our focus is only on validating username.
//UserBean.java
package beans;
public class UserBean {
private String username, password, email,confirmPwd, message;
public UserBean() {
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getConfirmPwd() {
return confirmPwd;
}
public void setConfirmPwd(String confirmPwd) {
this.confirmPwd = confirmPwd;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public void register(ActionEvent evt) {
if (! password.equals(confirmPwd))
{
message = "Password do not match!";
return;
}
// do registration
} // register
}
xml
The following entry is required in faces-config.xml for UserBean managed bean.
<!-- faces-config.xml -->
<managed-bean>
<managed-bean-name>userBean</managed-bean-name>
<managed-bean-class>beans.UserBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
Check
Now create a checkusername.jsp to check whether given username is valid. It sends a message if username is already exists otherwise it sends empty string (nothing).
<%@ page import="java.sql.*" contentType="text/plain"%>
<%
String username = request.getParameter("username"); // sent from client
// connect to oracle using thin driver
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","youruser","yourpassword");
PreparedStatement ps = con.prepareStatement("select username from users where username = ?");
ps.setString(1,username);
ResultSet rs = ps.executeQuery();
if ( rs.next()) { // found username
out.println("Username is already present!"); // send this to client
}
rs.close();
ps.close();
con.close();
%>
Deploy and Test
Now deploy the web application and run register.jsp. If you enter a username that is already present in USERS table then we get message - Username is already present - in SPAN item on the right of username field. If username is unique then SPAN item is set to empty string ( as JSP returns nothing). from:http://www.srikanthtechnologies.com/blog/java/jquerywithjsf.aspx
Java 7已經(jīng)完成的7大新功能:
1 對(duì)集合類的語(yǔ)言支持;
2 自動(dòng)資源管理;
3 改進(jìn)的通用實(shí)例創(chuàng)建類型推斷;
4 數(shù)字字面量下劃線支持;
5 switch中使用string;
6 二進(jìn)制字面量;
7 簡(jiǎn)化可變參數(shù)方法調(diào)用。
下面我們來(lái)仔細(xì)看一下這7大新功能:
1 對(duì)集合類的語(yǔ)言支持
Java將包含對(duì)創(chuàng)建集合類的第一類語(yǔ)言支持。這意味著集合類的創(chuàng)建可以像Ruby和Perl那樣了。
原本需要這樣:
List<String> list = new ArrayList<String>();
list.add("item");
String item = list.get(0);
Set<String> set = new HashSet<String>();
set.add("item");
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("key", 1);
int value = map.get("key");
現(xiàn)在你可以這樣:
List<String> list = ["item"];
String item = list[0];
Set<String> set = {"item"};
Map<String, Integer> map = {"key" : 1};
int value = map["key"];
這些集合是不可變的。
2 自動(dòng)資源管理
Java中某些資源是需要手動(dòng)關(guān)閉的,如InputStream,Writes,Sockets,Sql classes等。這個(gè)新的語(yǔ)言特性允許try語(yǔ)句本身申請(qǐng)更多的資源,
這些資源作用于try代碼塊,并自動(dòng)關(guān)閉。
這個(gè):
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
br.close();
}
變成了這個(gè):
try (BufferedReader br = new BufferedReader(new FileReader(path)) {
return br.readLine();
}
你可以定義關(guān)閉多個(gè)資源:
try (
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest))
{
// code
}
為了支持這個(gè)行為,所有可關(guān)閉的類將被修改為可以實(shí)現(xiàn)一個(gè)Closable(可關(guān)閉的)接口。
3 增強(qiáng)的對(duì)通用實(shí)例創(chuàng)建(diamond)的類型推斷
類型推斷是一個(gè)特殊的煩惱,下面的代碼:
Map<String, List<String>> anagrams = new HashMap<String, List<String>>();
通過(guò)類型推斷后變成:
Map<String, List<String>> anagrams = new HashMap<>();
這個(gè)<>被叫做diamond(鉆石)運(yùn)算符,這個(gè)運(yùn)算符從引用的聲明中推斷類型。
4 數(shù)字字面量下劃線支持
很長(zhǎng)的數(shù)字可讀性不好,在Java 7中可以使用下劃線分隔長(zhǎng)int以及l(fā)ong了,如:
int one_million = 1_000_000;
運(yùn)算時(shí)先去除下劃線,如:1_1 * 10 = 110,120 – 1_0 = 110
5 switch中使用string
以前你在switch中只能使用number或enum。現(xiàn)在你可以使用string了:
String s = ...
switch(s) {
case "quux":
processQuux(s);
// fall-through
case "foo":
case "bar":
processFooOrBar(s);
break;
case "baz":
processBaz(s);
// fall-through
default:
processDefault(s);
break;
}
6 二進(jìn)制字面量
由于繼承C語(yǔ)言,Java代碼在傳統(tǒng)上迫使程序員只能使用十進(jìn)制,八進(jìn)制或十六進(jìn)制來(lái)表示數(shù)(numbers)。
由于很少的域是以bit導(dǎo)向的,這種限制可能導(dǎo)致錯(cuò)誤。你現(xiàn)在可以使用0b前綴創(chuàng)建二進(jìn)制字面量:
int binary = 0b1001_1001;
現(xiàn)在,你可以使用二進(jìn)制字面量這種表示方式,并且使用非常簡(jiǎn)短的代碼,可將二進(jìn)制字符轉(zhuǎn)換為數(shù)據(jù)類型,如在byte或short。
byte aByte = (byte)0b001;
short aShort = (short)0b010;
7 簡(jiǎn)化的可變參數(shù)調(diào)用
當(dāng)程序員試圖使用一個(gè)不可具體化的可變參數(shù)并調(diào)用一個(gè)*varargs* (可變)方法時(shí),編輯器會(huì)生成一個(gè)“非安全操作”的警告。
JDK 7將警告從call轉(zhuǎn)移到了方法聲明(methord declaration)的過(guò)程中。這樣API設(shè)計(jì)者就可以使用vararg,因?yàn)榫娴臄?shù)量大大減少了。
posted @
2011-03-18 15:21 junly 閱讀(16865) |
評(píng)論 (9) |
編輯 收藏