struts2+ckeditor+ckfinder實現文件的上傳、從數據庫獲取數據、修改並提交到數據庫中保存

示例下載地址:http://download.csdn.net/detail/lin062854/7116033


第一步:工具下載

首先下載struts2

        下載地址:http://struts.apache.org/download.cgi#struts2315-SNAPSHOT

第二下載:CKEditor

        下載地址:http://ckeditor.com/download   (最新版本ckeditor 4.1.2)

第三下載:CKFinder

        下載地址:http://cksource.com/ckfinder/download  (最新版本ckfinder 2.3.1)

 

第二步:新建項目

      打開myeclipse -->File --> New -->Web Project

      項目名:ThreeGorgesSoulSystem

 

第三步:整合

      首先解壓:struts-2.3.14.2-all.zip,然後拷貝最小安裝包放在WEB-INF/lib下:

       在struts-2.3.14.2\apps打開struts2-blank.war,在WEB-INF\src\java下,拷貝struts.xml到classpath(src)下

       編輯WEB-INF\web.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
	xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

  <filter>
    <filter-name>struts2</filter-name>
    <!--  
      <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    -->
    <filter-class>com.orange.web.filter.FCKFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <welcome-file-list>
    <welcome-file>/index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 

        解壓ckeditor_ckeditor_4.1.2_full.zip,然後將ckeditor文件夾全部拷到WebRoot根目錄下。

      修改ckeditor文件下的config.js文件,代碼如下:

/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/

CKEDITOR.editorConfig = function (config) {
    // Define changes to default configuration here. For example:
    // config.language = 'fr';
    // config.uiColor = '#AADC6E';

    //CKFinder.SetupCKEditor(null, '../ckfinder/'); //注意ckfinder的路徑對應實際放置的位置
    config.skin = 'v2'; // 皮膚
    //config.uiColor = '#FFF'; // 皮膚背景顏色
    //config.resize_enabled = false;   // 取消 “拖拽以改變尺寸”功能   
    config.language = 'zh-cn'; //配置語言 
    config.font_names = '宋體;楷體_GB2312;新宋體;黑體;隸書;幼圓;微軟雅黑;Arial;Comic Sans MS;Courier New;Tahoma;Times New Roman;Verdana'; // 字體
    config.width = 1000; //寬度
    config.height = 450; //高度

    //config.toolbar = "Basic";  // 基礎工具欄
    config.toolbar = "Full";  // 全能工具欄 
    // 自定義工具欄  
    config.toolbar_Full =
    [
        ['Source', '-', 'Preview', '-', 'Templates'],
        ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Print', 'SpellChecker', 'Scayt'],
        ['Undo', 'Redo', '-', 'Find', 'Replace', '-', 'SelectAll', 'RemoveFormat'],
        ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'],
        '/',
        ['Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript'],
        ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', 'Blockquote', 'CreateDiv'],
        ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
        ['Link', 'Unlink', 'Anchor'],
          ['Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak'],
        '/',
        ['Styles', 'Format', 'Font', 'FontSize'],
        ['TextColor', 'BGColor'],
        ['Maximize', 'ShowBlocks', '-', 'About']
    ];

    config.toolbar_Basic =
    [
        ['Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink', '-', 'About']
    ];
    
    /*** 文件上傳功能的配置-----------------------
	 */
	config.filebrowserBrowseUrl = 'ckfinder/ckfinder.html'; 
    config.filebrowserImageBrowseUrl = 'ckfinder/ckfinder.html?type=Images';
    config.filebrowserFlashBrowseUrl = 'ckfinder/ckfinder.html?type=Flash';
    config.filebrowserUploadUrl = 'ckfinder/core/connector/java/connector.java?command=QuickUpload&type=Files';
    config.filebrowserImageUploadUrl = 'ckfinder/core/connector/java/connector.java?command=QuickUpload&type=Images';
    config.filebrowserFlashUploadUrl = 'ckfinder/core/connector/java/connector.java?command=QuickUpload&type=Flash';
	//---------------------------文件上傳功能的配置結束--------
};


        接着解壓:ckfinder_java_2.3.1.zip,在ckfinder目錄下再解壓CKFinderJava.war,將CKFinderJava下的ckfinder文件夾拷貝到WebRoot根目錄下,目錄結構如下圖:

       接着把config.xml拷貝到WEB-INF/下

       配置config.xml文件:

