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下:

struts2+ckeditor+ckfinder实现文件的上传、从数据库获取数据、修改并提交到数据库中保存_第1张图片

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

       编辑WEB-INF\web.xml

 




  
    struts2
    
    com.orange.web.filter.FCKFilter
  
  
    struts2
    /*
  
  
    /index.jsp
  

 

        解压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根目录下,目录结构如下图:

struts2+ckeditor+ckfinder实现文件的上传、从数据库获取数据、修改并提交到数据库中保存_第2张图片

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

       配置config.xml文件:



	
	true

	
	/ThreeGorgesSoulSystem/upload/
	
	
	
	true
	
	
	true
	

	
	
		
			%BASE_URL%files/
			%BASE_DIR%files
			0
			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
			
			
		
		
			%BASE_URL%images/
			%BASE_DIR%images
			0
			bmp,gif,jpeg,jpg,png
			
		
		
			%BASE_URL%flash/
			%BASE_DIR%flash
			0
			swf,flv
			
		
	
	
	
	
		
			*
			*
			/
			true
			true
			true
			true
			true
			true
			true
			true
		
	
	
		true
		%BASE_URL%_thumbs/
		%BASE_DIR%_thumbs
		false
		100
		100
		80
	
	
	
	
	
		
			imageresize
			com.ckfinder.connector.plugins.ImageResize
			
				
				
				
			
		
		
			fileeditor
			com.ckfinder.connector.plugins.FileEditor
			
		
	
	com.ckfinder.connector.configuration.ConfigurationPathBuilder

	

 

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




  
    struts2
    
    com.orange.web.filter.FCKFilter
  
  
    struts2
    /*
  

 
   
   		
		ConnectorServlet
		
		com.ckfinder.connector.ConnectorServlet
		
			
			XMLConfig
			/WEB-INF/config.xml
		
		
			
			debug
			false
		
		
		
		1
	
	
	
	
	
		ConnectorServlet
		
			/ckfinder/core/connector/java/connector.java
		
	


  
  
    /index.jsp
  


 

注:1.将ckfinder中的_samples文件夹直接删除

         2.如果jquery.min.js出错,是因为采用了压缩的jquery库,不被识别,在http://jquery.com/download/下载

struts2+ckeditor+ckfinder实现文件的上传、从数据库获取数据、修改并提交到数据库中保存_第3张图片

       点击链接,把jQuery2.0.2中的代码直接替换项目中jquery.min.js中的代码

   struts2+ckeditor+ckfinder实现文件的上传、从数据库获取数据、修改并提交到数据库中保存_第4张图片

 

第四步: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 listAllClassify() throws SQLException {
		return classifyDao.listAllClassify();
	}

	/**
	 * 查询从page条数据开始,总控查询rows条记录
	 * 
	 * @param page
	 * @param rows
	 * @return
	 * @throws SQLException
	 */
	public List 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 listAllClassify() throws SQLException {

		List classifys = new LinkedList();
		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 listAllClassify(int page, int rows)
			throws SQLException {

		Connection conn = null;
		PreparedStatement pst = null;
		ResultSet res = null;
		List classifys = new ArrayList();
		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

 index.jsp  

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



  
    
    
    My JSP 'left.jsp' starting page
    
	
	
	    
	
	
	

  
   
  
      三峡简介
三峡文化
三峡精神
三峡景点


update.jsp

 

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



  
    
    
    My JSP 'index.jsp' starting page
	
	
	    
	
	
	
	
	
	
  
  
  
  
     
内容:


第五步:

            因为struts2拦截器会拦截所有以"/"开头的URL,CKEd的servlet拦截器拦截所有以"
/ckfinder/core/connector/java/connector.java"开头的URL.当时CKEditor上传图片的时 候,URL中包含有"/"(指网站根目录),优先被struts2的拦截器拦截,这样上传的URL请求就不会转发到CKEditor的servlet中, 所有上传图片也就不会成功.
 
   解决步骤:
  
第一个办法(最简单):是将struts2的拦截器"/*"改成"#.action"或者"*.do",可以这样改
  
  
        struts2  
        *.action  
  
 
第二个办法是:
自己来定义一个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);     
            }   
        }    
 } 
第六步:运行测试
        struts2+ckeditor+ckfinder实现文件的上传、从数据库获取数据、修改并提交到数据库中保存_第5张图片 struts2+ckeditor+ckfinder实现文件的上传、从数据库获取数据、修改并提交到数据库中保存_第6张图片



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

 

你可能感兴趣的:(文件上传,数据库交互,struts框架)