|
Posted on 2008-09-27 16:09 三羽 閱讀(1185) 評論(0) 編輯 收藏
大家都知道了struts2 和fckEditor結合中為了上傳圖片
需要把
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
換掉
/*
但是在后來使用時發現標簽datetimepicker不能使用了
后來發現生成的頁面中有如下代碼
<link rel="stylesheet" href="/workStation/struts/xhtml/styles.css" type="text/css"/>
<script language="JavaScript" type="text/javascript">
// Dojo configuration
djConfig = {
baseRelativePath: "/workStation/struts/dojo",
isDebug: false,
bindEncoding: "gb2312",
debugAtAllCosts: true // not needed, but allows the Venkman debugger to work with the includes
};
</script>
<script language="JavaScript" type="text/javascript"
src="/workStation/struts/dojo/dojo.js"></script>
<script language="JavaScript" type="text/javascript"
src="/workStation/struts/simple/dojoRequire.js"></script>
所以就應加上
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/struts/*</url-pattern>
</filter-mapping>
要不然會找不到相應的js和css文件,大家遇到希望有幫助(結合時不要忘了在<head>中加入 <s:head />它會自動加上上面的代碼)
----------------------------------------
一 Webwork2 + FCkeditor
Java代碼
/*
* Copyright (c) 2002-2003 by OpenSymphony
* All rights reserved.
*/
package com.leo.controller;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.servlet.ServletContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.opensymphony.webwork.WebWorkException;
import com.opensymphony.webwork.components.AbstractRichtexteditorConnector;
import com.opensymphony.webwork.components.DefaultRichtexteditorConnector;
import com.opensymphony.webwork.util.ServletContextAware;
import com.opensymphony.webwork.views.util.UrlHelper;
import com.opensymphony.xwork.ActionContext;
/**
*
* @author tm_jee
* @version $Date: 2007-03-29 08:02:59 +0200 (Do, 29 Mrz 2007) $ $Id: DefaultRichtexteditorConnector.java 2883 2007-03-29 06:02:59Z tm_jee $
*/
public class MyConnector extends AbstractRichtexteditorConnector implements ServletContextAware {
private static final Log _log = LogFactory.getLog(DefaultRichtexteditorConnector.class);
private static final long serialVersionUID = -3792445192115623052L;
protected String _actualServerPath = "/user_file/";
protected String _serverPath = "/user_file/";
public String getActualServerPath() { return _actualServerPath; }
public void setActualServerPath(String actualServerPath) { _actualServerPath = actualServerPath; }
protected String calculateServerPath(String serverPath, String folderPath, String type) throws Exception {
//return UrlHelper.buildUrl(serverPath, _request, _response, null, _request.getScheme(), true, true, true);
return UrlHelper.buildUrl(serverPath+type+folderPath, _request, _response, new HashMap(), _request.getScheme(), true, true, true);
}
protected String calculateActualServerPath(String actualServerPath, String type, String folderPath) throws Exception {
String path = "file:////"+servletContext.getRealPath(actualServerPath);
path = path.trim();
path = path.replace('\\', '/');
makeDirIfNotExists(path);
path = path.endsWith("/") ? path : path+"/";
return path+type+folderPath;
}
private ServletContext servletContext;
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
protected Folder[] getFolders(String virtualFolderPath, String type) throws Exception {
String path = calculateActualServerPath(getActualServerPath(), type, virtualFolderPath);
makeDirIfNotExists(path);
java.io.File f = new java.io.File(new URI(path));
java.io.File[] children = f.listFiles(new FileFilter() {
public boolean accept(java.io.File pathname) {
if (! pathname.isFile()) {
return true;
}
return false;
}
});
List tmpFolders = new ArrayList();
for (int a=0; a< children.length; a++) {
tmpFolders.add(new Folder(children[a].getName()));
}
return (Folder[]) tmpFolders.toArray(new Folder[0]);
}
protected FoldersAndFiles getFoldersAndFiles(String virtualFolderPath, String type) throws Exception {
String path = calculateActualServerPath(getActualServerPath(), type, virtualFolderPath);
makeDirIfNotExists(path);
java.io.File f = new java.io.File(new URI(path));
java.io.File[] children = f.listFiles();
List directories = new ArrayList();
List files = new ArrayList();
for (int a=0; a< children.length; a++) {
if (children[a].isDirectory()) {
directories.add(new Folder(children[a].getName()));
}
else {
try {
files.add(new File(children[a].getName(), fileSizeInKBytes(children[a])));
}
catch(Exception e) {
_log.error("cannot deal with file "+children[a], e);
}
}
}
// TODO 非常重要的一句話,這樣才能使用自定義的路徑。
ActionContext.getContext().put("__richtexteditorServerPath", calculateServerPath(get_serverPath(), getCurrentFolder(), getType()));
return new FoldersAndFiles(
(Folder[]) directories.toArray(new Folder[0]),
(File[]) files.toArray(new File[0])
);
}
protected CreateFolderResult createFolder(String virtualFolderPath, String type, String newFolderName) {
try {
String tmpPath = calculateActualServerPath(getActualServerPath(), type, virtualFolderPath);
tmpPath = tmpPath+newFolderName;
boolean alreadyExists = makeDirIfNotExists(tmpPath);
if (alreadyExists) {
return CreateFolderResult.folderAlreadyExists();
}
}
catch(Exception e) {
_log.error(e.toString(), e);
return CreateFolderResult.unknownError();
}
return CreateFolderResult.noErrors();
}
protected FileUploadResult fileUpload(String virtualFolderPath, String type, String filename, String contentType, java.io.File newFile) {
try {
String tmpDir = calculateActualServerPath(getActualServerPath(), type, virtualFolderPath);
makeDirIfNotExists(tmpDir);
String tmpFile = tmpDir+filename;
if(makeFileIfNotExists(tmpFile)) {
// already exists
int a=0;
String ext = String.valueOf(a);
tmpFile = calculateActualServerPath(getActualServerPath(), type, virtualFolderPath)+filename+ext;
while(makeFileIfNotExists(tmpFile)) {
a = a + 1;
ext = String.valueOf(a);
if (a > 100) {
return FileUploadResult.invalidFile();
}
tmpFile = calculateActualServerPath(getActualServerPath(), type, virtualFolderPath)+filename+ext;
}
copyFile(newFile, new java.io.File(new URI(tmpFile)));
return FileUploadResult.uploadCompleteWithFilenamChanged(filename+ext);
}
else {
copyFile(newFile, new java.io.File(new URI(tmpFile)));
return FileUploadResult.uploadComplete();
}
}
catch(Exception e) {
_log.error(e.toString(), e);
return FileUploadResult.invalidFile();
}
}
protected void unknownCommand(String command, String virtualFolderPath, String type, String filename, String contentType, java.io.File newFile) {
throw new WebWorkException("unknown command "+command);
}
/**
*
* @param path
* @return true if file already exists, false otherwise.
*/
protected boolean makeDirIfNotExists(String path) throws URISyntaxException {
java.io.File dir = new java.io.File(new URI(path));
if (! dir.exists()) {
if (_log.isDebugEnabled()) {
_log.debug("make directory "+dir);
}
boolean ok = dir.mkdirs();
if (! ok) {
throw new WebWorkException("cannot make directory "+dir);
}
return false;
}
return true;
}
/**
*
* @param filePath
* @return true if file already exists, false otherwise
*/
protected boolean makeFileIfNotExists(String filePath) throws IOException, URISyntaxException {
java.io.File f = new java.io.File(new URI(filePath));
if (! f.exists()) {
if (_log.isDebugEnabled()) {
_log.debug("creating file "+filePath);
}
boolean ok = f.createNewFile();
if (! ok) {
throw new WebWorkException("cannot create file "+filePath);
}
return false;
}
return true;
}
protected void copyFile(java.io.File from, java.io.File to) throws FileNotFoundException, IOException {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
if (_log.isDebugEnabled()) {
_log.debug("copy file from "+from+" to "+to);
}
fis = new FileInputStream(from);
fos = new FileOutputStream(to);
int tmpByte = fis.read();
while(tmpByte != -1) {
fos.write(tmpByte);
tmpByte = fis.read();
}
fos.flush();
}
finally {
if (fis != null)
fis.close();
if (fos != null)
fos.close();
}
}
protected long fileSizeInKBytes(java.io.File file) throws FileNotFoundException, IOException {
FileInputStream fis = null;
long size = 0;
try {
fis = new FileInputStream(file);
size = fis.getChannel().size();
}
finally {
if (fis != null)
fis.close();
}
if (size > 0) {
size = (size / 100);
}
if (_log.isDebugEnabled()) {
_log.debug("size of file "+file+" is "+size+" kb");
}
return size;
}
public String get_serverPath() {
return _serverPath;
}
public void set_serverPath(String path) {
_serverPath = path;
}
}