<config>

	<!-- 開啓上傳功能,如果爲false爲提示
	:因爲安全原因,文件不可瀏覽. 請聯繫系統管理員並檢查CKFinder配置文件. 
	並且默認你是是爲false的 -->
	<enabled>true</enabled>

	<!-- 文件存放的地址    /ckfinder/userfiles/   (自動創建) -->
	<baseURL>/ThreeGorgesSoulSystem/upload/</baseURL>
	
	
	<!--檢查雙擴展名   -->
	<checkDoubleExtension>true</checkDoubleExtension>
	
	<!-- 在縮放後檢查大小 -->
	<checkSizeAfterScaling>true</checkSizeAfterScaling>
	

	<!-- 配置路徑以及格式 -->
	<types>
		<type name="Files">
			<url>%BASE_URL%files/</url>
			<directory>%BASE_DIR%files</directory>
			<maxSize>0</maxSize>
			<allowedExtensions>7z,aiff,asf,avi,bmp,csv,doc,docx,fla,flv,gif,gz,gzip,jpeg,jpg,mid,mov,mp3,mp4,mpc,mpeg,mpg,ods,odt,pdf,png,ppt,pptx,pxd,qt,ram,rar,rm,rmi,rmvb,rtf,sdc,sitd,swf,sxc,sxw,tar,tgz,tif,tiff,txt,vsd,wav,wma,wmv,xls,xlsx,zip
			</allowedExtensions>
			<deniedExtensions></deniedExtensions>
		</type>
		<type name="Images">
			<url>%BASE_URL%images/</url>
			<directory>%BASE_DIR%images</directory>
			<maxSize>0</maxSize>
			<allowedExtensions>bmp,gif,jpeg,jpg,png</allowedExtensions>
			<deniedExtensions></deniedExtensions>
		</type>
		<type name="Flash">
			<url>%BASE_URL%flash/</url>
			<directory>%BASE_DIR%flash</directory>
			<maxSize>0</maxSize>
			<allowedExtensions>swf,flv</allowedExtensions>
			<deniedExtensions></deniedExtensions>
		</type>
	</types>
	
	<!--  可允許的操作  -->
	<accessControls>
		<accessControl>
			<role>*</role>
			<resourceType>*</resourceType>
			<folder>/</folder>
			<folderView>true</folderView>
			<folderCreate>true</folderCreate>
			<folderRename>true</folderRename>
			<folderDelete>true</folderDelete>
			<fileView>true</fileView>
			<fileUpload>true</fileUpload>
			<fileRename>true</fileRename>
			<fileDelete>true</fileDelete>
		</accessControl>
	</accessControls>
	<thumbs>
		<enabled>true</enabled>
		<url>%BASE_URL%_thumbs/</url>
		<directory>%BASE_DIR%_thumbs</directory>
		<directAccess>false</directAccess>
		<maxHeight>100</maxHeight>
		<maxWidth>100</maxWidth>
		<quality>80</quality>
	</thumbs>
	
	
	<!-- 圖片瀏覽——圖片縮略圖 -->
	<plugins>
		<plugin>
			<name>imageresize</name>
			<class>com.ckfinder.connector.plugins.ImageResize</class>
			<params>
				<param name="smallThumb" value="90x90"></param>
				<param name="mediumThumb" value="120x120"></param>
				<param name="largeThumb" value="180x180"></param>
			</params>
		</plugin>
		<plugin>
			<name>fileeditor</name>
			<class>com.ckfinder.connector.plugins.FileEditor</class>
			<params></params>
		</plugin>
	</plugins>
	<basePathBuilderImpl>com.ckfinder.connector.configuration.ConfigurationPathBuilder</basePathBuilderImpl>
