【代碼總結-不按期更新】

  1 package com.runyi.share.service.information.commons.exceptions;
  2 
  3 import com.runyi.ryplat.api.exceptions.BusinessException;
  4 
  5 public class InfoBackStageException extends BusinessException{
  6 
  7     /**
  8      * 
  9      */
 10     private static final long serialVersionUID = 6854801395723117773L;
 11 
 12     public InfoBackStageException(String code,String msg){
 13         super(msg);
 14         super.setCode(code);
 15         super.setType("IM");
 16         super.setData(msg);
 17     }
 18     public InfoBackStageException(TYPE type){
 19         super(type.getDesc());
 20         super.setCode(type.getCode());
 21         super.setType("IM");
 22         super.setData(type.getDesc());
 23     }
 24     /**
 25      * 代碼定義規則
 26      * 例:WBPD001
 27      * WB(0,2):應用代碼已定請諮詢模塊負責人;
 28      * PD(2,4):業務模塊代碼,
 29      * 001(4,7):序號
 30      * 本項應用應用代碼爲:PL
 31      */
 32     public enum TYPE {
 33         IMSM001 ("IMSM001","系統錯誤"),
 34         
 35         IMSM002 ("IMSM002","綜合價格指數id不能爲空"),
 36         IMSM003 ("IMSM003","指數值不能爲空"),
 37         IMSM004 ("IMSM004","漲跌不能爲空"),
 38         IMSM005 ("IMSM005","指很多天期不能爲空"),
 39         IMSM006 ("IMSM006","指數行業代碼不能爲空"),
 40         IMSM007 ("IMSM007","指數行業名稱不能爲空"),
 41         IMSM008 ("IMSM008","指數分類代碼不能爲空"),
 42         IMSM009 ("IMSM009","指數分類名稱不能爲空"),
 43         IMSM010 ("IMSM010","該指數模板已經存在"),
 44         
 45         IMSM011 ("IMSM011","絕對價格指數id不能爲空"),
 46         IMSM012 ("IMSM012","品種代碼不能爲空"),
 47         IMSM013 ("IMSM013","品種名稱值不能爲空"),
 48         
 49         IMSM020 ("IMSM020","基準價id不能爲空"),
 50         IMSM021 ("IMSM021","基準價行業名稱不能爲空"),        
 51         IMSM022 ("IMSM022","基準價產地不能爲空"),
 52         IMSM023 ("IMSM023","基準價行業代碼不能爲空"),
 53         IMSM024 ("IMSM024","基準價代碼不能爲空"),
 54         IMSM026 ("IMSM026","基準價平均價不能爲空"),
 55         
 56         IMSM027 ("IMSM027","基價模板_行業名不能爲空"),
 57         IMSM028 ("IMSM028","基價模板_基價名不能爲空"),
 58         IMSM029 ("IMSM029","該基價模板已經存在"),
 59         
 60         SOSM030 ("SOSM030","頻道名稱不能爲空"),
 61         SOSM031 ("SOSM031","主頻道名稱不能爲空"),
 62         SOSM032 ("SOSM032","頻道主鍵不能爲空"),
 63         SOSM033 ("SOSM033","主頻道主鍵不能爲空"),
 64         SOSM034 ("SOSM034","主頻道代碼不能爲空"),
 65         SOSM035 ("SOSM035","頻道代碼不能爲空"),
 66         SOSM036 ("SOSM036","此頻道已存在不能添加"),
 67         SOSM037 ("SOSM037","此頻道代碼已存在不能添加"),
 68         SOSM038 ("SOSM038","此主頻道代碼已存在不能添加"),
 69         SOSM039 ("SOSM039","此主頻道名稱已存在不能添加"),
 70         
 71         SOSM040 ("SOSM040","主鍵不能爲空"),
 72         
 73         SOSM050 ("SOSM050","用戶已將資訊撤回"),
 74         SOSM051 ("SOSM051","只有草稿狀態才能保存"),
 75         SOSM052 ("SOSM052","只有審覈狀態才能審覈經過"),
 76         
 77         SOSM060 ("SOSM060","此規則已存在不能添加"),
 78         
 79         SOSM070 ("SOSM070","回覆id不能爲空"),
 80         SOSM071 ("SOSM071","回覆關聯的評論id不爲空"),
 81         SOSM072 ("SOSM072","回覆內容不能爲空"),
 82         
 83         SOSM080 ("SOSM080","資訊發佈上限已保存到草稿箱"),
 84         
 85         SOSM081 ("SOSM081","標籤名稱已經存在"),
 86         SOSM082 ("SOSM082","標籤主鍵爲空"),
 87         SOSM083 ("SOSM083","標籤名稱不能爲空"),
 88         SOSM084 ("SOSM084","專欄主鍵爲空"),
 89         SOSM085 ("SOSM085","專欄標題已經存在"),
 90         SOSM086 ("SOSM086","專欄標題爲空"),
 91         SOSM087 ("SOSM087","圖片主鍵爲空"),
 92         
 93         
 94         SOSM090 ("SOS090","該條資訊已刪除"),
 95         SOSM091 ("SOS091","打賞主鍵不存在"),
 96         
 97         SOSM092 ("SOSM092","投訴類型主鍵爲空"),
 98         SOSM093 ("SOSM093","投訴類型名稱爲空"),
 99         SOSM094 ("SOSM094","該投訴類型已經存在"),
100         
101         SOSM100 ("SOSM100","專欄不存在或已過時"),
102         SOSM101 ("SOSM101","未訂閱不能查看"),
103         
104         SOSM102 ("SOSM102","已存在專欄"),
105         
106         SOSM103 ("SOSM103","專欄狀態異常不能結算"),
107         
108         SOSM104 ("SOSM104","數據庫異常"),
109         
110         SOSM105 ("SOSM104","專題已存在"),
111 
112         ;
113         private String code;
114         private String desc;
115         TYPE(String code,String desc) {
116             this.code = code;
117             this.desc = desc;
118         }
119         public String getCode() {
120             return this.code;
121         }
122         public String getDesc() {
123             return this.desc;
124         }
125     }
126     
127 }
枚舉值1
 1 //讀取配置文件
 2 public class PropertiesUtil {
 3 
 4     private static Properties properties = new Properties();
 5     static {
 6         InputStream in = PropertiesUtil.class.getResourceAsStream("/config.properties");
 7         try {
 8             properties.load(in); 
 9         } catch (IOException e) {
10             e.printStackTrace();
11         }
12     }
13     public static String get(String key) {  
14         String value = properties.getProperty(key);
15         if(value != null){
16             value = value.trim();
17         }
18         return value;
19     }  
20   
21 }
讀取配置文件
 1 package org.seckill.enums;
 2 
 3 /**
 4  * 使用枚舉標識常量數據:
 5  * 數據字典放到枚舉當中
 6  */
 7 public enum SeckillStatEnum {
 8     SUCCESS(1,"秒殺成功"),
 9     END(0,"秒殺結束"),
10     REPEAT_KILL(-1,"重複秒殺"),
11     INNER_ORROR(-2,"系統異常"),
12     DATA_REWRITE(-3,"數據篡改");
13     private int state;
14     private String stateInfo;
15 
16     
17     
18     SeckillStatEnum(int state, String stateInfo) {
19         this.state = state;
20         this.stateInfo = stateInfo;
21     }
22 
23     public int getState() {
24         return state;
25     }
26 
27     public void setState(int state) {
28         this.state = state;
29     }
30 
31     public String getStateInfo() {
32         return stateInfo;
33     }
34 
35     public void setStateInfo(String stateInfo) {
36         this.stateInfo = stateInfo;
37     }
38 
39     public static  SeckillStatEnum stateOf(int index){
40         //枚舉內部的values()方法用於拿到全部的類型
41         for(SeckillStatEnum state: values()){
42             if(state.getState()==index){
43                 return state;
44             }
45         }
46         return  null;
47     }
48 
49 }
枚舉值2
  1 package com.yhb.jsxn.servlet;
  2 //中文simplecaptcha
  3 import java.awt.Color;
  4 import java.awt.Font;
  5 import java.awt.Graphics;
  6 import java.awt.Graphics2D;
  7 import java.awt.image.BufferedImage;
  8 import java.io.IOException;
  9 import java.util.Random;
 10 
 11 import javax.imageio.ImageIO;
 12 import javax.servlet.ServletException;
 13 import javax.servlet.ServletOutputStream;
 14 import javax.servlet.http.HttpServlet;
 15 import javax.servlet.http.HttpServletRequest;
 16 import javax.servlet.http.HttpServletResponse;
 17 
 18 import org.apache.commons.io.output.ByteArrayOutputStream;
 19 import org.springframework.beans.factory.BeanFactoryUtils;
 20 import org.springframework.web.context.WebApplicationContext;
 21 import org.springframework.web.context.support.WebApplicationContextUtils;
 22 
 23 import com.octo.captcha.service.CaptchaServiceException;
 24 import com.octo.captcha.service.image.ImageCaptchaService;
 25 
 26 
 27 /**
 28  * 提供驗證碼圖片的Servlet
 29  */
 30 @SuppressWarnings("serial")
 31 public class JcaptchaServlet3 extends HttpServlet {
 32     public static final String CAPTCHA_IMAGE_FORMAT = "jpeg";
 33     public static final int WIDTH = 120;
 34     public static final int HEIGHT = 30;
 35     private ImageCaptchaService captchaService;
 36 
 37     @Override
 38     public void init() throws ServletException {
 39         WebApplicationContext appCtx = WebApplicationContextUtils
 40                 .getWebApplicationContext(getServletContext());
 41         captchaService = (ImageCaptchaService) BeanFactoryUtils
 42                 .beanOfTypeIncludingAncestors(appCtx, ImageCaptchaService.class);
 43         
 44     }
 45 
 46     @Override
 47     protected void doGet(HttpServletRequest request,
 48             HttpServletResponse response) throws ServletException, IOException {
 49         byte[] captchaChallengeAsJpeg = null;
 50         // the output stream to render the captcha image as jpeg into
 51         ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
 52         try {
 53             // get the session id that will identify the generated captcha.
 54             // the same id must be used to validate the response, the session id
 55             // is a good candidate!
 56 
 57             String captchaId = request.getSession().getId();
 58             BufferedImage challenge = captchaService.getImageChallengeForID(
 59                     captchaId, request.getLocale());
 60             
 61             // Jimi.putImage("image/jpeg", challenge, jpegOutputStream);
 62              request.setCharacterEncoding("utf-8");
 63              response.setContentType("text/html;charset=utf-8");
 64                 // 建立緩存
 65                 BufferedImage bi = new BufferedImage(WIDTH, HEIGHT,
 66                         BufferedImage.TYPE_INT_RGB);
 67                 // 得到畫布
 68                 Graphics g = bi.getGraphics();
 69                 // 設置背影色
 70                 setBackGround(g);
 71                 // 設置邊框
 72                 setBorder(g);
 73                 // 畫干擾線
 74                 drawRandomLine(g);
 75                 // 寫隨機數
 76                 String random = drawRandomNum((Graphics2D) g);
 77                 // 將隨機漢字存在session中
 78                 request.getSession().setAttribute("checkcode", random);
 79                 // 將圖形寫給瀏覽器
 80                 response.setContentType("image/jpeg");
 81                 // 發頭控制瀏覽器不要緩存
 82                 response.setDateHeader("expries", -1);
 83                 response.setHeader("Cache-Control", "no-cache");
 84                 response.setHeader("Pragma", "no-cache");
 85                 ImageIO.write(bi, CAPTCHA_IMAGE_FORMAT, jpegOutputStream);
 86             
 87             
 88             //ImageIO.write(challenge, CAPTCHA_IMAGE_FORMAT, jpegOutputStream);
 89         } catch (IllegalArgumentException e) {
 90             response.sendError(HttpServletResponse.SC_NOT_FOUND);
 91             return;
 92         } catch (CaptchaServiceException e) {
 93             response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
 94             return;
 95         }
 96         // catch (JimiException e) {
 97         // response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
 98         // return;
 99         // }
100 
101         captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
102 
103         // flush it in the response
104         response.setHeader("Cache-Control", "no-store");
105         response.setHeader("Pragma", "no-cache");
106         response.setDateHeader("Expires", 0);
107         response.setContentType("image/" + CAPTCHA_IMAGE_FORMAT);
108 
109         ServletOutputStream responseOutputStream = response.getOutputStream();
110         responseOutputStream.write(captchaChallengeAsJpeg);
111         responseOutputStream.flush();
112         responseOutputStream.close();
113     }
114     /**
115      * 設置背景色
116      * 
117      * @param g
118      */
119     private void setBackGround(Graphics g) {
120         // 設置顏色
121         g.setColor(Color.WHITE);
122         // 填充區域
123         g.fillRect(0, 0, WIDTH, HEIGHT);
124     }
125     /**
126      * 設置邊框
127      * 
128      * @param g
129      */
130     private void setBorder(Graphics g) {
131         // 設置邊框顏色
132         g.setColor(Color.BLUE);
133         // 邊框區域
134         g.drawRect(1, 1, WIDTH - 2, HEIGHT - 2);
135     }
136     /**
137      * 畫隨機線條
138      * 
139      * @param g
140      */
141     private void drawRandomLine(Graphics g) {
142         // 設置顏色
143         g.setColor(Color.GREEN);
144         // 設置線條個數並畫線
145         for (int i = 0; i < 5; i++) {
146             int x1 = new Random().nextInt(WIDTH);
147             int y1 = new Random().nextInt(HEIGHT);
148             int x2 = new Random().nextInt(WIDTH);
149             int y2 = new Random().nextInt(HEIGHT);
150             g.drawLine(x1, y1, x2, y2);
151         }
152     }
153     /**
154      * 畫隨機漢字
155      * 
156      * @param g
157      * @return
158      */
159     private String drawRandomNum(Graphics2D g) {
160         StringBuffer sb = new StringBuffer();
161         // 設置顏色
162         g.setColor(Color.RED);
163         // 設置字體
164         g.setFont(new Font("宋體", Font.BOLD, 20));
165         // 準備經常使用漢字集
166         String base = "\u7684\u4e00\u4e86\u662f\u6211\u4e0d\u5728\u4eba\u4eec\u6709\u6765\u4ed6\u8fd9\u4e0a\u7740\u4e2a\u5730\u5230\u5927\u91cc\u8bf4\u5c31\u53bb\u5b50\u5f97\u4e5f\u548c\u90a3\u8981\u4e0b\u770b\u5929\u65f6\u8fc7\u51fa\u5c0f\u4e48\u8d77\u4f60\u90fd\u628a\u597d\u8fd8\u591a\u6ca1\u4e3a\u53c8\u53ef\u5bb6\u5b66\u53ea\u4ee5\u4e3b\u4f1a\u6837\u5e74\u60f3\u751f\u540c\u8001\u4e2d\u5341\u4ece\u81ea\u9762\u524d\u5934\u9053\u5b83\u540e\u7136\u8d70\u5f88\u50cf\u89c1\u4e24\u7528\u5979\u56fd\u52a8\u8fdb\u6210\u56de\u4ec0\u8fb9\u4f5c\u5bf9\u5f00\u800c\u5df1\u4e9b\u73b0\u5c71\u6c11\u5019\u7ecf\u53d1\u5de5\u5411\u4e8b\u547d\u7ed9\u957f\u6c34\u51e0\u4e49\u4e09\u58f0\u4e8e\u9ad8\u624b\u77e5\u7406\u773c\u5fd7\u70b9\u5fc3\u6218\u4e8c\u95ee\u4f46\u8eab\u65b9\u5b9e\u5403\u505a\u53eb\u5f53\u4f4f\u542c\u9769\u6253\u5462\u771f\u5168\u624d\u56db\u5df2\u6240\u654c\u4e4b\u6700\u5149\u4ea7\u60c5\u8def\u5206\u603b\u6761\u767d\u8bdd\u4e1c\u5e2d\u6b21\u4eb2\u5982\u88ab\u82b1\u53e3\u653e\u513f\u5e38\u6c14\u4e94\u7b2c\u4f7f\u5199\u519b\u5427\u6587\u8fd0\u518d\u679c\u600e\u5b9a\u8bb8\u5feb\u660e\u884c\u56e0\u522b\u98de\u5916\u6811\u7269\u6d3b\u90e8\u95e8\u65e0\u5f80\u8239\u671b\u65b0\u5e26\u961f\u5148\u529b\u5b8c\u5374\u7ad9\u4ee3\u5458\u673a\u66f4\u4e5d\u60a8\u6bcf\u98ce\u7ea7\u8ddf\u7b11\u554a\u5b69\u4e07\u5c11\u76f4\u610f\u591c\u6bd4\u9636\u8fde\u8f66\u91cd\u4fbf\u6597\u9a6c\u54ea\u5316\u592a\u6307\u53d8\u793e\u4f3c\u58eb\u8005\u5e72\u77f3\u6ee1\u65e5\u51b3\u767e\u539f\u62ff\u7fa4\u7a76\u5404\u516d\u672c\u601d\u89e3\u7acb\u6cb3\u6751\u516b\u96be\u65e9\u8bba\u5417\u6839\u5171\u8ba9\u76f8\u7814\u4eca\u5176\u4e66\u5750\u63a5\u5e94\u5173\u4fe1\u89c9\u6b65\u53cd\u5904\u8bb0\u5c06\u5343\u627e\u4e89\u9886\u6216\u5e08\u7ed3\u5757\u8dd1\u8c01\u8349\u8d8a\u5b57\u52a0\u811a\u7d27\u7231\u7b49\u4e60\u9635\u6015\u6708\u9752\u534a\u706b\u6cd5\u9898\u5efa\u8d76\u4f4d\u5531\u6d77\u4e03\u5973\u4efb\u4ef6\u611f\u51c6\u5f20\u56e2\u5c4b\u79bb\u8272\u8138\u7247\u79d1\u5012\u775b\u5229\u4e16\u521a\u4e14\u7531\u9001\u5207\u661f\u5bfc\u665a\u8868\u591f\u6574\u8ba4\u54cd\u96ea\u6d41\u672a\u573a\u8be5\u5e76\u5e95\u6df1\u523b\u5e73\u4f1f\u5fd9\u63d0\u786e\u8fd1\u4eae\u8f7b\u8bb2\u519c\u53e4\u9ed1\u544a\u754c\u62c9\u540d\u5440\u571f\u6e05\u9633\u7167\u529e\u53f2\u6539\u5386\u8f6c\u753b\u9020\u5634\u6b64\u6cbb\u5317\u5fc5\u670d\u96e8\u7a7f\u5185\u8bc6\u9a8c\u4f20\u4e1a\u83dc\u722c\u7761\u5174\u5f62\u91cf\u54b1\u89c2\u82e6\u4f53\u4f17\u901a\u51b2\u5408\u7834\u53cb\u5ea6\u672f\u996d\u516c\u65c1\u623f\u6781\u5357\u67aa\u8bfb\u6c99\u5c81\u7ebf\u91ce\u575a\u7a7a\u6536\u7b97\u81f3\u653f\u57ce\u52b3\u843d\u94b1\u7279\u56f4\u5f1f\u80dc\u6559\u70ed\u5c55\u5305\u6b4c\u7c7b\u6e10\u5f3a\u6570\u4e61\u547c\u6027\u97f3\u7b54\u54e5\u9645\u65e7\u795e\u5ea7\u7ae0\u5e2e\u5566\u53d7\u7cfb\u4ee4\u8df3\u975e\u4f55\u725b\u53d6\u5165\u5cb8\u6562\u6389\u5ffd\u79cd\u88c5\u9876\u6025\u6797\u505c\u606f\u53e5\u533a\u8863\u822c\u62a5\u53f6\u538b\u6162\u53d4\u80cc\u7ec6";
167         int x = 5;
168         // 控制字數
169         for (int i = 0; i < 4; i++) {
170             // 設置字體旋轉角度
171             int degree = new Random().nextInt() % 30;
172             // 截取漢字
173             String ch = base.charAt(new Random().nextInt(base.length())) + "";
174             sb.append(ch);
175             // 正向角度
176             g.rotate(degree * Math.PI / 180, x, 20);
177             g.drawString(ch, x, 20);
178             // 反向角度
179             g.rotate(-degree * Math.PI / 180, x, 20);
180             x += 30;
181         }
182         return sb.toString();
183     }
184 }
生成漢字的驗證碼
 1 package com.yhb.jsxn.servlet;
 2 
 3 import java.awt.image.BufferedImage;
 4 import java.io.IOException;
 5 
 6 import javax.imageio.ImageIO;
 7 import javax.servlet.ServletException;
 8 import javax.servlet.ServletOutputStream;
 9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 