/*
* Copyright (c) 2002-2003 by OpenSymphony
* All rights reserved.
*/
package com.leo.controller;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.opensymphony.webwork.WebWorkException;
import com.opensymphony.webwork.components.AbstractRichtexteditorConnector;
import com.opensymphony.webwork.components.DefaultRichtexteditorConnector;
import com.opensymphony.webwork.util.ServletContextAware;
import com.opensymphony.webwork.views.util.UrlHelper;
import com.opensymphony.xwork.ActionContext;

/**
*
* @author tm_jee
* @version $Date: 2007-03-29 08:02:59 +0200 (Do, 29 Mrz 2007) $ $Id: DefaultRichtexteditorConnector.java 2883 2007-03-29 06:02:59Z tm_jee $
*/
public class MyConnector extends AbstractRichtexteditorConnector implements ServletContextAware {

private static final Log _log = LogFactory.getLog(DefaultRichtexteditorConnector.class);

private static final long serialVersionUID = -3792445192115623052L;

protected String _actualServerPath = "/user_file/";
protected String _serverPath = "/user_file/";


public String getActualServerPath() { return _actualServerPath; }
public void setActualServerPath(String actualServerPath) { _actualServerPath = actualServerPath; }


protected String calculateServerPath(String serverPath, String folderPath, String type) throws Exception {
//return UrlHelper.buildUrl(serverPath, _request, _response, null, _request.getScheme(), true, true, true);
return UrlHelper.buildUrl(serverPath+type+folderPath, _request, _response, new HashMap(), _request.getScheme(), true, true, true);
}

protected String calculateActualServerPath(String actualServerPath, String type, String folderPath) throws Exception {
String path = "file:////"+servletContext.getRealPath(actualServerPath);
path = path.trim();
path = path.replace('\\', '/');
makeDirIfNotExists(path);
path = path.endsWith("/") ? path : path+"/";
return path+type+folderPath;
}

private ServletContext servletContext;
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}

