2011年3月18日
摘要: JSF学习笔记 JSF事件驱动型的MVC框架,与流行的struts比较学习,易于理解。jsf component event事件是指从浏览器由用户操作触发的事件,Struts application event 是用Action来接受浏览器表单提交的事件,一个表单只能对应一个事件,application event和component event相比是一种粗粒度的事件。优点:事件...
阅读全文
posted @
2011-05-30 21:48 junly 阅读(1253) |
评论 (2) |
编辑 收藏
Struts2 的UITag原理:
Struts2 UITag分三部份组成,一部份用于定义Tag的内容与逻辑的UIBean,一部份用于定义JSP Tag,也就是平时我们定义的那种,最后就是Template,它存放在你的theme目录之下,是一个FreeMarker模板文件。
我现在辑写一份MMTag,它主要是用于输出带链接的文字,比如像这样:
<cur:mm message="'I am a boy.'" />
就会输出:
<a href="http://www.blogjava.net/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会自动在后面加入.ftl扩展名以找到特定的模板文件。
* setXXX,设置UIBean的属性,一般Tag中有几个这样的属性,这里就有几个。@StrutsTagAttribute(description="set message", type="String") 注解,说明该属性是字符串(也可以是其它),这一步很重要。
* 覆写evaluateExtraParams() 方法,在UIBean初始化后会调用这个方法来初始化设定参数,如addParameter方法,会在freemarker里的parameters里加 入一个key value。这里要注意findString,还有相关的findxxxx方法,它们是已经封装好了的解释ognl语法的工具,具体是怎么样的,大家可以 查看一下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()初始化参数,一般用来初始化UIBean(Component)。
* setXXXX设置属性,和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目录(这个目录名和你的theme有关),然后在里面建一个 mm.ftl文件:
<a href="http://www.yinsha.com">${parameters.message?html}</a>
建一个action测试一下,视图文件:
<%@ 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: 写得有些粗鄙,所以,如有问题的,可以留言。
http://devilkirin.javaeye.com/blog/427395
http://xiaojianhx.javaeye.com/blog/482888
posted @
2011-05-30 21:43 junly 阅读(1112) |
评论 (1) |
编辑 收藏
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
posted @
2011-05-30 21:38 junly 阅读(768) |
评论 (0) |
编辑 收藏
Java 7已经完成的7大新功能:
1 对集合类的语言支持;
2 自动资源管理;
3 改进的通用实例创建类型推断;
4 数字字面量下划线支持;
5 switch中使用string;
6 二进制字面量;
7 简化可变参数方法调用。
下面我们来仔细看一下这7大新功能:
1 对集合类的语言支持
Java将包含对创建集合类的第一类语言支持。这意味着集合类的创建可以像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");
现在你可以这样:
List<String> list = ["item"];
String item = list[0];
Set<String> set = {"item"};
Map<String, Integer> map = {"key" : 1};
int value = map["key"];
这些集合是不可变的。
2 自动资源管理
Java中某些资源是需要手动关闭的,如InputStream,Writes,Sockets,Sql classes等。这个新的语言特性允许try语句本身申请更多的资源,
这些资源作用于try代码块,并自动关闭。
这个:
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
br.close();
}
变成了这个:
try (BufferedReader br = new BufferedReader(new FileReader(path)) {
return br.readLine();
}
你可以定义关闭多个资源:
try (
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest))
{
// code
}
为了支持这个行为,所有可关闭的类将被修改为可以实现一个Closable(可关闭的)接口。
3 增强的对通用实例创建(diamond)的类型推断
类型推断是一个特殊的烦恼,下面的代码:
Map<String, List<String>> anagrams = new HashMap<String, List<String>>();
通过类型推断后变成:
Map<String, List<String>> anagrams = new HashMap<>();
这个<>被叫做diamond(钻石)运算符,这个运算符从引用的声明中推断类型。
4 数字字面量下划线支持
很长的数字可读性不好,在Java 7中可以使用下划线分隔长int以及long了,如:
int one_million = 1_000_000;
运算时先去除下划线,如:1_1 * 10 = 110,120 – 1_0 = 110
5 switch中使用string
以前你在switch中只能使用number或enum。现在你可以使用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 二进制字面量
由于继承C语言,Java代码在传统上迫使程序员只能使用十进制,八进制或十六进制来表示数(numbers)。
由于很少的域是以bit导向的,这种限制可能导致错误。你现在可以使用0b前缀创建二进制字面量:
int binary = 0b1001_1001;
现在,你可以使用二进制字面量这种表示方式,并且使用非常简短的代码,可将二进制字符转换为数据类型,如在byte或short。
byte aByte = (byte)0b001;
short aShort = (short)0b010;
7 简化的可变参数调用
当程序员试图使用一个不可具体化的可变参数并调用一个*varargs* (可变)方法时,编辑器会生成一个“非安全操作”的警告。
JDK 7将警告从call转移到了方法声明(methord declaration)的过程中。这样API设计者就可以使用vararg,因为警告的数量大大减少了。
posted @
2011-03-18 15:21 junly 阅读(16833) |
评论 (9) |
编辑 收藏