13 import org.apache.commons.io.output.ByteArrayOutputStream;
14 import org.springframework.beans.factory.BeanFactoryUtils;
15 import org.springframework.web.context.WebApplicationContext;
16 import org.springframework.web.context.support.WebApplicationContextUtils;
17 
18 import com.octo.captcha.service.CaptchaServiceException;
19 import com.octo.captcha.service.image.ImageCaptchaService;
20 
21 
22 /**
23  * 提供驗證碼圖片的Servlet
24  */
25 @SuppressWarnings("serial")
26 public class JcaptchaServlet extends HttpServlet {
27     public static final String CAPTCHA_IMAGE_FORMAT = "jpeg";
28 
29     private ImageCaptchaService captchaService;
30 
31     @Override
32     public void init() throws ServletException {
33         WebApplicationContext appCtx = WebApplicationContextUtils
34                 .getWebApplicationContext(getServletContext());
35         captchaService = (ImageCaptchaService) BeanFactoryUtils
36                 .beanOfTypeIncludingAncestors(appCtx, ImageCaptchaService.class);
37         
38     }
39 
40     @Override
41     protected void doGet(HttpServletRequest request,
42             HttpServletResponse response) throws ServletException, IOException {
43         byte[] captchaChallengeAsJpeg = null;
44         // the output stream to render the captcha image as jpeg into
45         ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
46         try {
47             // get the session id that will identify the generated captcha.
48             // the same id must be used to validate the response, the session id
49             // is a good candidate!
50 
51             String captchaId = request.getSession().getId();
52             BufferedImage challenge = captchaService.getImageChallengeForID(
53                     captchaId, request.getLocale());
54             // Jimi.putImage("image/jpeg", challenge, jpegOutputStream);
55             ImageIO.write(challenge, CAPTCHA_IMAGE_FORMAT, jpegOutputStream);
56         } catch (IllegalArgumentException e) {
57             response.sendError(HttpServletResponse.SC_NOT_FOUND);
58             return;
59         } catch (CaptchaServiceException e) {
60             response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
61             return;
62         }
63         // catch (JimiException e) {
64         // response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
65         // return;
66         // }
67 
68         captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
69 
70         // flush it in the response
71         response.setHeader("Cache-Control", "no-store");
72         response.setHeader("Pragma", "no-cache");
73         response.setDateHeader("Expires", 0);
74         response.setContentType("image/" + CAPTCHA_IMAGE_FORMAT);
75 
76         ServletOutputStream responseOutputStream = response.getOutputStream();
77         responseOutputStream.write(captchaChallengeAsJpeg);
78         responseOutputStream.flush();
79         responseOutputStream.close();
80     }
81 }
隨機數驗證碼
  1 package test1;
  2 
  3 import java.awt.Color;
  4 import java.io.BufferedReader;
  5 import java.io.File;
  6 import java.io.FileOutputStream;
  7 import java.io.FileReader;
  8 import java.io.IOException;
  9 
 10 import com.lowagie.text.Document;
 11 import com.lowagie.text.DocumentException;
 12 import com.lowagie.text.Font;
 13 import com.lowagie.text.HeaderFooter;
 14 import com.lowagie.text.Image;
 15 import com.lowagie.text.PageSize;
 16 import com.lowagie.text.Paragraph;
 17 import com.lowagie.text.Phrase;
 18 import com.lowagie.text.Rectangle;
 19 import com.lowagie.text.pdf.BaseFont;
 20 import com.lowagie.text.pdf.PdfContentByte;
 21 import com.lowagie.text.pdf.PdfGState;
 22 import com.lowagie.text.pdf.PdfReader;
 23 import com.lowagie.text.pdf.PdfStamper;
 24 import com.lowagie.text.pdf.PdfWriter;
 25 
 26 public class PdfConvertor {
 27 
 28 // txt原始文件的路徑
 29 private static final String txtFilePath = "c:/test/01.txt";
 30 //生成的pdf文件路徑
 31 private static final String pdfFilePath = "c:/test/01.pdf";
 32 //添加水印圖片路徑
 33 private static final String imageFilePath = "c:/test/images/psue.jpg";
 34 //生成臨時文件前綴
 35 private static final String prefix = "tempFile";
 36 //全部者密碼
 37 private static final String OWNERPASSWORD = "123456";
 38 
 39 
 40 public static void generatePDFWithTxt(String txtFile, String pdfFile,
 41 String userPassWord, String waterMarkName, int permission) {
 42 try {
 43 // 生成臨時文件
 44 File file = File.createTempFile(prefix, ".pdf");
 45 // 建立pdf文件到臨時文件
 46 if (createPDFFile(txtFile, file)) {
 47 // 增長水印和加密
 48 waterMark(file.getPath(), pdfFile, userPassWord, OWNERPASSWORD,
 49 waterMarkName, permission);
 50 }
 51 } catch (Exception e) {
 52 e.printStackTrace();
 53 }
 54 }
 55 
 56 
 57 private static boolean createPDFFile(String txtFilePath, File file) {
 58 // 設置紙張
 59 Rectangle rect = new Rectangle(PageSize.A4);
 60 // 設置頁碼
 61 HeaderFooter footer = new HeaderFooter(new Phrase("頁碼:", PdfConvertor
 62 .setChineseFont()), true);
 63 footer.setBorder(Rectangle.NO_BORDER);
 64 // step1
 65 Document doc = new Document(rect, 50, 50, 50, 50);
 66 doc.setFooter(footer);
 67 try {
 68 FileReader fileRead = new FileReader(txtFilePath);
 69 BufferedReader read = new BufferedReader(fileRead);
 70 // 設置pdf文件生成路徑 step2
 71 PdfWriter.getInstance(doc, new FileOutputStream(file));
 72 // 打開pdf文件 step3
 73 doc.open();
 74 // 實例化Paragraph 獲取寫入pdf文件的內容,調用支持中文的方法.step4
 75 while (read.ready()) {
 76 // 添加內容到pdf(這裏將會按照txt文件的原始樣式輸出)
 77 doc.add(new Paragraph(read.readLine(), PdfConvertor
 78 .setChineseFont()));
 79 }
 80 // 關閉pdf文件 step5
 81 doc.close();
 82 return true;
 83 } catch (Exception e) {
 84 e.printStackTrace();
 85 return false;
 86 }
 87 }
 88 
 89 
 90 private static void waterMark(String inputFile, String outputFile,
 91 String userPassWord, String ownerPassWord, String waterMarkName,
 92 int permission) {
 93 try {
 94 PdfReader reader = new PdfReader(inputFile);
 95 PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(
 96 outputFile));
 97 // 設置密碼
 98 //stamper.setEncryption(userPassWord.getBytes(), ownerPassWord.getBytes(), permission, false);
 99 BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
100 BaseFont.NOT_EMBEDDED);
101 int total = reader.getNumberOfPages() + 1;
102 Image image = Image.getInstance(imageFilePath);
103 image.setAbsolutePosition(50, 400);//座標
104 image.setRotation(-20);//旋轉 弧度
105 image.setRotationDegrees(-45);//旋轉 角度
106 // image.scaleAbsolute(200,100);//自定義大小
107 image.scalePercent(50);//依照比例縮放
108 PdfContentByte under;
109 int j = waterMarkName.length();
110 char c = 0;
111 int rise = 0;
112 for (int i = 1; i < total; i++) {
113 rise = 500;
114 under = stamper.getUnderContent(i);
115 // 添加圖片
116 under.addImage(image);
117 PdfGState gs = new PdfGState();
118 gs.setFillOpacity(0.2f);// 設置透明度爲0.2
119 under.setGState(gs);
120 under.beginText();
121 under.setColorFill(Color.CYAN);
122 under.setFontAndSize(base, 30);
123 // 設置水印文字字體傾斜 開始
124 if (j >= 15) {
125 under.setTextMatrix(200, 120);
126 for (int k = 0; k < j; k++) {
127 under.setTextRise(rise);
128 c = waterMarkName.charAt(k);
129 under.showText(c + "");
130 rise -= 20;
131 }
132 } else {
133 under.setTextMatrix(180, 100);
134 for (int k = 0; k < j; k++) {
135 under.setTextRise(rise);
136 c = waterMarkName.charAt(k);
137 under.showText(c + "");
138 rise -= 18;
139 }
140 }
141 // 字體設置結束
142 under.endText();
143 // 畫一個圓
144 // under.ellipse(250, 450, 350, 550);
145 // under.setLineWidth(1f);
146 // under.stroke();
147 }
148 stamper.close();
149 } catch (Exception e) {
150 e.printStackTrace();
151 }
152 }
153 
154 
155 private static Font setChineseFont() {
156 BaseFont base = null;
157 Font fontChinese = null;
158 try {
159 base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
160 BaseFont.EMBEDDED);
161 fontChinese = new Font(base, 12, Font.NORMAL);
162 } catch (DocumentException e) {
163 e.printStackTrace();
164 } catch (IOException e) {
165 e.printStackTrace();
166 }
167 return fontChinese;
168 }
169 
170 public static void main(String[] args) {
171 generatePDFWithTxt(txtFilePath, pdfFilePath, "123", "", 16);
172 }
173 }
itext對PDF水印圖片的旋轉、放大、縮小等操做的示例
 1 public class CusAccessObjectUtil {
 2      /** 
 3        * 獲取用戶真實IP地址,不使用request.getRemoteAddr();的緣由是有可能用戶使用了代理軟件方式避免真實IP地址, 
 4        * 
 5        * 但是,若是經過了多級反向代理的話,X-Forwarded-For的值並不止一個,而是一串IP值,究竟哪一個纔是真正的用戶端的真實IP呢? 
 6        * 答案是取X-Forwarded-For中第一個非unknown的有效IP字符串。 
 7        * 
 8        * 如:X-Forwarded-For:192.168.1.110, 192.168.1.120, 192.168.1.130, 
 9        * 192.168.1.100 
10        * 
11        * 用戶真實IP爲: 192.168.1.110 
12        * 
13        * @param request 
14        * @return 
15        */ 
16       public static String getIpAddress(HttpServletRequest request) { 
17         /*String ip = request.getHeader("x-forwarded-for"); 
18         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
19           ip = request.getHeader("Proxy-Client-IP"); 
20         } 
21         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
22           ip = request.getHeader("WL-Proxy-Client-IP"); 
23         } 
24         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
25           ip = request.getHeader("HTTP_CLIENT_IP"); 
26         } 
27         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
28           ip = request.getHeader("HTTP_X_FORWARDED_FOR"); 
29         } 
30         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
31           ip = request.getRemoteAddr(); 
32         } 
33         return ip; */
34           String ip = request.getHeader("x-forwarded-for");
35           
36             if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
37                 ip = request.getHeader("Proxy-Client-IP");
38             }
39             if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
40                 ip = request.getHeader("WL-Proxy-Client-IP");
41             }
42             if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
43                 ip = request.getRemoteAddr();
44             }
45             return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
46       } 
47 }
request獲取請求ip
package com.yhb.jsxn.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.yhb.jsxn.common.Constants;