protected Folder[] getFolders(String virtualFolderPath, String type) throws Exception {
String path = calculateActualServerPath(getActualServerPath(), type, virtualFolderPath);
makeDirIfNotExists(path);
java.io.File f = new java.io.File(new URI(path));
java.io.File[] children = f.listFiles(new FileFilter() {
public boolean accept(java.io.File pathname) {
if (! pathname.isFile()) {
return true;
}
return false;
}
});

List tmpFolders = new ArrayList();
for (int a=0; a< children.length; a++) {
tmpFolders.add(new Folder(children[a].getName()));
}

return (Folder[]) tmpFolders.toArray(new Folder[0]);
}

protected FoldersAndFiles getFoldersAndFiles(String virtualFolderPath, String type) throws Exception {
String path = calculateActualServerPath(getActualServerPath(), type, virtualFolderPath);
makeDirIfNotExists(path);
java.io.File f = new java.io.File(new URI(path));
java.io.File[] children = f.listFiles();

List directories = new ArrayList();
List files = new ArrayList();
for (int a=0; a< children.length; a++) {
if (children[a].isDirectory()) {
directories.add(new Folder(children[a].getName()));
}
else {
try {
files.add(new File(children[a].getName(), fileSizeInKBytes(children[a])));
}
catch(Exception e) {
_log.error("cannot deal with file "+children[a], e);
}
}
}
// TODO 非常重要的一句話,這樣才能使用自定義的路徑。
ActionContext.getContext().put("__richtexteditorServerPath", calculateServerPath(get_serverPath(), getCurrentFolder(), getType()));

return new FoldersAndFiles(
(Folder[]) directories.toArray(new Folder[0]),
(File[]) files.toArray(new File[0])
);
}