</config>
	

 

      在配置web.xml文件中添加ckeditor+ckfinder配置信息

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
	xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

  <filter>
    <filter-name>struts2</filter-name>
    <!--  
      <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    -->
    <filter-class>com.orange.web.filter.FCKFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

 <!-- =================ckeditor+ckfinder圖片上傳功能的配置=================== -->
   <servlet>
   		<!-- servlet的命 名===註冊名稱,這個名稱可以任意的        -->
		<servlet-name>ConnectorServlet</servlet-name>
		<!-- servlet 所在包  -->
		<servlet-class>com.ckfinder.connector.ConnectorServlet</servlet-class>
		<init-param>
			<!-- 初始化設置 -->
			<param-name>XMLConfig</param-name>
			<param-value>/WEB-INF/config.xml</param-value>
		</init-param>
		<init-param>
			<!-- 設置是否可以查看debug,在正常時候需要設置爲false. -->
			<param-name>debug</param-name>
			<param-value>false</param-value>
		</init-param>
		
		<!-- 
		
		load-on-startup 元素在web應用啓動的時候指定了
		servlet被加載的順序,它的值必須是一個整數。
		如果它的值是一個負整數或是這個元素不存在,
		那麼容器會在該servlet被調用的時候,加載這個servlet 
		。如果值是正整數或零,容器在配置的時候就加載並初始化這個servlet,
		容器必須保證值小的先被加載。如果值相等,容器可以自動選擇先加載誰。

		
		在此不是必須的
		 -->
		<load-on-startup>1</load-on-startup>
	</servlet>
	
	
	<!-- 映射的相對路徑,主要是在其他地方使用,比如js,頁面訪問  -->
	<servlet-mapping>
		<servlet-name>ConnectorServlet</servlet-name>
		<url-pattern>
			/ckfinder/core/connector/java/connector.java
		</url-pattern>
	</servlet-mapping>

<!-- =================ckeditor+ckfinder圖片上傳功能的配置結束=================== -->
  
  <welcome-file-list>
    <welcome-file>/index.jsp</welcome-file>
  </welcome-file-list>
</web-app>


 

注:1.將ckfinder中的_samples文件夾直接刪除

         2.如果jquery.min.js出錯,是因爲採用了壓縮的jquery庫,不被識別,在http://jquery.com/download/下載

       點擊鏈接,把jQuery2.0.2中的代碼直接替換項目中jquery.min.js中的代碼

  

 

第四步:java代碼和頁面

action層中的代碼:    

package com.orange.web.action;
import java.sql.SQLException;
import com.orange.domain.Classify;
import com.orange.domain.Menu;
import com.orange.service.ClassifyService;
import com.orange.service.MenuService;
import com.orange.service.impl.ClassifyServiceImpl;
import com.orange.service.impl.MenuServiceImpl;


public class ClassifyAction {
	/**
	 * menuId
	 */
	private int menuId;
	/**
	 * 分類信息
	 */
	private Classify classify;
	/**
	 * 獲取文本域中的內容(ckeditor中textared內容)
	 */
	private String editor1;
	/**
	 * 簡介
	 */
	private Classify intro;
	/**
	 * 文化
	 */
	private Classify cultural;
	/**
	 * 精神
	 */
	private Classify spirit;
	/**
	 * 旅遊
	 */
	private Classify tourism;

	private ClassifyService classifyService = new ClassifyServiceImpl();

	private MenuService menuService = new MenuServiceImpl();