import redis.clients.jedis.Jedis;

/**
 * 
* @ClassName: SecurityCodeUtil.java
* @Description:生成各類圖形驗證碼的工具類
* @version: v1.0.0
* @author: YJ
 */
public class SecurityCodeUtil {
    private static Random random = new Random();
    private static String randString = "0123456789";// 隨機產生數字 
    private static int width = 78;// 圖片寬  
    private static int height = 32;// 圖片高  
    private static int lineSize = 180;// 干擾線數量
    private static String randFH="+x-";  
    private String randZF="嵐儒金服";//隨機數字 
    private static int stringNum = 2;// 隨機產生字符數量  

    
    public static String getTowCalcPic(HttpServletRequest request,HttpServletResponse response) throws IOException{
        String ipAddress = CusAccessObjectUtil.getIpAddress(request);
        //System.out.println("<===============>"+ipAddress);
        
        HttpSession session = request.getSession();
        // BufferedImage類是具備緩衝區的Image類,Image類是用於描述圖像信息的類  
        BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_BGR);  
        Graphics2D g = (Graphics2D) image.getGraphics();// 產生Image對象的Graphics對象,修改對象能夠在圖像上進行各類繪製操做  
        g.fillRect(0, 0, width, height);  //填充指定的矩形。int x,int y,int width,int height.x - 要填充矩形的 x 座標。 y - 要填充矩形的 y 座標。width - 要填充矩形的寬度。height - 要填充矩形的高度。
        g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18));  //設置繪製字體
        g.setColor(getRandColor(110, 133)); //設置繪製顏色
        // 繪製干擾線  
        for (int i = 0; i <= lineSize; i++) {  
            drowLine(g);  
        } 
        // 繪製隨機字符  
        String randomString = "";  
        for (int i = 1; i <= stringNum; i++) {  
            randomString = drowString(g, randomString, i);  
        }   
        //解析繪製圖形的字符串並計算結果值
        char [] stringArr = randomString.toCharArray();  
        if(stringArr[1]=='+'){  
            randomString=String.valueOf(Integer.parseInt(String.valueOf(stringArr[0]))+Integer.parseInt(String.valueOf(stringArr[2])));   
        }else if(stringArr[1]=='-'){  
            randomString=String.valueOf(Integer.parseInt(String.valueOf(stringArr[0]))-Integer.parseInt(String.valueOf(stringArr[2])));    
        }else if(stringArr[1]=='x'){  
            randomString=String.valueOf(Integer.parseInt(String.valueOf(stringArr[0]))*Integer.parseInt(String.valueOf(stringArr[2])));   
        } 
        g.dispose();  //釋放此圖形的上下文以及它使用的全部系統資源 釋放之後將不能使用g
        session.removeAttribute(Constants.RANDOM_CODE_KEY + ipAddress);  
        session.setAttribute(Constants.RANDOM_CODE_KEY + ipAddress, randomString);  
        Jedis jedis = new Jedis();
        jedis.set(Constants.RANDOM_CODE_KEY + ipAddress, randomString);
        //設置保存時間
        jedis.expire(Constants.RANDOM_CODE_KEY+ipAddress, 2 * 60);
        jedis.close();
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        
        
        try {  
            
            ImageIO.write(image, "JPEG", jpegOutputStream);
        } catch (Exception e) {  
            e.printStackTrace();  
        } 
        byte[] captchaChallengeAsJpeg   = jpegOutputStream.toByteArray();
        ServletOutputStream responseOutputStream = response.getOutputStream();//獲取輸出流
        responseOutputStream.write(captchaChallengeAsJpeg);//輸出流
        responseOutputStream.flush();
        responseOutputStream.close();
        
        return randomString;
        
    }

    
    
    /**
     * 繪製計算算子,並返回 用於後端程序解析計算
     */
    private static String drowString(Graphics2D g, String randomString, int i) {  
        g.setFont(getFont());  
        g.setColor(new Color(random.nextInt(101), random.nextInt(111), random.nextInt(121)));
        // 設置字體旋轉角度
        int degree = new Random().nextInt() % 30;
        int x = 5;
        // 正向角度
        g.rotate(degree * Math.PI / 180, x, 20);
        g.drawString(randomString, x, 20);
        // 反向角度
        g.rotate(-degree * Math.PI / 180, x, 20);
        String rand1 = String.valueOf(getRandomString(random.nextInt(randString.length())));  
        String rand2 = String.valueOf(getRandomString(random.nextInt(randString.length())));  
        String rand3 = String.valueOf(getRandomStringFH(random.nextInt(randFH.length())));  
        randomString += rand1+rand3+rand2+"=?";  
        /* g.translate(random.nextInt(2), random.nextInt(2));  */
        /*   g.drawString(randomString, 13 * i, 24);  */
        return randomString;  
    }
    
    /** 
     * 繪製干擾線 
     */  
    private static void drowLine(Graphics g) {  
        int x = random.nextInt(width);  
        int y = random.nextInt(height);  
        int xl = random.nextInt(13);  
        int yl = random.nextInt(13);  
        // 設置邊框顏色
      //  g.setColor(Color.black);
        // 邊框區域
        
        /*g.drawRect(0, 0, WIDTH - 2, HEIGHT - 2);*/
        g.drawLine(x, y, x + xl, y + yl - 1);  
    }  
  
    /** 
     * 獲取隨機的字符 
     */  
    public static String getRandomString(int num) {  
        return String.valueOf(randString.charAt(num));  
    }  
      
    /**
     * 獲取隨機的運算符號 
     */  
    public static String getRandomStringFH(int num) {  
        return String.valueOf(randFH.charAt(num));  
    }
    /**
     * 得到字體 
     */  
    private static Font getFont() {  
        return new Font("Fixedsys", Font.CENTER_BASELINE, 18);  
    }  
    /**
     * 得到顏色 
     */  
    private static Color getRandColor(int fc, int bc) {  
        if (fc > 255)  
            fc = 255;  
        if (bc > 255)  
            bc = 255;  
        int r = fc + random.nextInt(bc - fc - 16);//110+7  
        int g = fc + random.nextInt(bc - fc - 14);//110+9  
        int b = fc + random.nextInt(bc - fc - 18);//110+5  
        return new Color(r, g, b);  
    }  
    
    /* 
     * 獲取隨機的漢字 
     */  
    public String getRandomString2(int num) {  
        return String.valueOf(randZF.charAt(num));  
    }  
}
生成計算數據的驗證碼
 @Test

 Assert.assertEquals(2, principalCollection.asList().size());


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:applicationContext*.xml"})
junite4
package com.test;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.junit.Before;
import org.junit.Test;