protected CreateFolderResult createFolder(String virtualFolderPath, String type, String newFolderName) {
try {
String tmpPath = calculateActualServerPath(getActualServerPath(), type, virtualFolderPath);
tmpPath = tmpPath+newFolderName;
boolean alreadyExists = makeDirIfNotExists(tmpPath);
if (alreadyExists) {
return CreateFolderResult.folderAlreadyExists();
}
}
catch(Exception e) {
_log.error(e.toString(), e);
return CreateFolderResult.unknownError();
}
return CreateFolderResult.noErrors();
}

protected FileUploadResult fileUpload(String virtualFolderPath, String type, String filename, String contentType, java.io.File newFile) {
try {
String tmpDir = calculateActualServerPath(getActualServerPath(), type, virtualFolderPath);
makeDirIfNotExists(tmpDir);
String tmpFile = tmpDir+filename;
if(makeFileIfNotExists(tmpFile)) {
// already exists
int a=0;
String ext = String.valueOf(a);
tmpFile = calculateActualServerPath(getActualServerPath(), type, virtualFolderPath)+filename+ext;
while(makeFileIfNotExists(tmpFile)) {
a = a + 1;
ext = String.valueOf(a);
if (a > 100) {
return FileUploadResult.invalidFile();
}
tmpFile = calculateActualServerPath(getActualServerPath(), type, virtualFolderPath)+filename+ext;
}
copyFile(newFile, new java.io.File(new URI(tmpFile)));
return FileUploadResult.uploadCompleteWithFilenamChanged(filename+ext);
}
else {
copyFile(newFile, new java.io.File(new URI(tmpFile)));
return FileUploadResult.uploadComplete();
}
}
catch(Exception e) {
_log.error(e.toString(), e);
return FileUploadResult.invalidFile();
}
}

protected void unknownCommand(String command, String virtualFolderPath, String type, String filename, String contentType, java.io.File newFile) {
throw new WebWorkException("unknown command "+command);
}





/**
*
* @param path
* @return true if file already exists, false otherwise.
*/
protected boolean makeDirIfNotExists(String path) throws URISyntaxException {
java.io.File dir = new java.io.File(new URI(path));
if (! dir.exists()) {
if (_log.isDebugEnabled()) {
_log.debug("make directory "+dir);
}
boolean ok = dir.mkdirs();
if (! ok) {
throw new WebWorkException("cannot make directory "+dir);
}
return false;
}
return true;
}

/**
*
* @param filePath
* @return true if file already exists, false otherwise
*/
protected boolean makeFileIfNotExists(String filePath) throws IOException, URISyntaxException {
java.io.File f = new java.io.File(new URI(filePath));
if (! f.exists()) {
if (_log.isDebugEnabled()) {
_log.debug("creating file "+filePath);
}
boolean ok = f.createNewFile();
if (! ok) {
throw new WebWorkException("cannot create file "+filePath);
}
return false;
}
return true;
}

protected void copyFile(java.io.File from, java.io.File to) throws FileNotFoundException, IOException {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
if (_log.isDebugEnabled()) {
_log.debug("copy file from "+from+" to "+to);
}
fis = new FileInputStream(from);
fos = new FileOutputStream(to);
int tmpByte = fis.read();
while(tmpByte != -1) {
fos.write(tmpByte);
tmpByte = fis.read();
}
fos.flush();
}
finally {
if (fis != null)
fis.close();
if (fos != null)
fos.close();
}
}