	public String listToMenuId() {
		try {
			classify = classifyService.listToMenuId(menuId);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "listToMenuId";
	}
	public String updateClassify(){
		Menu menu = new Menu();
		try {
			menu = menuService.listMenu(menuId);
			classify.setMenu(menu);
			classify.setClassifyContent(editor1);
			classifyService.updateClassify(classify);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return initalize();
	}
	public String initalize() {
		try {
			intro = classifyService.listToMenuId(11000);
			cultural = classifyService.listToMenuId(21000);
			spirit = classifyService.listToMenuId(31000);
			tourism = classifyService.listToMenuId(41000);
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "threegorgessoul";
	}
	public int getMenuId() {
		return menuId;
	}
	public void setMenuId(int menuId) {
		this.menuId = menuId;
	}
	public Classify getClassify() {
		return classify;
	}
	public void setClassify(Classify classify) {
		this.classify = classify;
	}
	public String getEditor1() {
		return editor1;
	}
	public void setEditor1(String editor1) {
		this.editor1 = editor1;
	}
	public Classify getIntro() {
		return intro;
	}
	public void setIntro(Classify intro) {
		this.intro = intro;
	}
	public Classify getCultural() {
		return cultural;
	}
	public void setCultural(Classify cultural) {
		this.cultural = cultural;
	}
	public Classify getSpirit() {
		return spirit;
	}
	public void setSpirit(Classify spirit) {
		this.spirit = spirit;
	}
	public Classify getTourism() {
		return tourism;
	}
	public void setTourism(Classify tourism) {
		this.tourism = tourism;
	}
	
}

service層:

package com.orange.service.impl;
import java.sql.SQLException;
import java.util.List;
import com.orange.dao.ClassifyDao;
import com.orange.dao.impl.ClassifyDaoImpl;
import com.orange.domain.Classify;
import com.orange.service.ClassifyService;

public class ClassifyServiceImpl implements ClassifyService {
	
	private ClassifyDao classifyDao = new ClassifyDaoImpl();
	
	/**
	 * 添加分類
	 * 
	 * @param classify
	 * @throws SQLException
	 */
	public void addClassify(Classify classify) throws SQLException {
		classifyDao.addClassify(classify);
	}

	/**
	 * 修改評論
	 * 
	 * @param classify
	 * @throws SQLException
	 */
	public void updateClassify(Classify classify) throws SQLException {
		classifyDao.updateClassify(classify);
	}

	/**
	 * 刪除評論
	 * 
	 * @param classify_Id
	 * @throws SQLException
	 */
	public void deleteClassify(int classifyId) throws SQLException {
		classifyDao.deleteClassify(classifyId);
	}

	/**
	 * 根據id查看評論
	 * 
	 * @param classify_Id
	 * @return
	 * @throws SQLException
	 */
	public Classify listClassify(int classifyId) throws SQLException {
		return classifyDao.listClassify(classifyId);
	}
	/**
	 * 根據menuId查看評論
	 * 
	 * @param classify_Id
	 * @return
	 * @throws SQLException
	 */
	public Classify listToMenuId(int menuId) throws SQLException {
		return classifyDao.listToMenuId(menuId);
	}

	/**
	 * 查看所有評論信息
	 * 
	 * @return
	 * @throws SQLException
	 */
	public List<Classify> listAllClassify() throws SQLException {
		return classifyDao.listAllClassify();
	}

	/**
	 * 查詢從page條數據開始,總控查詢rows條記錄
	 * 
	 * @param page
	 * @param rows
	 * @return
	 * @throws SQLException
	 */
	public List<Classify> listAllClassify(int page, int rows)
			throws SQLException {
		return classifyDao.listAllClassify(page, rows);
	}

	/**
	 * 查詢數據庫中得所有記錄數據
	 * 
	 * @return
	 * @throws SQLException
	 */
	public int getCount() throws SQLException {
		return classifyDao.getCount();
	}

}

dao層:

package com.orange.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import com.orange.common.DataBaseUtils;
import com.orange.dao.ClassifyDao;
import com.orange.domain.Classify;
import com.orange.domain.Menu;

public class ClassifyDaoImpl implements ClassifyDao {
	Classify classify = new Classify();

	public void addClassify(Classify classify) throws SQLException {
		String sql = "insert into t_classify(classify_title,classify_content,menu_id) values(?, ?, ?)";
		Object[] params = {
			classify.getClassifyTitle(),
			classify.getClassifyContent(), 
			classify.getMenu().getMenuId()
		};

		DataBaseUtils.executeUpdate(sql, params);

	}

	public void updateClassify(Classify classify) throws SQLException {
		String sql = "update t_classify set classify_title=?,classify_content=?,menu_id=? where classify_id = ?";
		Object[] params = { 				
				classify.getClassifyTitle(),
				classify.getClassifyContent(), 
				classify.getMenu().getMenuId(),
				classify.getClassifyId() 

		};
		DataBaseUtils.executeUpdate(sql, params);

	}

	public void deleteClassify(int classifyId) throws SQLException {
		String sql = "delete  from t_classify where classify_Id=?";
		Object[] params = { classifyId };

		DataBaseUtils.executeUpdate(sql, params);

	}
	public Classify listClassify(int classifyId) throws SQLException {
		Classify classify = null;
		Connection conn = null;
		PreparedStatement pst = null;
		ResultSet res = null;

		try {

			conn = DataBaseUtils.getConnection();

			pst = conn.prepareStatement("SELECT  " +
					"c.classify_id,c.classify_title,c.classify_content,c.menu_id, " +
					"m.menu_id,m.menu_name,m.model_id " +
					" FROM " +
					"t_classify AS c , " +
					"t_menu AS m " +
					" WHERE " +
					"c.menu_id =  m.menu_id AND " +
					"c.classify_id =  ?");

			pst.setInt(1, classifyId);

			res = pst.executeQuery();

			if (res.next()) {

				classify = new Classify();
				classify.setClassifyId(res.getInt("classify_Id"));
				classify.setClassifyTitle(res.getString("classify_title"));
				classify.setClassifyContent(res.getString("classify_content"));
				Menu menu = new Menu();
				menu.setMenuId(res.getInt("menu_id"));
				menu.setMenuName(res.getString("menu_name"));
				menu.setModel(null);
				classify.setMenu(menu);
			}

		} finally {
			DataBaseUtils.close(conn, pst, res);
		}

		return classify;

	}
	/**
	 * 根據menuId查看評論
	 * 
	 * @param classify_Id
	 * @return
	 * @throws SQLException
	 */
	public Classify listToMenuId(int menuId) throws SQLException {
		Classify classify = null;
		Connection conn = null;
		PreparedStatement pst = null;
		ResultSet res = null;

		try {

			conn = DataBaseUtils.getConnection();

			pst = conn.prepareStatement("SELECT  " +
					"c.classify_id,c.classify_title,c.classify_content,c.menu_id, " +
					"m.menu_id,m.menu_name,m.model_id " +
					" FROM " +
					"t_classify AS c , " +
					"t_menu AS m " +
					" WHERE " +
					"c.menu_id =  m.menu_id AND " +
					"c.menu_id =  ?");

			pst.setInt(1, menuId);

			res = pst.executeQuery();

			if (res.next()) {

				classify = new Classify();
				classify.setClassifyId(res.getInt("classify_Id"));
				classify.setClassifyTitle(res.getString("classify_title"));
				classify.setClassifyContent(res.getString("classify_content"));
				Menu menu = new Menu();
				menu.setMenuId(res.getInt("menu_id"));
				menu.setMenuName(res.getString("menu_name"));
				menu.setModel(null);
				classify.setMenu(menu);
			}

		} finally {
			DataBaseUtils.close(conn, pst, res);
		}

		return classify;

	}
	public List<Classify> listAllClassify() throws SQLException {

		List<Classify> classifys = new LinkedList<Classify>();
		Connection conn = null;
		PreparedStatement pst = null;
		ResultSet res = null;

		try {

			conn = DataBaseUtils.getConnection();

			pst = conn
					.prepareStatement("SELECT c.classify_id,c.classify_title,c.classify_content,c.menu_id,m.menu_id,m.menu_name,m.model_id FROMt_classify AS c ,t_menu AS m WHERE c.menu_id = m.model_id");

			res = pst.executeQuery();

			while (res.next()) {
				classify = new Classify();
				classify.setClassifyId(res.getInt("classify_Id"));
				classify.setClassifyTitle(res.getString("classify_title"));
				classify.setClassifyContent(res.getString("classify_content"));
				Menu menu = new Menu();
				menu.setMenuId(res.getInt("menu_id"));
				menu.setMenuName(res.getString("menu_name"));
				menu.setModel(null);
				classify.setMenu(menu);
			}

		} finally {
			DataBaseUtils.close(conn, pst, res);
		}

		return classifys;
	}

	public List<Classify> listAllClassify(int page, int rows)
			throws SQLException {

		Connection conn = null;
		PreparedStatement pst = null;
		ResultSet res = null;
		List<Classify> classifys = new ArrayList<Classify>();
		try {
			// 連接數據庫
			conn = DataBaseUtils.getConnection();
			// 創建sql執行器
			pst = conn
					.prepareStatement("SELECT c.classify_id,c.classify_title,c.classify_content,c.menu_id,m.menu_id,m.menu_name,m.model_id FROMt_classify AS c ,t_menu AS m WHERE c.menu_id = m.model_id");
			pst.setInt(1, (page - 1) * rows);
			pst.setInt(2, rows);
			// 執行sql語句
			res = pst.executeQuery();

			while (res.next()) {

				Classify classify = new Classify();
				classify = new Classify();
				classify.setClassifyId(res.getInt("classify_Id"));
				classify.setClassifyTitle(res.getString("classify_title"));
				classify.setClassifyContent(res.getString("classify_content"));
				Menu menu = new Menu();
				menu.setMenuId(res.getInt("menu_id"));
				menu.setMenuName(res.getString("menu_name"));
				menu.setModel(null);
				classify.setMenu(menu);
				classifys.add(classify);
			}
		} finally {
			DataBaseUtils.close(conn, pst, res);
		}
		return classifys;
	}

	public int getCount() throws SQLException {

		Connection conn = null;
		PreparedStatement pst = null;
		ResultSet res = null;
		int count = -1;

		conn = DataBaseUtils.getConnection();
		pst = conn.prepareStatement("select count(0) as count from t_classify");
		res = pst.executeQuery();

		res.next();
		count = res.getInt(1);
		return count;
	}

}


連接數據庫信息:

package com.orange.common;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DataBaseUtils {

	public static Connection getConnection() throws SQLException {
		try {
		
			Class.forName("com.mysql.jdbc.Driver");
			
			Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/threegorgessouldb", "root", "123456");
			
			return conn;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			throw new SQLException("沒有找到驅動包");
		}
	}
	
	public static void close(Connection conn, PreparedStatement pst, ResultSet res) throws SQLException {
		if(res != null) {
			res.close();
		}
		if(pst != null) {
			pst.close();
		}
		if(conn != null) {
			conn.close();
		}
	}
	
	public static void executeUpdate(String sql, Object[] params) throws SQLException {
		Connection conn = null;
		PreparedStatement pst = null;
		
		try {
			conn = DataBaseUtils.getConnection();
			
			pst = conn.prepareStatement(sql);
			
			for(int i=0;i<params.length;i++) {
				pst.setObject(i + 1, params[i]);
			}			
			pst.executeUpdate();
			
			System.out.println(sql);
		} finally {
			DataBaseUtils.close(conn, pst, null);
		}
	}
}

 index.jsp  

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'left.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
   
  <body>
      <a href="ClassifyAction!listToMenuId?menuId=11000">三峽簡介</a><br>
      <a href="ClassifyAction!listToMenuId?menuId=21000">三峽文化</a><br>
      <a href="ClassifyAction!listToMenuId?menuId=31000">三峽精神</a><br>
      <a href="ClassifyAction!listToMenuId?menuId=41000">三峽景點</a><br>
  </body>
</html>


update.jsp

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
	<script type="text/javascript" src="ckfinder/ckfinder.js"></script>
	
  </head>
  
  <body>
  
     <form  id="form1" name="form1" action="ClassifyAction!updateClassify" method="post" > 
            <input type="hidden" name="classify.classifyId"  value="${classify.classifyId }"/> 
            <input type="hidden" name="classify.classifyTitle" value="${classify.classifyTitle }" />
            <input type="hidden" name="menuId" value="${classify.menu.menuId }" />
            <table width="650" height="450" border="0" align="center">               
                <tr>  
                    <td valign="top">  
                        內容:  
                    </td>  
                    <td>  
                        <textarea id="editor1" name="editor1" class="ckeditor"><p>${classify.classifyContent}. </p></textarea>  
                        <script type="text/javascript">  
                            CKEDITOR.replace( 'editor1' );  
                        </script>  
                    </td>  
                </tr>  
                <tr>  
                    <td></td>  
                    <td>  
                        <input type="submit" name="Submit" value="提交" />  
                        <input type="reset" name="Reset" value="重置" />  
                    </td>  
                </tr>  
            </table>  
        </form>  
  </body>
</html>


第五步:

          因爲struts2攔截器會攔截所有以"/"開頭的URL,CKEd的servlet攔截器攔截所有以"
/ckfinder/core/connector/java/connector.java"開頭的URL.當時CKEditor上傳圖片的時 候,URL中包含有"/"(指網站根目錄),優先被struts2的攔截器攔截,這樣上傳的URL請求就不會轉發到CKEditor的servlet中, 所有上傳圖片也就不會成功.
 
   解決步驟:
  
第一個辦法(最簡單):是將struts2的攔截器"/*"改成"#.action"或者"*.do",可以這樣改
  
<filter-mapping>  
        <filter-name>struts2</filter-name>  
        <url-pattern>*.action</url-pattern>  
</filter-mapping>  
 
第二個辦法是:
自己來定義一個CKeditor的過濾器,讓它來繼承Struts2的過濾器FilterDispatcher,其完整代碼是
package com.orange.web.filter;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.dispatcher.FilterDispatcher;

@SuppressWarnings("deprecation")  
public class FCKFilter extends FilterDispatcher {  
     public void doFilter(ServletRequest req,ServletResponse res, FilterChain chain) throws IOException, ServletException {     
            HttpServletRequest request = (HttpServletRequest) req;    
            String URI = request.getRequestURI();   
            String[] uriArray = URI.split("/ckfinder/core/connector/java/*/");   
            int arrayLen = uriArray.length;   
            if (arrayLen >= 2) {   
                chain.doFilter(req, res);    
            }else {   
                super.doFilter(req, res, chain);     
            }   
        }    
 } 
第六步:運行測試
       



示例下載地址:http://download.csdn.net/detail/lin062854/7116033

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章