mybatis+springMVC操做存取blob

基於springMVC+mybatis+xheditor存取內容,圖片上傳功能暫時沒作,參考:javascript

http://my.oschina.net/uniquejava/blog/88321?p=1php

1、Content實體類:css

 

import java.io.Serializable;
import java.sql.Blob;
import java.util.Date;



public class Content implements Serializable{

    private static final long serialVersionUID = 1L;
    private String id ;
    private String org ;//來源
    private String title ;//標題
    public Blob content;//內容
    private Date publishDate;//發佈時間
 
    //getter/setter省略

}

mysql 數據庫設計:html

CREATE TABLE `content` (
  `id` varchar(100) NOT NULL COMMENT '主鍵id',
  `org` varchar(100) DEFAULT NULL COMMENT '來源',
  `title` varchar(100) DEFAULT NULL COMMENT '文章標題',
  `content` blob NOT NULL COMMENT '內容',
  `publish_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '發佈時間',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

2、contentDao:
   html5

import java.util.Map;



public interface ContentDao {
    
    //保存內容
    public void saveContent(Map<String, Object> map);
    //查詢內容
    public Map<String, Object> findContents(String id);

}

ContentMapper.xml:java

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC   
    "-//mybatis.org//DTD Mapper 3.3//EN"  
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
    
    <mapper namespace="com.wa.xwolf.sblog.dao.ContentDao">
      <insert id="saveContent"  parameterType="java.util.Map" statementType="PREPARED" >
     insert into content  (id,org,title,content,publish_date) values (#{id},#{org},#{title},#{content,jdbcType=BLOB},#{publishDate})
      </insert>
      
      <select id="findContents" parameterType="java.lang.String"    resultType="java.util.Map" statementType="PREPARED" >
       select content from content where id=#{id}
      </select>
     
    </mapper>

3、controller:mysql

package com.wa.xwolf.sblog.controller;

import java.io.IOException;
import java.io.Writer;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.rowset.serial.SerialBlob;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;





import com.alibaba.fastjson.JSONObject;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.wa.xwolf.sblog.dao.ContentDao;
import com.wa.xwolf.sblog.util.CommonUtils;
import com.wa.xwolf.sblog.util.UUIDUtils;

/**
 * 整合xheditor測試案例
 *
 */
@Controller
public class XheditorController {
    
    private Logger log = Logger.getLogger(XheditorController.class);
    @Autowired
      ContentDao contentDao;
    
    @RequestMapping("/xheditor")
    public String toBlog(){
        return "editor/xheditor";
    }
    /**
     * xheditor上傳圖片
     * @param request
     * @param response
     * @param writer
     */
    @RequestMapping("/upload")
    public void uploadImage(@RequestParam("filedata") MultipartFile file,HttpServletRequest request,HttpServletResponse response,
            Writer writer){
        //String fileName = file.getOriginalFilename();
        
    }
    /**
     * 保存內容
     * @param request
     * @param response
     * @param writer
     */
    @RequestMapping("/saveContent")
    public void save(HttpServletRequest request,HttpServletResponse response,Writer writer) {
        String title = request.getParameter("title");
        String org = request.getParameter("org");
        String content = request.getParameter("content");
        java.sql.Blob blob=null;
        JSONObject object = new JSONObject();
        try {
            blob = new SerialBlob(content.getBytes());
            
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("id",UUIDUtils.getLowerCase());
            map.put("title",title);
            map.put("org", org);
            map.put("content",blob);
            map.put("publishDate", new Date());
            contentDao.saveContent(map);
            object.put("result", true);
            object.put("msg","保存成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(new Date()+"內容保存失敗,error Message ="+e.getMessage());
            object.put("result", false);
            object.put("msg","保存失敗");
        } finally{
            try {
                writer.write(object.toJSONString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
    }
    /**
     * 列出內容信息
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/listContent")
    public ModelAndView toList
         (HttpServletRequest request,HttpServletResponse response,Model model){
        ModelAndView view = new ModelAndView();
        Map<String, Object > map = contentDao.findContents("0cfe4a5b991743fea7e18df94c871d48");
        //以byte[] 方式取出blog類型的數據 
        String list = new String((byte[])map.get("content"));
        model.addAttribute("content",list);
        view.setViewName("editor/content_list");
        return view;
    }

}

jsp頁面:jquery

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>xheditor整合案例</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.4.3.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/xheditor/xheditor-1.2.1.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/xheditor/xheditor_lang/zh-cn.js"></script>

<style type="text/css">
   /* 增長插入代碼工具圖標 */
  .btnCode {
    background: transparent url(images/code.gif) no-repeat 0px 0px;
    background-position: 3px -2px;
  }
</style>
<script type="text/javascript">
  
   $(function(){
       /*
       加入擴展的插入代碼的 功能 
       */
       var plugins={
                Code:{c:'btnCode',t:'插入代碼',h:1,e:function(){
                  var _this=this;
                  var htmlCode="<div>編程語言<select id='xheCodeType'>";
                    htmlCode+="<option value='html'>HTML/XML</option>";
                    htmlCode+="<option value='js'>Javascript</option>";
                    htmlCode+="<option value='css'>CSS</option>";
                    htmlCode+="<option value='php'>PHP</option>";
                    htmlCode+="<option value='java'>Java</option>";
                    htmlCode+="<option value='py'>Python</option>";
                    htmlCode+="<option value='pl'>Perl</option>";
                    htmlCode+="<option value='rb'>Ruby</option>";
                    htmlCode+="<option value='cs'>C#</option>";
                    htmlCode+="<option value='c'>C++/C</option>";
                    htmlCode+="<option value='vb'>VB/ASP</option>";
                    htmlCode+="<option value=''>其它</option>";
                    htmlCode+="</select></div><div>";
                    htmlCode+="<textarea id='xheCodeValue' wrap='soft' spellcheck='false' style='width:300px;height:100px;' />";
                    htmlCode+="</div><div style='text-align:right;'><input type='button' id='xheSave' value='肯定' /></div>";            
                  var jCode=$(htmlCode),jType=$('#xheCodeType',jCode),jValue=$('#xheCodeValue',jCode),jSave=$('#xheSave',jCode);
                  jSave.click(function(){
                    _this.loadBookmark();
                    _this.pasteHTML('<pre class="brush: '+jType.val()+'">'+_this.domEncode(jValue.val())+'</pre> ');
                    _this.hidePanel();
                    return false;    
                  });
                  _this.saveBookmark();
                  _this.showDialog(jCode);
                }},
                  
                  };
                  $('#content').xheditor({
                  plugins:plugins,//使用咱們定義的插件  
                  tools : 'full',
                   width:980,
                   height:450,
                    skin : 'default',
                    upImgUrl : "${pageContext.request.contextPath}/upload.htm",
                    upImgExt : "jpg,jpeg,png,gif",
                    html5Upload : false,
                    //上傳圖片的配置 
                    onUpload : upload,
                  loadCSS:'<style>pre{margin-left:2em;border-left:3px solid #CCC;padding:0 1em;}</style>',
                  });
       
      
       //回調函數 
       function upload(data){
           
       }
       
   });
    
   
   function save(){
       
       $.post("${pageContext.request.contextPath}/saveContent.htm",
               {"org":$("#org").val,
                 "content":$("#content").val,
                 "title":$("#title").val},
               function(data){
                   alert(data);
               },
               "json");
       
   }


</script>

</head>
<body>


 
<form action="${pageContext.request.contextPath}/saveContent.htm" method="post">
  
  <table>
    
    <tr>
     <td>來源:</td>
     <td><input id="org" name="org" ></td>
    </tr>
    
    <tr>
     
     <td>標題:</td>
     
     <td><input id="title" name="title"></td>
    
    </tr>
  
  </table>
   
    <textarea id="content" name="content"></textarea>
    
     <input type="submit" value="發佈" > 
    
      </form>
</body>
</html>

相關文章
相關標籤/搜索