protected long fileSizeInKBytes(java.io.File file) throws FileNotFoundException, IOException {
FileInputStream fis = null;
long size = 0;
try {
fis = new FileInputStream(file);
size = fis.getChannel().size();
}
finally {
if (fis != null)
fis.close();
}
if (size > 0) {
size = (size / 100);
}
if (_log.isDebugEnabled()) {
_log.debug("size of file "+file+" is "+size+" kb");
}
return size;
}
public String get_serverPath() {
return _serverPath;
}
public void set_serverPath(String path) {
_serverPath = path;
}
}


注意以下變量部分:

1.在MyConnector.java第42行的變量_actualServerPath 默認為值:/WEB-INF/classes/com/opensymphony/webwork/static/richtexteditor/data/,從源碼com.opensymphony.webwork.components.DefaultRichtexteditorConnector.java的第38行

Java代碼
protected String _actualServerPath = "/com/opensymphony/webwork/static/richtexteditor/data/";

protected String _actualServerPath = "/com/opensymphony/webwork/static/richtexteditor/data/";以及第51行

Java代碼
String path = "file:////"+servletContext.getRealPath("/WEB-INF/classes"+actualServerPath);

String path = "file:////"+servletContext.getRealPath("/WEB-INF/classes"+actualServerPath);


可以得出。
因此,我這里改成/user_file文件夾作為文件上傳路徑,你可以自由選擇。


2.在MyConnector.java第43行的變量_serverPath 表示的是上傳完附件后,選擇的路徑,默認為: /webwork/richtexteditor/data/。從源碼com.opensymphony.webwork.components.AbstractRichtexteditorConnector.java的第73行:

Java代碼
protected String _serverPath = "/webwork/richtexteditor/data/";

protected String _serverPath = "/webwork/richtexteditor/data/"; 可以看到。但FCKEditor使用時,會變成:http://IP地址/項目/webwork/richtexteditor/data/. 記住,這里不會帶端口號的,這也是唯一美中不足的地方,如果要修改,可能要改動很大了。


因此,我這里改成也/user_file文件夾,為了可以在上傳成功后,FCKEditor能夠選擇上傳成功的文件。


最后來到MyConnector.java 的第112行:


Java代碼
// TODO 非常重要的一句話,這樣才能使用自定義的路徑。
ActionContext.getContext().put("__richtexteditorServerPath", calculateServerPath(get_serverPath(), getCurrentFolder(), getType()));

// TODO 非常重要的一句話,這樣才能使用自定義的路徑。
ActionContext.getContext().put("__richtexteditorServerPath", calculateServerPath(get_serverPath(), getCurrentFolder(), getType()));

這里我詳細說一下:MyConnector.java 繼承自 AbstractRichtexteditorConnector.java,在AbstractRichtexteditorConnector.java源碼146行左右有這么一段:


Java代碼
else if ("CreateFolder".equals(getCommand())) {
_log.debug("Command "+getCommand()+" detected \n\t type="+getType()+"\n\t folderPath="+getCurrentFolder()+"\n\t newFolderName="+getNewFolderName());
ActionContext.getContext().put("__richtexteditorCommand", getCommand());
ActionContext.getContext().put("__richtexteditorType", getType());
ActionContext.getContext().put("__richtexteditorFolderPath", getCurrentFolder());
ActionContext.getContext().put("__richtexteditorServerPath", calculateServerPath(getServerPath(), getCurrentFolder(), getType()));
CreateFolderResult createFolderResult = createFolder(getCurrentFolder(), getType(), getNewFolderName());
ActionContext.getContext().put("__richtexteditorCreateFolder", createFolderResult);
return CREATE_FOLDER;
}