import redis.clients.jedis.Jedis;

public class TestRedis {
    private Jedis jedis; 
    
    @Before
    public void setup() {
        //鏈接redis服務器,192.168.0.100:6379
        jedis = new Jedis("192.168.0.100", 6379);
        //權限認證
        jedis.auth("admin");  
    }
    
    /**
     * redis存儲字符串
     */
    @Test
    public void testString() {
        //-----添加數據----------  
        jedis.set("name","xinxin");//向key-->name中放入了value-->xinxin  
        System.out.println(jedis.get("name"));//執行結果:xinxin  
        
        jedis.append("name", " is my lover"); //拼接
        System.out.println(jedis.get("name")); 
        
        jedis.del("name");  //刪除某個鍵
        System.out.println(jedis.get("name"));
        //設置多個鍵值對
        jedis.mset("name","liuling","age","23","qq","476777XXX");
        jedis.incr("age"); //進行加1操做
        System.out.println(jedis.get("name") + "-" + jedis.get("age") + "-" + jedis.get("qq"));
        
    }
    
    /**
     * redis操做Map
     */
    @Test
    public void testMap() {
        //-----添加數據----------  
        Map<String, String> map = new HashMap<String, String>();
        map.put("name", "xinxin");
        map.put("age", "22");
        map.put("qq", "123456");
        jedis.hmset("user",map);
        //取出user中的name,執行結果:[minxr]-->注意結果是一個泛型的List  
        //第一個參數是存入redis中map對象的key,後面跟的是放入map中的對象的key,後面的key能夠跟多個,是可變參數  
        List<String> rsmap = jedis.hmget("user", "name", "age", "qq");
        System.out.println(rsmap);  
  
        //刪除map中的某個鍵值  
        jedis.hdel("user","age");
        System.out.println(jedis.hmget("user", "age")); //由於刪除了,因此返回的是null  
        System.out.println(jedis.hlen("user")); //返回key爲user的鍵中存放的值的個數2 
        System.out.println(jedis.exists("user"));//是否存在key爲user的記錄 返回true  
        System.out.println(jedis.hkeys("user"));//返回map對象中的全部key  
        System.out.println(jedis.hvals("user"));//返回map對象中的全部value 
  
        Iterator<String> iter=jedis.hkeys("user").iterator();  
        while (iter.hasNext()){  
            String key = iter.next();  
            System.out.println(key+":"+jedis.hmget("user",key));  
        }  
    }
    
