在修改好相應的文字與圖象之后,我們就將PSD文件輸出(X)HTML文件。
首先得先對PSD文件做切片,有兩種方法:
①使用工具欄上的“切片工具”,
然后在圖象上劃出一塊一塊的區域。
②使用基于參考線的切片,按ctrl+R調出標尺欄,
把鼠標移動到標尺上,按住鼠標左鍵,移動到圖象上,將會看到一條綠色的參考線,如圖
將參考線;排好,然后點一下工具欄上的切片工具圖表,然后點上面
選項欄里的“基于參考線的切片”。于是在原來的參考線上就變成了一塊一塊的切片了。
********************************************************************************
接下來就可以輸出了:
①依次選擇菜單欄上的“文件”→“存儲為Web所用格式”→“存儲”。
②接下來就會彈出一個“將優化結果存儲為”的窗口。
在“保存類型”處有個下拉列框可以選擇,因為我們要存儲為網頁的格式,所以選擇“HTML和圖象(* html)”,再選擇“保存”就可以輸出一個網頁格式的HTML文件與一個包含圖象的名為“images”的文件夾。
③如果我們需要輸出“div+css的網頁”我們還可以這么做:
在“設置”處的下拉列框,選擇“其他”
就會彈出一個“輸出設置”的窗口
在第2個下拉列框處選擇“切片”,選擇“生成CSS”,單擊“好”→“保存”,就可以輸出一個目前流行的“div+css”的HTML網頁。
文檔流中其它元素的布局就像絕對定位的元素不存在一樣:
var store = new Ext.data.JsonStore({
url: 'get-images.php',
root: 'images',
fields: [
'name', 'url',
{name:'size', type: 'float'},
{name:'lastmod', type:'date', dateFormat:'timestamp'}
]
});
store.load();
var tpl = new Ext.XTemplate(
'<tpl for=".">',
'<div class="thumb-wrap" id="{name}">',
'<div class="thumb"><img src="{url}" title="{name}"></div>',
'<span class="x-editable">{shortName}</span></div>',
'</tpl>',
'<div class="x-clear"></div>'
);
var panel = new Ext.Panel({
id:'images-view',
frame:true,
width:535,
autoHeight:true,
collapsible:true,
layout:'fit',
title:'Simple DataView',
items: new Ext.DataView({
store: store,
tpl: tpl,
autoHeight:true,
multiSelect: true,
overClass:'x-view-over', //鼠標懸停item時的類樣式,defaults to undefined
itemSelector:'div.thumb-wrap', //必須項,值為item選擇器,此值也可為.thumb-wrap e.g. div.some-class
// //(默認名)defaults to 'x-view-selected',但仍必須寫此類的CSS內容
emptyText: 'No images to display'
/*
plugins: [
new Ext.DataView.DragSelector(),
new Ext.DataView.LabelEditor({dataIndex: 'name'})
],*/
prepareData: function(data){ //數據預處理,即數據處理前.data為原始數據,類型為對象.
data.shortName = Ext.util.Format.ellipsis(data.name, 15); //指定字符串為15個字符,超出部分用三個圓點代替.
// data.sizeString = Ext.util.Format.fileSize(data.size);
// data.dateString = data.lastmod.format("m/d/Y g:i a");
return data;
},
listeners: {
selectionchange: { //結點的選擇發生改變時,即重新選擇結點時,可以更改為selectionchange:function(dv,nodes)...
fn: function(dv,nodes){
var l = nodes.length;
var s = l != 1 ? 's' : '';
panel.setTitle('Simple DataView ('+l+' item'+s+' selected)');
}
}
})
});
panel.render(document.body);
DataView 用store提供的數據流,采用tpl的格式顯示,itemSelector的值為數據流中塊的CSS類選擇器,對塊操作時更換其CSS類樣式,如鼠標懸停在塊上和塊被選定時的CSS類樣式;簡單點說,就是有利于對數據流中的塊好控制操作.
tpl定義的塊:<div id="zack_hat.jpg" class="thumb-wrap">
鼠標懸停時的塊(overClass):<div id="zack_hat.jpg" class="thumb-wrap x-view-over">
點擊被選中的塊(selectedClass):<div id="kids_hug2.jpg" class="thumb-wrap x-view-selected">
1.當鼠標點擊數據流中某一塊時,塊增加selectedClass定義的類樣式,如沒定義類名,即采用默認的類名'x-view-selected'(CSS內容依然為空,仍需手寫,只是類名必須為此);
2.用overClass定義的CSS類樣式,鼠標懸停在塊(div)上,更換其CSS類樣式.
3.dataView.store.filter(f1,f2):從store中查找f1字段,與f2匹配(不完全匹配相同)過濾,重新本地加載數據.
4.dataView.store.store(f1,'asc'/'desc'):store的內容按f1的值排序.
5.dataView.store.clearFilter():清除過濾狀態.還原初始.
6.dataView.select(n):更換第n個塊的CSS類樣式.
(二)html:
<html>
<head>
</head>
<body id="ext-gen6" class=" ext-gecko ext-gecko3">
-->
<h1>DataView Example</h1>
<p>
</p>
<div id="images-view" class="x-panel" style="width: 535px;">
<div class="x-panel-tl">
</div>
<div id="ext-gen8" class="x-panel-bwrap">
<div class="x-panel-ml">
<div class="x-panel-mr">
<div class="x-panel-mc">
<div id="ext-gen9" class="x-panel-body" style="width: 523px; height: auto;">
<div id="ext-comp-1001" style="height: auto;">
<div id="kids_hug2.jpg" class="thumb-wrap x-view-selected ">
<div class="thumb">
<img title="kids_hug2.jpg" src="images/thumbs/kids_hug2.jpg"/>
</div>
<span class="x-editable"/>
</div>
<div id="zack_hat.jpg" class="thumb-wrap ">
</div>
<div id="zack.jpg" class="thumb-wrap ">
</div>
<div id="zack_sink.jpg" class="thumb-wrap ">
</div>
<div id="sara_pink.jpg" class="thumb-wrap">
</div>
<div id="dance_fever.jpg" class="thumb-wrap ">
<div class="thumb">
<img title="dance_fever.jpg" src="images/thumbs/dance_fever.jpg"/>
</div>
<span class="x-editable"/>
</div>
<div id="gangster_zack.jpg" class="thumb-wrap ">
</div>
<div id="zacks_grill.jpg" class="thumb-wrap">
</div>
<div id="kids_hug.jpg" class="thumb-wrap ">
</div>
<div id="zack_dress.jpg" class="thumb-wrap ">
</div>
<div id="sara_pumpkin.jpg" class="thumb-wrap">
</div>
<div id="sara_smile.jpg" class="thumb-wrap ">
</div>
<div id="up_to_something.jpg" class="thumb-wrap ">
</div>
<div class="x-clear"/>
</div>
</div>
</div>
</div>
</div>
<div class="x-panel-bl x-panel-nofooter">
</div>
</div>
</div>
</body>
<div id="_firebugConsole" style="display: none;" FirebugVersion="1.4.2"/>
</html>
(三)css
#images-view .x-panel-body {
-moz-background-clip:border;
-moz-background-inline-policy:continuous;
-moz-background-origin:padding;
-x-system-font:none;
background:white none repeat scroll 0 0;
font-family:Arial,Helvetica,sans-serif;
font-size:11px;
font-size-adjust:none;
font-stretch:normal;
font-style:normal;
font-variant:normal;
font-weight:normal;
line-height:normal;
}
#images-view .thumb {
-moz-background-clip:border;
-moz-background-inline-policy:continuous;
-moz-background-origin:padding;
background:#DDDDDD none repeat scroll 0 0;
padding:3px;
}
#images-view .thumb img {
height:60px;
width:80px;
}
#images-view .thumb-wrap {
float:left;
margin:4px 0 4px 4px;
padding:5px;
}
#images-view .thumb-wrap span {
display:block;
overflow:hidden;
text-align:center;
}
#images-view .x-view-over {
-moz-background-clip:border;
-moz-background-inline-policy:continuous;
-moz-background-origin:padding;
background:#EFEFEF url(../../resources/images/default/grid/row-over.gif) repeat-x scroll left top;
border:1px solid #DDDDDD;
padding:4px;
}
#images-view .x-view-selected {
-moz-background-clip:border;
-moz-background-inline-policy:continuous;
-moz-background-origin:padding;
background:#EFF5FB url(images/selected.gif) no-repeat scroll right bottom;
border:1px solid #99BBE8;
padding:4px;
}
#images-view .x-view-selected .thumb {
-moz-background-clip:border;
-moz-background-inline-policy:continuous;
-moz-background-origin:padding;
background:transparent none repeat scroll 0 0;
}
#images-view .loading-indicator {
background-image:url(../../resources/images/default/grid/loading.gif);
background-position:left center;
background-repeat:no-repeat;
font-size:11px;
margin:10px;
padding-left:20px;
}
三個必須項: title,root ,loader
new Ext.tree.TreePanel({
rootVisible : false,
useArrows : true,// 是否使用箭頭樣式
loader : new Ext.tree.TreeLoader({
url : "tree-data.json"
}),
title : "tool1",
root : new Ext.tree.AsyncTreeNode()
}), {
title : "tool2"
ERROR [main] (CGLIBLazyInitializer.java:130) - CGLIB Enhancement failed: item.common.hibernate.query.partsum.Partsum
java.lang.NoSuchMethodError: org.objectweb.asm.ClassVisitor.visit(IILjava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)V
WARN [main] (PojoEntityTuplizer.java:173) - could not create proxy factory for: item.common.hibernate.query.partsum.Partsum
org.hibernate.HibernateException: CGLIB Enhancement failed: item.common.hibernate.query.partsum.Partsum
Caused by: java.lang.NoSuchMethodError: org.objectweb.asm.ClassVisitor.visit(IILjava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)V
///////////////////////////////////////////////////////////////////////////////////////////
ERROR [main] (CGLIBLazyInitializer.java:130) - CGLIB Enhancement failed: item.common.hibernate.fourm.Fourm
java.lang.NoClassDefFoundError
WARN [main] (PojoEntityTuplizer.java:173) - could not create proxy factory for:item.common.hibernate.fourm.Fourm
org.hibernate.HibernateException: CGLIB Enhancement failed: item.common.hibernate.fourm.Fourm
Caused by: java.lang.NoClassDefFoundError
at org.hibernate.proxy.CGLIBLazyInitializer.getProxyFactory(CGLIBLazyInitializer.java:116)
////////////////////////////////////////////////////////////////////////////////////////////
ERROR [main] (CGLIBLazyInitializer.java:130) - CGLIB Enhancement failed: item.common.hibernate.picture
java.lang.NoClassDefFoundError
WARN [main] (PojoEntityTuplizer.java:173) - could not create proxy factory for:item.common.hibernate.picture
org.hibernate.HibernateException: CGLIB Enhancement failed: item.common.hibernate.picture
Caused by: java.lang.NoClassDefFoundError
at org.hibernate.proxy.CGLIBLazyInitializer.getProxyFactory(CGLIBLazyInitializer.java:116)
解決方案:
Spring 和 Hibernate 共用的一些 jar 文件發生了版本沖突, 刪除 WEB-INF/lib/asm-2.2.3.jar 然后重啟 Tomcat.
四.錯誤提示:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'SessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.objectweb.asm.ClassVisitor.visit(IILjava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)V
...
Caused by: java.lang.NoSuchMethodError: org.objectweb.asm.ClassVisitor.visit(IILjava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)V
解決方法:
并不是真正的bean name錯了,也不是找不到他的方法.是asm-2.2.3.jar與asm.jar沖突.
正確的刪除asm-2.2.3.jar方法是到項目的發布文件夾\WEB-INF\lib中刪除,不能用MyEclipse里刪除.因為他在發布時仍沒刪除.
五。
嚴重: Exception sending context initialized event to listener instance of class
org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in
ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is
org.hibernate.DuplicateMappingException: Duplicate class/entity mapping Check
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean
(AbstractAutowireCapableBeanFactory.java:1336)
... 39 more
2009-8-21 11:52:37 org.apache.catalina.core.StandardContext start
<property name="mappingResources">
<list>
<value>com/dao/Check.hbm.xml</value>
<value>./Check.hbm.xml</value></list>
</property>
六。
<class catalog="page" name="com.dao.Check" table="check0908100816">
<id name="checkid" type="java.lang.Integer">
<column name="checkid"/>
<generator class="native"/>
</id>
嚴重: Exception sending context initialized event to listener instance of class
org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in
ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is
org.hibernate.MappingException: entity class not found: Check
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean
... 52 more
2009-8-21 11:56:45 org.apache.catalina.core.StandardContext start
int i=Integer.parseInt(str);
如何將字串 String 轉換成Integer ?
Integer integer=Integer.valueOf(str);
如何將整數 int 轉換成字串 String ?
1.) String s = String.valueOf(i);
2.) String s = Integer.toString(i);
3.) String s = "" + i;
如何將整數 int 轉換成Integer ?
Integer integer=new Integer(i);
如何將Integer 轉換成字串 String ?
Integer integer=String
如何將Integer 轉換成 int ?
int num=Integer.intValue();
如何將String轉換成 BigDecimal ?
BigDecimal d_id = new BigDecimal(str);
如何將 String 轉換成 char ?
char[] ca="123".toCharArray();
如何將char轉換成String?
String s=ca.toString(); //任何類型都可以采用toString()轉換成String類型
//-----------------日期-------------------------
Calendar calendar=Calendar.getInstance();
int year=calendar.get(Calendar.YEAR);
int month=calendar.get(Calendar.MONTH)+1;
int day=calendar.get(Calendar.DATE);
獲取今天的日期字符串
String today=java.text.DateFormat.getDateInstance().format(new java.util.Date());
獲取今天的日期
new java.sql.Date(System.currentTimeMillis())
out.print(fs.showfourm());
} else if (c.equals("isDetail")) { //論壇詳細內容調用
String title = request.getParameter("title");
String identity = request.getParameter("identity");
out.print(fs.showfourm(title, identity));
} else if (c.equals("insert")) {
String[] t = new String[4];
t[0] = "title";//request.getParameter("title");
t[1] = "底盤部門";//request.getParameter("identity");
t[2] = "底盤作者";//request.getParameter("author");
t[3] ="底盤詳細內容"; //request.getParameter("detail");
fs.insertjson(t);
out.print("{success:true,msg:'添加成功!'}"); //必須指定{success:true'},他傳回EXTJS調用成功,否則EXTJS卡住無法執行;如果沒有這行代碼即為報"SYNTAX ERROR:)"錯.他還能傳任意參數如MSG回EXTJS.
}
%>
//獲取ApplicationContext.xml文件中定義的BEAN
PictureService ps=(PictureService)ac.getBean("pictureService");
<!--顯示數據的表格窗口-->
<div id="member_grid"></div>
<input type="button" id="button1" value="update">
......以下總結這段時間以來遇到的中文問題匯集:
注:以下“后臺”字眼,相當于在servlet內,或者某一個類內,或者struts的action內。
1.一字符串在后臺用system.out.println輸出正常,保存在session里到JSP頁面顯示亂碼
最初的亂碼問題.
原因:似乎是默認的JSP頁面采用8859-1編碼,顯示不了中文。
解決:在JSP頁面上方加個<%@ page contentType="text/html;charset=utf-8"%>解決。當然,也可以用charaset="gbk","gb2312"之類的編碼,不過建議還是用utf-8,詳細原因去看看jdon板橋里人的那篇《中文亂碼終極解決方法》。
*****************************************************************************
2.提交表單,在后臺讀取表單內容發現亂碼
原因:request的默認編碼問題,具體不甚清楚,沒看過tomcat源代碼。。。
解決:寫個fileter,具體如下:
package operator;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class SetCharacterEncodingFilter implements Filter {
protected String encoding = null;
protected FilterConfig filterConfig = null;
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
chain.doFilter(request, response);
}
public void destroy() {
this.encoding = null;
this.filterConfig = null;
}
protected String selectEncoding(ServletRequest request) {
return (this.encoding);
}
}
web.xml配置:
在servlet-mapping后加入以下內容:
<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>operator.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
***********************************************************************
3.下載時,“另保存為”默認名字顯示亂碼
原因:不清楚。。。
在tomcat安裝目錄的config/sever.xml內的
<Connector
port="80" maxHttpHeaderSize="8192"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
connectionTimeout="20000" disableUploadTimeout="true" URIEncoding="UTF-8" />
加進最后的“URIEncoding="UTF8"
4.在后臺用system.out.println()輸出正常,保存到mysql數據庫EMS顯示亂碼,讀回數據也是亂碼
原因:mysql默認采用的是latin1編碼;
解決:創建表的時候要修改成utf-8。如果已存在表,用EMS的話,直接修改table-property里面的default charater set就可以了,其他管理工具不知道,沒用過。
5.在后臺用system.out.println()輸出正常,保存到mysql數據庫EMS顯示亂碼,讀回數據時——居然正常了,直接往數據庫里插入正常的中文,讀出——居然亂碼了;
原因:EMS管理工具的默認顯示問題
解決:register數據庫時,client default charater set改utf-8
注:這該死的問題困擾了我好長一段時間,一直以為我程序有問題,檢查了N久,發現居然是工具顯示問題。。
6.COMMON-UPLOAD 上傳中文名文件時,顯示亂碼
原因:common-upload組件默認采用系統的編碼,而頁面傳過來的請求采用UTF-8編碼。
我的系統是簡體中文WINDOWS 2K3,系統編碼是GBK,當頁面請求過來時,UPLOAD就把UTF8編碼的流直接按GBK編碼了。。。如果用new String(oldStr.getBytes("gbk"),"utf8)可以發現,部分中文可以還原回去。
解決:網上的說法五花八門,甚至有歸罪于這是UPLOAD的BUG,其實只要在
DiskFileUpload fu = new DiskFileUpload();
后加一句:
fu.setHeaderEncoding("utf8");
就解決了。。。
看來有時候還是直接讀英文幫助手冊來得正確。。。
public class StringConverter implements Converter {
public Object getAsObject(FacesContext context, UIComponent component,
String newValues) throws ConverterException {
String newstr = "";
if (newValues == null) {
newValues = "";
}
byte[] byte1 = null;
try {
byte1 = newValues.getBytes("ISO-8859-1");
newstr = new String(byte1, "GB2312");
UIInput input=(UIInput)component;//
input.setSubmittedValue(newstr);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return newstr;
}
public String getAsString(FacesContext context, UIComponent component,
Object Values) throws ConverterException {
return (String) Values;
}
}
2、注冊轉換器
faces-config.xml片段
<converter>
<converter-id>stringconverter</converter-id>
<converter-class>util.StringConverter</converter-class>
</converter>
3、在頁面使用轉換器
<h:inputText id="account" value="#{util.account}" required="true" styleClass="input" >
<f:converter converterId="stringconverter"/> <!--注:這里不是EL表達式-->
JSF估計是天生就是這個毛病,凡是有jsf標簽生成的html代碼中有中文的(指從 backbean中提取出來的),在html源代碼中回出現類似:雨滴 這種“漢字內碼”,比如jsf的代碼如下:
<f:view>
<h:outputText value="#{testBean.testValue}"></h:outputText>
<br>
哈哈
</f:view>
<br>呵呵
瀏覽器顯示如下:
雨滴雨滴2
哈哈
呵呵
而查看html源代碼如下:
雨滴雨滴2 <br> 哈哈 <br>呵呵
我們發現用jsf標簽出來的有內碼,而不是jsf標簽的就沒事。(網頁服務器編碼等都是UTF-8統一的)。
那么有什么辦法呢?
第一個方法,寫一個自定義的Converter,在jsf中有這種功能,但是我測試了寫了一個converter,但是效果令我失望,因為我發現jsf的內在邏輯把漢字變成內碼的地方在converter以后,我在converter中添加什么東西,在html源代碼中還是內碼。于是放棄
第二種方法是在寫個Servlet的Filter過濾器,放到web.xml中,但是由于漢字內碼雨需要去掉前后墜,然后把這幾個數字變成char,在變成String。每個字都用這種方法變回來,這樣本身效率回很低,而且一個html文檔中用jsf顯示的內容占有比率有多有少,如果沒有標簽的也是用這個過濾器一個字一個字取解析,那么效率就更不敢恭維了。雖然這種方法一定可行(因為過濾器可以到輸出的最后一步),但是由于效率問題,我沒有取試。
第三種方法是我自己研究出來的,通過FacesContext類來作,方法如下:
首先,寫一個類
public class Converter {
public static void process(String str){
FacesContext fc=FacesContext.getCurrentInstance();
try {
fc.getResponseWriter().write(str);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
然后在每個backbean中需要getXXX方法中返回是String的方法中修改如下:
把 return XXX 改為 return ""
在return前面,也就是方法的最后一步,添加Converter.process(testValue),這個testValue是你要return的變量
ok,就這么簡單^_^。。。
在網上找了一天沒找到合理解決方法,用這個方法終于解決了。。
(3)faces-config.xml
<application>
<variable-resolver>org.springframework.web.jsf.DelegatingVariableResolver</variable-resolver>
</application>
(4)設置過濾器,解決亂碼問題
詳見:http://www.tkk7.com/algz/articles/201833.html 第二條
以上配置完成后.JSF就可以訪問SPRING管理的BEAN.
四.spring+hiberante集成時,asm-2.2.3.jar與asm.jar沖突:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'SessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.objectweb.asm.ClassVisitor.visit(IILjava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)V
...
Caused by: java.lang.NoSuchMethodError: org.objectweb.asm.ClassVisitor.visit(IILjava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)V
正確的解決方法:
是到項目的發布文件夾\WEB-INF\lib下刪除asm-2.2.3.jar,不能用MyEclipse里刪除.因為他在發布時仍沒刪除.
五.創建進行分類的包.
com.dao(數據訪問層), com.service(業務層), com.web(表示層)
六.創建類.(完成MODEL層設計).
*****************************(也可以利用MyEclipse反向ORM功能自動產生,但應注意自動配置引起的"類完全名"的錯誤)*******************
(一)數據訪問層(DAO)開發:
Spring 配置文件(附加)
(1)配置數據源 <bean id="dataSource" ...> //Myeclipse Hibernate自動反轉工具自動配置
(2)配置會話工廠 <bean id="sessionFactory" ...> //Myeclipse Hibernate自動反轉工具自動配置
(3)配置事務管理器 <bean id="transactionManager" ...>
(4)配置事務代理 www.tkk7.com/algz/articles/163236.html
(5)數據訪問層Bean作為屬性注入業務層Property中. (注:不要用NEW創建數據訪問層對象,否則得不到ServletContext而報錯.)
例:
/**數據訪問層Bean(Myeclipse Hibernate自動反轉工具配置)*/
<bean id="userDao" class="com.data.dao.impl.UserDaoImpl">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
/**業務層Bean(Myeclipse Spring配置文檔中可以配置,但需先定義好相關類)*/
<bean id="userService" class="com.model.service.impl.UserServiceImpl">
<property name="userDao">
<ref bean="userDao" />
</property>
</bean>
1. 創建 數據訪問層接口: 必須創建,詳見:http://www.tkk7.com/algz/articles/262893.html
public interface 數據訪問層接口 { //在類已存在的情況下,添加其接口:Refactor(重構)->Extract Interfaces提取接口
public String add...();
public String save...();
...... //update, delete, load
}
2 .創建數據訪問層實現類 //ORM反向功能自動配置
public class 數據訪問層實現類 extends HibernateDaoSupport implements 數據訪問層接口 {
...... //getHibernateTemplate().save(user)
}
在實現類的方法(throw DataAccessException)中封裝 getHibernateTemplate().save(user) 等Spring已封裝的持久化方法.(注:如果使用Hibernate API 要用try{...}catch{...}自行處理導常.)
3.注意事項: could not initialize proxy - no Session 異常, 可能是沒有聯表查詢.詳見: http://www.tkk7.com/algz/articles/191835.html
*****************************(也可以利用MyEclipse反向ORM功能自動產生)***********************************
(二)業務邏輯層(Service)開發:
1.創建業務邏輯層接口.
package com.service;
import com.dao.CheckDAO;
public interface ICheckService {
public abstract CheckDAO getCheckDAO();
public abstract void setCheckDAO(CheckDAO checkDAO);
public abstract String searchCheck();
}
2.創建業務邏輯層實現類
public class 業務邏輯層實現類 implements 業務邏輯層接口.
在實現類中. 引用的數據訪問層對象實例采用DI的設值方式注入
在業務邏輯方法(throw DataAccessException)中,使用數據訪問層對象實例來訪問數據庫.
package com.service;
import java.util.List;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import com.dao.Check;
import com.dao.CheckDAO;
import com.dao.ICheckDAO;
public class CheckService implements ICheckService {
private CheckDAO checkDAO;
public CheckDAO getCheckDAO() {
return checkDAO;
}
public void setCheckDAO(CheckDAO checkDAO) {
this.checkDAO = checkDAO;
}
public String searchCheck(){
List<Check> l=checkDAO.findAll();
JSONArray ja=new JSONArray();
JSONObject jo=new JSONObject();
for(Check c:l){
// jo.put("department", c.getDepartment());
// jo.put("checkid", c.getCheckid());
// jo.put("nam", c.getNam());
// jo.put("num", c.getNum());
// jo.put("ondutytime", c.getOndutytime());
// jo.put("offdutytime", c.getOffdutytime1());
// jo.put("registerdate", c.getRegisterdate());
// jo.put("overtime", c.getOvertime());
// ja.add(jo.clone());
// jo.clear();
}
return "";
}
}
3.數據訪問層Bean作為屬性注入業務邏輯層實現類的Property中. (注:不要用NEW創建數據訪問層對象,否則得不到ServletContext而報錯.)
例:
/**數據訪問層Bean(Hibernate自動反轉工具自動配置)*/
<bean id="userDao" class="com.data.dao.impl.UserDaoImpl">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
/**業務邏輯層Bean(Spring配置文檔中手動配置,但需先定義好相關類)*/
<bean id="userService" class="com.model.service.impl.UserServiceImpl">
<property name="userDao">
<ref bean="userDao" />
</property>
</bean>
(三).表示層開發
(1)在 faces-config.xml 中配置托管BEAN.(實現控制層層設計)
業務層bean作為屬性注入CONTROL層中.
package com.web;
import com.service.ICheckService;
public class SearchAll {
private ICheckService searchService;
private String searchData;
public SearchAll() {
}
public ICheckService getSearchService() {
return searchService;
}
public void setSearchService(ICheckService searchService) {
this.searchService = searchService;
}
public String getSearchData() {
searchData = searchService.searchCheck();
return searchData;
}
public void setSearchData(String searchData) {
this.searchData = searchData;
}
}
<managed-bean>
<managed-bean-name>userBean</managed-bean-name>
<managed-bean-class>com.web.SearchAll</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>searchService</property-name>
<value> #{userService}</value> //直接引用spring定義的bean
</managed-property>
<managed-property>
<property-name>searchData</property-name> //頁面中 userBean.name訪問屬性的數據
<value>123</value> //屬性默認值
</managed-property>
</managed-bean>
(2)Bean訪問客戶端傳來的參數值
HttpServletRequest request=(HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
String s=request.getParameter("webnam");
七.頁面設計.(實現VIEW層設計)
index.faces:(共二行)
<%@ page language="java" pageEncoding="UTF-8"%> //解決EXTJS 接收數據中有中文出現"?????"等亂碼
${searchAll.searchData} //解決JS接收數據.Ext.store({url:index.faces,...})
頁面中訪問Bean的二種方法
方法一:直接在.faces頁面中使用${userBean.property} (推薦) //property:get/set methord
注,不能使用${userBean.method}
<f:view> //JSF標簽必須放在里面
名稱1: ${userBean.searchData} //正確
//#{userBean.searchData} //報錯
名稱2: <h:inputText value="#{userBean.searchData}"/> //正確
//<h:inputText value="${userBean.searchData}"/> //報錯
//<input value="#{userBean.searchData}"/> //報錯
名稱3: <input value="${userBean.searchData}"/> //正確,而且仍然可以使用JSF的ManagedBean
</f:view>
JSF表達式#{...}只能用在JSF標簽里,JSP表達式${...}也只能用JSP頁面里.
JSP EL的語法格式:${...} 不能放在<%...%>中.
方法二: 在.JSP頁面中,直接獲取業務層定義的BEAN
<%@ page import="javax.servlet.ServletContext" %>
<%@ page import="org.springframework.context.ApplicationContext" %>
<%@ page import="org.springframework.web.context.support.WebApplicationContextUtils" %>
<%
//獲取ApplicationContext對象
ServletContext servletContext = request.getSession().getServletContext();
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(servletContext);
//獲取ApplicationContext.xml文件中定義的BEAN
userServiceps=(userService)ac.getBean("userService");
八.導出war
File->Export->J2EE->WAR file