else if ("CreateFolder".equals(getCommand())) {
_log.debug("Command "+getCommand()+" detected \n\t type="+getType()+"\n\t folderPath="+getCurrentFolder()+"\n\t newFolderName="+getNewFolderName());
ActionContext.getContext().put("__richtexteditorCommand", getCommand());
ActionContext.getContext().put("__richtexteditorType", getType());
ActionContext.getContext().put("__richtexteditorFolderPath", getCurrentFolder());
ActionContext.getContext().put("__richtexteditorServerPath", calculateServerPath(getServerPath(), getCurrentFolder(), getType()));
CreateFolderResult createFolderResult = createFolder(getCurrentFolder(), getType(), getNewFolderName());
ActionContext.getContext().put("__richtexteditorCreateFolder", createFolderResult);
return CREATE_FOLDER;
}
在這段代碼的第7行,計算出的路徑永遠是父類里默認的 /webwork/richtexteditor/data/, 所以在它的子類MyConnector.java,我們重新賦值了一下: Java代碼
// TODO 非常重要的一句話,這樣才能使用自定義的路徑。
ActionContext.getContext().put("__richtexteditorServerPath", calculateServerPath(get_serverPath(), getCurrentFolder(), getType()));

// TODO 非常重要的一句話,這樣才能使用自定義的路徑。
ActionContext.getContext().put("__richtexteditorServerPath", calculateServerPath(get_serverPath(), getCurrentFolder(), getType()));


這樣,就能保證我們剛才定義的 user_file文件夾生效,文件通過FCKEditor上傳完后,通過服務器端瀏覽,可以看到我們上傳的圖片,然后點確定就可以了。不過,如果你不是默認的80端口,那么可能要手動改一改,真是有點遺憾。最后一步,也是最重要的一步,配置我們剛才寫的MyConnector.java


Xml代碼
<package name="richtexteditor-upload" extends="webwork-default"
namespace="/webwork/richtexteditor/editor/filemanager/upload">
<action name="uploader" class="com.leo.controller.MyConnector"
method="upload">
<result name="richtexteditorFileUpload" />
</action>
</package>
<package name="richtexteditor-browse" extends="webwork-default"
namespace="/webwork/richtexteditor/editor/filemanager/browser/default/connectors/jsp">
<action name="connector" class="com.leo.controller.MyConnector"
method="browse">
<result name="getFolders" type="richtexteditorGetFolders" />
<result name="getFoldersAndFiles"
type="richtexteditorGetFoldersAndFiles" />
<result name="createFolder"
type="richtexteditorCreateFolder" />
<result name="fileUpload" type="richtexteditorFileUpload" />
</action>
</package>

<package name="richtexteditor-upload" extends="webwork-default"
namespace="/webwork/richtexteditor/editor/filemanager/upload">
<action name="uploader" class="com.leo.controller.MyConnector"
method="upload">
<result name="richtexteditorFileUpload" />
</action>
</package>

<package name="richtexteditor-browse" extends="webwork-default"
namespace="/webwork/richtexteditor/editor/filemanager/browser/default/connectors/jsp">
<action name="connector" class="com.leo.controller.MyConnector"
method="browse">
<result name="getFolders" type="richtexteditorGetFolders" />
<result name="getFoldersAndFiles"
type="richtexteditorGetFoldersAndFiles" />
<result name="createFolder"
type="richtexteditorCreateFolder" />
<result name="fileUpload" type="richtexteditorFileUpload" />
</action>
</package>

一切完成,直接在JSP里調用即可:Html代碼
<ww:richtexteditor toolbarCanCollapse="true" width="700" label=""
name="txt" value="可以正常上傳了。" />

<ww:richtexteditor toolbarCanCollapse="true" width="700" label=""
name="txt" value="可以正常上傳了。" />



二 Struts2 + Dojo


Struts2部分更簡單了。雖然Struts2不直接支持FCKeditor,但直接Dojo,而且個人更喜歡這種簡潔的風格,我用的是Struts2.0.11版本進行測試,使用時,只要配置兩個地方

1. 在HTML<head />標簽之間,加上

Html代碼
<s:head theme="ajax"/>

<s:head theme="ajax"/>
2. 將textarea加上主題 Html代碼
<s:textarea theme="ajax" />

<s:textarea theme="ajax" />

就這么簡單。

/Files/tunaic/webwork_test.rar
|