    /** 
     * jedis操做List 
     */  
    @Test  
    public void testList(){  
        //開始前,先移除全部的內容  
        jedis.del("java framework");  
        System.out.println(jedis.lrange("java framework",0,-1));  
        //先向key java framework中存放三條數據  
        jedis.lpush("java framework","spring");  
        jedis.lpush("java framework","struts");  
        jedis.lpush("java framework","hibernate");  
        //再取出全部數據jedis.lrange是按範圍取出,  
        // 第一個是key,第二個是起始位置,第三個是結束位置,jedis.llen獲取長度 -1表示取得全部  
        System.out.println(jedis.lrange("java framework",0,-1));  
        
        jedis.del("java framework");
        jedis.rpush("java framework","spring");  
        jedis.rpush("java framework","struts");  
        jedis.rpush("java framework","hibernate"); 
        System.out.println(jedis.lrange("java framework",0,-1));
    }  
    
    /** 
     * jedis操做Set 
     */  
    @Test  
    public void testSet(){  
        //添加  
        jedis.sadd("user","liuling");  
        jedis.sadd("user","xinxin");  
        jedis.sadd("user","ling");  
        jedis.sadd("user","zhangxinxin");
        jedis.sadd("user","who");  
        //移除noname  
        jedis.srem("user","who");  
        System.out.println(jedis.smembers("user"));//獲取全部加入的value  
        System.out.println(jedis.sismember("user", "who"));//判斷 who 是不是user集合的元素  
        System.out.println(jedis.srandmember("user"));  
        System.out.println(jedis.scard("user"));//返回集合的元素個數  
    }  
  
    @Test  
    public void test() throws InterruptedException {  
        //jedis 排序  
        //注意,此處的rpush和lpush是List的操做。是一個雙向鏈表(但從表現來看的)  
        jedis.del("a");//先清除數據,再加入數據進行測試  
        jedis.rpush("a", "1");  
        jedis.lpush("a","6");  
        jedis.lpush("a","3");  
        jedis.lpush("a","9");  
        System.out.println(jedis.lrange("a",0,-1));// [9, 3, 6, 1]  
        System.out.println(jedis.sort("a")); //[1, 3, 6, 9]  //輸入排序後結果  
        System.out.println(jedis.lrange("a",0,-1));  
    }  
    
    @Test
    public void testRedisPool() {
        RedisUtil.getJedis().set("newname", "中文測試");
        System.out.println(RedisUtil.getJedis().get("newname"));
    }
}
java操做redis
  1 <?xml version="1.0" encoding="UTF-8" ?>
  2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
  3 <mapper namespace="com.yhb.jsxn.mapper.FinanceProductsUsersMapper">
  4 <!-- mybatis sql語句中的轉義字符的書寫:
  5         1、在xml的sql語句中,不能直接用大於號、小於號要用轉義字符
  6         若是用小於號會報錯誤以下:
  7         org.apache.ibatis.builder.BuilderException: Error creating document instance. 
  8         Cause: org.xml.sax.SAXParseException: The content of elements must consist of well-formed character data or markup.
  9         轉義字符
 10                 小於號        <            &lt;
 11                 大於號        >        &gt;
 12                 和            &         &amp;
 13                 單引號        '        &apos;
 14                 雙引號        "       &quot;
 15         二、使用<![CDATA[  你的sql語句  ]]>(sql語句中的<where><if>等標籤不會被解析)
 16          如:
 17          <![CDATA[
 18                 select * from 
 19               (select t.*, ROWNUM as rowno from tbl_user t where ROWNUM <= #{page.end,jdbcType=DECIMAL}) table_alias
 20               where table_alias.rowno >#{page.start,jdbcType=DECIMAL}
 21              ]]>          
 22 -->
 23  
 24 <!--    Mybatis批量插入Oracle、MySQL 
 25 
 26 
 27  --> 
 28  
 29 <!-- mysql數據庫的數據類型: -->
 30 <!--
 31 
 32 -->
 33 
 34 
 35 <!--  mysql修改字符編碼
 36   X:\%path%\MySQL\MySQL Server 5.0\bin\MySQLInstanceConfig.exe
 37   從新啓動設置,將默認編碼設置爲utf8.這樣就能達到咱們所要的效果了。
 38 
 39 1、修改數據庫字符編碼
 40 
 41 mysql> alter database mydb character set utf8 ;
 42 
 43 2、建立數據庫時,指定數據庫的字符編碼
 44 
 45 mysql> create database mydb character set utf8 ;
 46 
 47 3、查看mysql數據庫的字符編碼
 48 
 49 mysql> show variables like 'character%'; //查詢當前mysql數據庫的全部屬性的字符編碼
 50 
 51 +--------------------------+----------------------------+
 52 | Variable_name            | Value                      |
 53 +--------------------------+----------------------------+
 54 | character_set_client     | latin1                     |
 55 | character_set_connection | latin1                     |
 56 | character_set_database   | utf8                       |
 57 | character_set_filesystem | binary                     |
 58 | character_set_results    | latin1                     |
 59 | character_set_server     | utf8                       |
 60 | character_set_system     | utf8                       |
 61 | character_sets_dir       | /usr/share/mysql/charsets/ |
 62 +--------------------------+----------------------------+
 63 
 64 4、修改mysql數據庫的字符編碼
 65 
 66 修改字符編碼必需要修改mysql的配置文件my.cnf,而後重啓才能生效
 67 
 68 一般須要修改my.cnf的以下幾個地方:
 69 
 70 【client】下面,加上default-character-set=utf8,或者character_set_client=utf8
 71 
 72 【mysqld】下面,加上character_set_server = utf8 ;
 73 
 74 由於以上配置,mysql默認是latin1,若是僅僅是經過命令行客戶端,mysql重啓以後就不起做用了。
 75 
 76 以下是客戶端命令行修改方式,不推薦使用
 77 
 78 mysql> set character_set_client=utf8 ;
 79 
 80 mysql> set character_set_connection=utf8 ;
 81 
 82 mysql> set character_set_database=utf8 ;
 83 
 84 mysql> set character_set_database=utf8 ;
 85 
 86 mysql> set character_set_results=utf8 ;
 87 
 88 mysql> set character_set_server=utf8 ;
 89 
 90 mysql> set character_set_system=utf8 ;
 91 
 92 mysql> show variables like 'character%';
 93 +--------------------------+----------------------------+
 94 | Variable_name            | Value                      |
 95 +--------------------------+----------------------------+
 96 | character_set_client     | utf8                       |
 97 | character_set_connection | utf8                       |
 98 | character_set_database   | utf8                       |
 99 | character_set_filesystem | binary                     |
100 | character_set_results    | utf8                       |
101 | character_set_server     | utf8                       |
102 | character_set_system     | utf8                       |
103 | character_sets_dir       | /usr/share/mysql/charsets/ |
104 +--------------------------+----------------------------+
105 
106     -> ;
107 +--------------------------+---------------------------------------------------------------+
108 | Variable_name            | Value                                                         |
109 +--------------------------+---------------------------------------------------------------+
110 | character_set_client     | utf8                                                          |
111 | character_set_connection | utf8                                                          |
112 | character_set_database   | utf8                                                          |
113 | character_set_filesystem | binary                                                        |
114 | character_set_results    | utf8                                                          |
115 | character_set_server     | utf8                                                          |
116 | character_set_system     | utf8                                                          |
117 | character_sets_dir       | C:\Program Files (x86)\MySQL\MySQL Server 5.5\share\charsets\ |
118 +--------------------------+---------------------------------------------------------------+
119 
120 8 rows in set (0.00 sec)
121 8 rows in set (0.00 sec)
122  -->
123     <!-- 查詢結果映射 -->
124     <!--解決數據庫表字段列明和實體vo不匹配問題  -->
125     <resultMap id="BaseResultMap" type="com.yhb.jsxn.entity.FinanceProductsUsers">
126         <!-- 主鍵映射 -->
127         <id column="FPUID" property="FPUID"                                     jdbcType="INTEGER" />
128         <result column="UserID" property="UserID"                                 jdbcType="VARCHAR" />
129         <result column="FProductsRates" property="FProductsRates"                 jdbcType="FLOAT" />
130         <result column="FProductsBuyMoney" property="FProductsBuyMoney"         jdbcType="DECIMAL" />
131         <result column="FProductsBuyTime" property="FProductsBuyTime"             jdbcType="TIMESTAMP" />
132         <result column="FProductsRateInNum" property="FProductsRateInNum"         jdbcType="INTEGER" />
133 
134     </resultMap>
135 
136     <!-- select 語句
137         select 標籤屬性:
138             id: id編號
139             parameterType: 獲取的參數值:
140                 eg:
141                     java.lang.Integer
142                     map
143             resultMap:
144                 eg:
145                     返回的是一個映射結果集,對應一個實體vo類
146                             想用ParameterType=Map傳入多個參數構造SQL進行查詢:
147                             <select id="getBusList" resultMap="busListMap" parameterType="java.util.Map">  
148                                     select bs.bus_id as bus_id,bs.arrive_time as up_time,b.start_station  
149                                     as start_station_id,  
150                                     b.end_station as end_station_id  
151                                     from bus b , bus_station bs where b.bus_id = bs.bus_id and  
152                                     bs.station_id=#{upStationId}  
153                                     and is_up=1 and b.up_station_line like  
154                                     #{upStationLineLike} and b.down_station_line  
155                                     like  
156                                     #{downStationLineLike}  
157                                     and (b.daily=1 or b.weekly like #{weeklyLike} or b.run_day like  
158                                     #{runDayLike} )  
159                                     order by bs.arrive_time asc  
160                                 </select>  
161                             調試時報 Parameter not found異常
162                             解決方法,使用此方式傳參,必須在對應的接口方法用@Param標籤訂義參數value才行:
163                             
164                             public List<Bus> getBusList(@Param(value = "upStationId") long upStationId,   
165                                         @Param(value = "upStationLineLike") String upStationLineLike,   
166                                         @Param(value = "downStationLineLike") String downStationLineLike,  
167                                         @Param(value = "weeklyLike") String weeklyLike,  
168                                         @Param(value = "runDayLike") String runDayLike  
169                                         ){} ;  
170             resultType:
171                 eg:
172                     Integer
173                     String
174                     Decimal
175                     int
176      -->
177    <select id="selectFinByFPUID" resultMap="BaseResultMap" parameterType="java.lang.Integer">
178    select 
179     *
180     from financeproducts_users
181     where FPUID = #{FPUID,jdbcType=INTEGER}
182   </select>
183     <select id="selectAllByFPid" resultMap="BaseResultMap" parameterType="map">
184         select
185         a.TrueName,a.UserName,b.FProductsBuyMoney,b.FProductsBuyTime from
186         accounts_users a, financeproducts_users b where a.UserID = b.UserID
187         and b.FPid=#{fpid} and FProductsCountNum &gt; FProductsRateInNum order
188         by b.FProductsBuyTime DESC limit
189         #{pageNo},#{size}
190     </select>
191     <select id="getFinancialUsers" resultType="String">
192         select distinct userid from financeproducts_users
193     </select>
194     <select id="selectNewProduct" parameterType="String" resultType="Integer">
195         select count(*) from financeproducts_users where UserID =#{userId} and
196         FPid in (140,141)
197     </select>
198     <select id="getUserFreeze"  parameterType="map" resultType="Decimal">
199         select sum(FproductsBuyMoney-FProductsRateMoney) userFrezz from
200         financeproducts_users where UserID =#{userId} and FProductsEm_k2=1
201     </select>
202     <!--     <if test="array.length > 0">
203                     <where>
204                         <foreach collection="array"  open="(" item="age" close=")" separator=",">
205                             and age in (#{age})
206                         </foreach>
207                     </where>
208                 </if> -->
209     
210     <select id="selectByUserIdById" resultMap="BaseResultMap" parameterType="Map">
211         select * from (
212         select
213         a.UserID,a.FProductsBuyMoney,a.FProductsName,b.ProfitMoney,b.UserId_Get,b.UserName_Give
214         from financeproducts_users a
215         left join
216         (SELECT
217         UserId_Give,UserId_Get,UserName_Give,ProfitMoney FROM
218         accounts_distributor_profit
219         where UserId_Get=#{Id} group by UserId_Give
220         )b
221         on a.UserId=b.UserId_Give
222         )a where a.UserId_Get is not null
223     </select> 
224      <select id="getHistoricalBuyProductsByName" resultMap="BaseResultMap"
225         parameterType="hashMap">
226         select
227         FProductsName,FProductsRateInNum,FProductsImgs,FProductsCountRateMoney,FProductsBuyMoney,
228         FProductsBuyTime,FProductsCountNum
229         from financeproducts_users
230         where
231         <if test="UserID !=null">
232             UserID =#{UserID}
233         </if>
234         and FProductsCountNum<![CDATA[<=]]>FProductsRateInNum
235         <if test="startTime !=null">
236             and DATE_FORMAT(FProductsBuyTime,'%Y-%m-%d')<![CDATA[>=]]>#{startTime}
237         </if>
238         <if test="dayNum !=null">
239             and FProductsCountNum <![CDATA[<=]]>#{dayNum}
240         </if>
241         <if test="FProductsName !=null and FProductsName !=''">
242         <!-- mysql> select concat_ws(',','11','22','33');
243                 
244                 +-------------------------------+
245                 | concat_ws(',','11','22','33') |
246                 +-------------------------------+
247                 | 11,22,33 |
248                 +-------------------------------+ 
249         oracle 可使用||來鏈接
250         -->
251             and FProductsName like CONCAT('%', #{FProductsName}, '%')
252         </if>
253     </select> 
254     <select id="selectAlreadyByUserId" resultMap="BaseResultMap"
255         parameterType="Map">
256         select
257         FProductsName,FProductsRateInNum,FProductsImgs,FProductsCountRateMoney,FProductsBuyMoney,
258         FProductsBuyTime,FProductsCountNum
259         from financeproducts_users
260         where
261         FProductsCountNum &gt; FProductsRateInNum and UserID =#{UserID}
262         order
263         by FProductsBuyTime
264     </select>
265         <!--根據查詢條件獲取歷史購買產品並分頁 
266             用 ISNULL(), NVL(), IFNULL() and COALESCE() 函數替換空值
267             在數據庫操做中,每每要對一些查詢出來的空值進行替換,如函數SUM(),這個函數若是沒有值會返回NULL,這是咱們不但願看到的,
268                     在MySQL中咱們能夠這樣來寫:
269                         select IFNULL(sum(data),0) ...
270                     在SQLSERVER中咱們能夠這樣寫:
271                         select ISNULL(sum(data),0) ...
272                     在ORACLE中咱們能夠這樣寫:
273                         select NVL(sum(data),0) ...
274             對於全部數據庫適用的方法能夠這樣寫:
275                     select COALESCE(sum(data),0) ...
276         COALESCE()用法:
277              COALESCE(value,...)
278             返回第一個不是null的值,若是參數列表全是null,則返回null
279                 SELECT COALESCE(NULL,1);
280                     -> 1
281                 SELECT COALESCE(NULL,NULL,NULL);
282                 -> NULL
283         -->
284     <select id="selectHistoricalByUserIdByPageName" resultMap="BaseResultMap"
285         parameterType="Map">
286 
287             select b.UserID,coalesce(a.FProductsBuyMoney,b.FProductsRateMoney) as FProductsBuyMoney,coalesce(a.m,0) as sumProfit,b.FProductsRateMoney,b.FPUID,b.FProductsName,b.FProductsImgs from 
288              ( select * from financeproducts_users where FProductsEm_k2 = 0 and userid =#{UserID}) b
289             left join
290                     (select userid,FProductsBuyMoney,FProductsRateEm_k1,sum(FProductsAsRateMoney) as m from financeproducts_rates 
291                     where userid =#{UserID}
292                      group by FProductsRateEm_k1 ) a
293                     on a.FProductsRateEm_k1=b.fpuid 
294 
295         <if test="startTime !=null">
296             and DATE_FORMAT(b.FProductsBuyTime,'%Y-%m-%d')<![CDATA[>=]]>#{startTime}
297         </if>
298         <if test="productName !=null">
299             and b.FProductsName like CONCAT('%', #{productName}, '%')
300         </if>
301     </select>
302   
303       <!-- insert -->
304       <insert id="insertSelective" useGeneratedKeys="true" keyProperty="FPUID" parameterType="com.yhb.jsxn.entity.FinanceProductsUsers">
305         insert into financeproducts_users
306         <trim prefix="(" suffix=")" suffixOverrides=",">
307             <if test="UserID != null">
308                 UserID,
309             </if>
310             <if test="FPid != null">
311                 FPid,
312             </if>
313         </trim>
314         <trim prefix="values (" suffix=")" suffixOverrides=",">
315             <if test="UserID != null">
316                 #{UserID,jdbcType=VARCHAR},
317             </if>
318             <if test="FPid != null">
319                 #{FPid,jdbcType=INTEGER},
320             </if>
321             <if test="FProductsName != null">
322                 #{FProductsName,jdbcType=VARCHAR},
323             </if>
324         </trim>
325     </insert>
326       
327     <!-- update 語句 -->
328     <update id="updateByPrimaryKeySelective" parameterType="com.yhb.jsxn.entity.FinanceProductsUsers">
329         update financeproducts_users
330         <set>
331             <if test="FProductsEm_k2 != null">
332                 FProductsEm_k2=#{FProductsEm_k2,jdbcType=VARCHAR},
333             </if>
334             <if test="FProductsEm_k3 != null">
335                 FProductsEm_k3=#{FProductsEm_k3,jdbcType=VARCHAR},
336             </if>
337         </set>
338         where FPUID =#{FPUID,jdbcType=INTEGER}
339     </update>
340     
341     <!-- del 語句 -->
342 </mapper>
343 
344 mybatis經常使用寫法
mybatis經常使用寫法
 1 Map<String, Object> map = new HashMap<String, Object>();
 2         map.put("seckillId", seckillId);
 3         map.put("phone", userPhone);
 4         map.put("killTime", new Date());
 5         map.put("result", null);
 6 
 7  seckillDao.killByProcedure(map);
 8 
 9 xml:
10 <!--使用mybatis調用msyql5.6存儲過程注意存儲過程的入參和出參-->
11     <select id="killByProcedure" statementType="CALLABLE">
12           call execute_seckill(
13             #{seckillId,jdbcType=BIGINT,mode=IN},
14             
15             #{phone,jdbcType=BIGINT,mode=IN},
16             
17             #{killTime,jdbcType=TIMESTAMP,mode=IN},
18             
19             #{result,jdbcType=INTEGER,mode=OUT}<!-- map.put("result", null);//執行存儲過程之後,result被賦值:返回執行結果的枚舉值: -->
20           )
21     </select>
mybatis-調用mysql的存儲過程

 項目中出現的奇怪現象:html

BaseConfig appProConfig = baseConfigService.selectByParam("cfg_appIndexPro");java

 

就是查詢不出來,後來粘貼java代碼中的參數cfg_appIndexPro到subline中對比數據庫中的value 值 cfg_appIndexPro我夥呆:mysql

暫時還不知道怎麼會出現這個狀況的。web

相關文章
相關標籤/搜索