【代码总结-不定期更新】

1 packagecom.runyi.share.service.information.commons.exceptions;2
3 importcom.runyi.ryplat.api.exceptions.BusinessException;4
5 public class InfoBackStageException extendsBusinessException{6
7     /**
8 *9      */
10     private static final long serialVersionUID = 6854801395723117773L;11
12     publicInfoBackStageException(String code,String msg){13         super(msg);14         super.setCode(code);15         super.setType("IM");16         super.setData(msg);17 }18     publicInfoBackStageException(TYPE type){19         super(type.getDesc());20         super.setCode(type.getCode());21         super.setType("IM");22         super.setData(type.getDesc());23 }24     /**
25 * 代码定义规则26 * 例:WBPD00127 * WB(0,2):应用代码已定请咨询模块负责人;28 * PD(2,4):业务模块代码,29 * 001(4,7):序号30 * 本项应用应用代码为:PL31      */
32     public enumTYPE {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         privateString code;114         privateString desc;115 TYPE(String code,String desc) {116             this.code =code;117             this.desc =desc;118 }119         publicString getCode() {120             return this.code;121 }122         publicString getDesc() {123             return this.desc;124 }125 }126
127 }

枚举值1

1 //读取配置文件
2 public classPropertiesUtil {3
4     private static Properties properties = newProperties();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 staticString get(String key) {14         String value =properties.getProperty(key);15         if(value != null){16             value =value.trim();17 }18         returnvalue;19 }20
21 }

读取配置文件

1 packageorg.seckill.enums;2
3 /**
4 * 使用枚举标识常量数据:5 * 数据字典放到枚举当中6  */
7 public enumSeckillStatEnum {8     SUCCESS(1,"秒杀成功"),9     END(0,"秒杀结束"),10     REPEAT_KILL(-1,"重复秒杀"),11     INNER_ORROR(-2,"系统异常"),12     DATA_REWRITE(-3,"数据篡改");13     private intstate;14     privateString stateInfo;15
16
17
18     SeckillStatEnum(intstate, String stateInfo) {19         this.state =state;20         this.stateInfo =stateInfo;21 }22
23     public intgetState() {24         returnstate;25 }26
27     public void setState(intstate) {28         this.state =state;29 }30
31     publicString getStateInfo() {32         returnstateInfo;33 }34
35     public voidsetStateInfo(String stateInfo) {36         this.stateInfo =stateInfo;37 }38
39     public static  SeckillStatEnum stateOf(intindex){40         //枚举内部的values()方法用于拿到所有的类型
41         for(SeckillStatEnum state: values()){42             if(state.getState()==index){43                 returnstate;44 }45 }46         return  null;47 }48
49 }

枚举值2

1 packagecom.yhb.jsxn.servlet;2 //中文simplecaptcha
3 importjava.awt.Color;4 importjava.awt.Font;5 importjava.awt.Graphics;6 importjava.awt.Graphics2D;7 importjava.awt.image.BufferedImage;8 importjava.io.IOException;9 importjava.util.Random;10
11 importjavax.imageio.ImageIO;12 importjavax.servlet.ServletException;13 importjavax.servlet.ServletOutputStream;14 importjavax.servlet.http.HttpServlet;15 importjavax.servlet.http.HttpServletRequest;16 importjavax.servlet.http.HttpServletResponse;17
18 importorg.apache.commons.io.output.ByteArrayOutputStream;19 importorg.springframework.beans.factory.BeanFactoryUtils;20 importorg.springframework.web.context.WebApplicationContext;21 importorg.springframework.web.context.support.WebApplicationContextUtils;22
23 importcom.octo.captcha.service.CaptchaServiceException;24 importcom.octo.captcha.service.image.ImageCaptchaService;25
26
27 /**
28 * 提供验证码图片的Servlet29  */
30 @SuppressWarnings("serial")31 public class JcaptchaServlet3 extendsHttpServlet {32     public static final String CAPTCHA_IMAGE_FORMAT = "jpeg";33     public static final int WIDTH = 120;34     public static final int HEIGHT = 30;35     privateImageCaptchaService captchaService;36
37 @Override38     public void init() throwsServletException {39         WebApplicationContext appCtx =WebApplicationContextUtils40 .getWebApplicationContext(getServletContext());41         captchaService =(ImageCaptchaService) BeanFactoryUtils42                 .beanOfTypeIncludingAncestors(appCtx, ImageCaptchaService.class);43
44 }45
46 @Override47     protected voiddoGet(HttpServletRequest request,48             HttpServletResponse response) throwsServletException, IOException {49         byte[] captchaChallengeAsJpeg = null;50         //the output stream to render the captcha image as jpeg into
51         ByteArrayOutputStream jpegOutputStream = newByteArrayOutputStream();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 id55             //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 = newBufferedImage(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 *@paramg118      */
119     private voidsetBackGround(Graphics g) {120         //设置颜色
121 g.setColor(Color.WHITE);122         //填充区域
123         g.fillRect(0, 0, WIDTH, HEIGHT);124 }125     /**
126 * 设置边框127 *128 *@paramg129      */
130     private voidsetBorder(Graphics g) {131         //设置边框颜色
132 g.setColor(Color.BLUE);133         //边框区域
134         g.drawRect(1, 1, WIDTH - 2, HEIGHT - 2);135 }136     /**
137 * 画随机线条138 *139 *@paramg140      */
141     private voiddrawRandomLine(Graphics g) {142         //设置颜色
143 g.setColor(Color.GREEN);144         //设置线条个数并画线
145         for (int i = 0; i < 5; i++) {146             int x1 = newRandom().nextInt(WIDTH);147             int y1 = newRandom().nextInt(HEIGHT);148             int x2 = newRandom().nextInt(WIDTH);149             int y2 = newRandom().nextInt(HEIGHT);150 g.drawLine(x1, y1, x2, y2);151 }152 }153     /**
154 * 画随机汉字155 *156 *@paramg157 *@return
158      */
159     privateString drawRandomNum(Graphics2D g) {160         StringBuffer sb = newStringBuffer();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         returnsb.toString();183 }184 }

生成汉字的验证码

1 packagecom.yhb.jsxn.servlet;2
3 importjava.awt.image.BufferedImage;4 importjava.io.IOException;5
6 importjavax.imageio.ImageIO;7 importjavax.servlet.ServletException;8 importjavax.servlet.ServletOutputStream;9 importjavax.servlet.http.HttpServlet;10 importjavax.servlet.http.HttpServletRequest;11 importjavax.servlet.http.HttpServletResponse;12
13 importorg.apache.commons.io.output.ByteArrayOutputStream;14 importorg.springframework.beans.factory.BeanFactoryUtils;15 importorg.springframework.web.context.WebApplicationContext;16 importorg.springframework.web.context.support.WebApplicationContextUtils;17
18 importcom.octo.captcha.service.CaptchaServiceException;19 importcom.octo.captcha.service.image.ImageCaptchaService;20
21
22 /**
23 * 提供验证码图片的Servlet24  */
25 @SuppressWarnings("serial")26 public class JcaptchaServlet extendsHttpServlet {27     public static final String CAPTCHA_IMAGE_FORMAT = "jpeg";28
29     privateImageCaptchaService captchaService;30
31 @Override32     public void init() throwsServletException {33         WebApplicationContext appCtx =WebApplicationContextUtils34 .getWebApplicationContext(getServletContext());35         captchaService =(ImageCaptchaService) BeanFactoryUtils36                 .beanOfTypeIncludingAncestors(appCtx, ImageCaptchaService.class);37
38 }39
40 @Override41     protected voiddoGet(HttpServletRequest request,42             HttpServletResponse response) throwsServletException, IOException {43         byte[] captchaChallengeAsJpeg = null;44         //the output stream to render the captcha image as jpeg into
45         ByteArrayOutputStream jpegOutputStream = newByteArrayOutputStream();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 id49             //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 packagetest1;2
3 importjava.awt.Color;4 importjava.io.BufferedReader;5 importjava.io.File;6 importjava.io.FileOutputStream;7 importjava.io.FileReader;8 importjava.io.IOException;9
10 importcom.lowagie.text.Document;11 importcom.lowagie.text.DocumentException;12 importcom.lowagie.text.Font;13 importcom.lowagie.text.HeaderFooter;14 importcom.lowagie.text.Image;15 importcom.lowagie.text.PageSize;16 importcom.lowagie.text.Paragraph;17 importcom.lowagie.text.Phrase;18 importcom.lowagie.text.Rectangle;19 importcom.lowagie.text.pdf.BaseFont;20 importcom.lowagie.text.pdf.PdfContentByte;21 importcom.lowagie.text.pdf.PdfGState;22 importcom.lowagie.text.pdf.PdfReader;23 importcom.lowagie.text.pdf.PdfStamper;24 importcom.lowagie.text.pdf.PdfWriter;25
26 public classPdfConvertor {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 voidgeneratePDFWithTxt(String txtFile, String pdfFile,41 String userPassWord, String waterMarkName, intpermission) {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 booleancreatePDFFile(String txtFilePath, File file) {58 //设置纸张
59 Rectangle rect = newRectangle(PageSize.A4);60 //设置页码
61 HeaderFooter footer = new HeaderFooter(new Phrase("页码:", PdfConvertor62 .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 = newFileReader(txtFilePath);69 BufferedReader read = newBufferedReader(fileRead);70 //设置pdf文件生成路径 step2
71 PdfWriter.getInstance(doc, newFileOutputStream(file));72 //打开pdf文件 step3
73 doc.open();74 //实例化Paragraph 获取写入pdf文件的内容,调用支持中文的方法.step4
75 while(read.ready()) {76 //添加内容到pdf(这里将会按照txt文件的原始样式输出)
77 doc.add(newParagraph(read.readLine(), PdfConvertor78 .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 voidwaterMark(String inputFile, String outputFile,91 String userPassWord, String ownerPassWord, String waterMarkName,92 intpermission) {93 try{94 PdfReader reader = newPdfReader(inputFile);95 PdfStamper stamper = new PdfStamper(reader, newFileOutputStream(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 = newPdfGState();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 staticFont 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 returnfontChinese;168 }169
170 public static voidmain(String[] args) {171 generatePDFWithTxt(txtFilePath, pdfFilePath, "123", "", 16);172 }173 }

itext对PDF水印图片的旋转、放大、缩小等操作的示例

1 public classCusAccessObjectUtil {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.10010 *11 * 用户真实IP为: 192.168.1.11012 *13 *@paramrequest14 *@return
15        */
16       public staticString 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

packagecom.yhb.jsxn.util;importjava.awt.Color;importjava.awt.Font;importjava.awt.Graphics;importjava.awt.Graphics2D;importjava.awt.image.BufferedImage;importjava.io.ByteArrayOutputStream;importjava.io.IOException;importjava.util.Date;importjava.util.HashMap;importjava.util.Random;importjavax.imageio.ImageIO;importjavax.servlet.ServletOutputStream;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjavax.servlet.http.HttpSession;importcom.yhb.jsxn.common.Constants;importredis.clients.jedis.Jedis;/***
* @ClassName: SecurityCodeUtil.java
* @Description:生成各种图形验证码的工具类
*@version: v1.0.0
*@author: YJ*/
public classSecurityCodeUtil {private static Random random = newRandom();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) throwsIOException{String ipAddress=CusAccessObjectUtil.getIpAddress(request);//System.out.println("<===============>"+ipAddress);
HttpSession session=request.getSession();//BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类BufferedImage image = newBufferedImage(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();//释放此图形的上下文以及它使用的所有系统资源 释放以后将不能使用gsession.removeAttribute(Constants.RANDOM_CODE_KEY +ipAddress);  session.setAttribute(Constants.RANDOM_CODE_KEY+ipAddress, randomString);  Jedis jedis= newJedis();jedis.set(Constants.RANDOM_CODE_KEY+ipAddress, randomString);//设置保存时间jedis.expire(Constants.RANDOM_CODE_KEY+ipAddress, 2 * 60);jedis.close();ByteArrayOutputStream jpegOutputStream= newByteArrayOutputStream();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();returnrandomString;}/*** 绘制计算算子,并返回 用于后端程序解析计算*/private static String drowString(Graphics2D g, String randomString, inti) {  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);*/returnrandomString;  }/*** 绘制干扰线*/  private static voiddrowLine(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(intnum) {returnString.valueOf(randString.charAt(num));  }/*** 获取随机的运算符号*/  public static String getRandomStringFH(intnum) {returnString.valueOf(randFH.charAt(num));  }/*** 获得字体*/  private staticFont getFont() {return new Font("Fixedsys", Font.CENTER_BASELINE, 18);  }/*** 获得颜色*/  private static Color getRandColor(int fc, intbc) {if (fc > 255)  fc= 255;if (bc > 255)  bc= 255;int r = fc + random.nextInt(bc - fc - 16);//110+7int g = fc + random.nextInt(bc - fc - 14);//110+9int b = fc + random.nextInt(bc - fc - 18);//110+5return newColor(r, g, b);  }/** 获取随机的汉字*/  public String getRandomString2(intnum) {returnString.valueOf(randZF.charAt(num));  }
}

生成计算数据的验证码

@TestAssert.assertEquals(2, principalCollection.asList().size());@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:applicationContext*.xml"})

junite4

packagecom.test;importjava.util.HashMap;importjava.util.Iterator;importjava.util.List;importjava.util.Map;importorg.junit.Before;importorg.junit.Test;importredis.clients.jedis.Jedis;public classTestRedis {privateJedis jedis; @Beforepublic voidsetup() {//连接redis服务器,192.168.0.100:6379jedis = new Jedis("192.168.0.100", 6379);//权限认证jedis.auth("admin");  }/*** redis存储字符串*/@Testpublic voidtestString() {//-----添加数据----------jedis.set("name","xinxin");//向key-->name中放入了value-->xinxinSystem.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*/@Testpublic voidtestMap() {//-----添加数据----------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")); //因为删除了,所以返回的是nullSystem.out.println(jedis.hlen("user")); //返回key为user的键中存放的值的个数2System.out.println(jedis.exists("user"));//是否存在key为user的记录 返回trueSystem.out.println(jedis.hkeys("user"));//返回map对象中的所有keySystem.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*/@Testpublic voidtestList(){//开始前,先移除所有的内容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*/@Testpublic voidtestSet(){//添加jedis.sadd("user","liuling");  jedis.sadd("user","xinxin");  jedis.sadd("user","ling");  jedis.sadd("user","zhangxinxin");jedis.sadd("user","who");//移除nonamejedis.srem("user","who");  System.out.println(jedis.smembers("user"));//获取所有加入的valueSystem.out.println(jedis.sismember("user", "who"));//判断 who 是否是user集合的元素System.out.println(jedis.srandmember("user"));  System.out.println(jedis.scard("user"));//返回集合的元素个数
}  @Testpublic void test() throwsInterruptedException {//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));  }  @Testpublic voidtestRedisPool() {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         2、使用<![CDATA[  你的sql语句  ]]>(sql语句中的<where><if>等标签不会被解析)16 如:17          <![CDATA[18                 select *from19               (select t.*, ROWNUM as rowno from tbl_user t where ROWNUM <= #{page.end,jdbcType=DECIMAL}) table_alias20               where table_alias.rowno >#{page.start,jdbcType=DECIMAL}21              ]]>
22 -->
23
24 <!--Mybatis批量插入Oracle、MySQL25
26
27  -->
28
29 <!-- mysql数据库的数据类型: -->
30 <!--
31
32 -->
33
34
35 <!--mysql修改字符编码36   X:\%path%\MySQL\MySQL Server 5.0\bin\MySQLInstanceConfig.exe37   重新启动设置,将默认编码设置为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=utf871
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.00sec)121 8 rows in set (0.00sec)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.Integer142 map143 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_station149 as start_station_id,150 b.end_station as end_station_id151                                     from bus b , bus_station bs where b.bus_id =bs.bus_id and152                                     bs.station_id=#{upStationId}153                                     and is_up=1and b.up_station_line like154 #{upStationLineLike} and b.down_station_line155 like156 #{downStationLineLike}157                                     and (b.daily=1or b.weekly like #{weeklyLike} or b.run_day like158 #{runDayLike} )159 order by bs.arrive_time asc160                                 </select>
161 调试时报 Parameter not found异常162 解决方法,使用此方式传参,必须在对应的接口方法用@Param标签定义参数value才行:163
164                             public List<Bus> getBusList(@Param(value = "upStationId") longupStationId,165                                         @Param(value = "upStationLineLike") String upStationLineLike,166                                         @Param(value = "downStationLineLike") String downStationLineLike,167                                         @Param(value = "weeklyLike") String weeklyLike,168                                         @Param(value = "runDayLike") String runDayLike169 ){} ;170 resultType:171 eg:172 Integer173 String174 Decimal175                     int
176      -->
177    <select id="selectFinByFPUID" resultMap="BaseResultMap" parameterType="java.lang.Integer">
178 select179     *
180 from financeproducts_users181     where FPUID = #{FPUID,jdbcType=INTEGER}182   </select>
183     <select id="selectAllByFPid" resultMap="BaseResultMap" parameterType="map">
184 select185 a.TrueName,a.UserName,b.FProductsBuyMoney,b.FProductsBuyTime from186         accounts_users a, financeproducts_users b where a.UserID =b.UserID187         and b.FPid=#{fpid} and FProductsCountNum &gt; FProductsRateInNum order188 by b.FProductsBuyTime DESC limit189 #{pageNo},#{size}190     </select>
191     <select id="getFinancialUsers" resultType="String">
192 select distinct userid from financeproducts_users193     </select>
194     <select id="selectNewProduct" parameterType="String" resultType="Integer">
195         select count(*) from financeproducts_users where UserID =#{userId} and196         FPid in (140,141)197     </select>
198     <select id="getUserFreeze"  parameterType="map" resultType="Decimal">
199         select sum(FproductsBuyMoney-FProductsRateMoney) userFrezz from200         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 select213 a.UserID,a.FProductsBuyMoney,a.FProductsName,b.ProfitMoney,b.UserId_Get,b.UserName_Give214 from financeproducts_users a215 left join216 (SELECT217 UserId_Give,UserId_Get,UserName_Give,ProfitMoney FROM218 accounts_distributor_profit219         where UserId_Get=#{Id} group by UserId_Give220 )b221         on a.UserId=b.UserId_Give222         )a where a.UserId_Get is not null
223     </select>
224      <select id="getHistoricalBuyProductsByName" resultMap="BaseResultMap"
225         parameterType="hashMap">
226 select227 FProductsName,FProductsRateInNum,FProductsImgs,FProductsCountRateMoney,FProductsBuyMoney,228 FProductsBuyTime,FProductsCountNum229 from financeproducts_users230 where231         <if test="UserID !=null">
232             UserID =#{UserID}233         </if>
234         and FProductsCountNum<![CDATA[<=]]>FProductsRateInNum235         <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 select257 FProductsName,FProductsRateInNum,FProductsImgs,FProductsCountRateMoney,FProductsBuyMoney,258 FProductsBuyTime,FProductsCountNum259 from financeproducts_users260 where261         FProductsCountNum &gt; FProductsRateInNum and UserID =#{UserID}262 order263 by FProductsBuyTime264     </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,则返回null279                 SELECT COALESCE(NULL,1);280                     -> 1
281 SELECT COALESCE(NULL,NULL,NULL);282                 ->NULL283         -->
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 from288              ( select * from financeproducts_users where FProductsEm_k2 = 0 and userid =#{UserID}) b289 left join290 (select userid,FProductsBuyMoney,FProductsRateEm_k1,sum(FProductsAsRateMoney) as m from financeproducts_rates291                     where userid =#{UserID}292 group by FProductsRateEm_k1 ) a293                     on a.FProductsRateEm_k1=b.fpuid294
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_users306         <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_users330         <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", newDate());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的存储过程

项目中出现的奇怪现象:

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

就是查询不出来,后来粘贴java代码中的参数cfg_appIndexPro到subline中对比数据库中的value 值 cfg_appIndexPro我伙呆:

暂时还不知道怎么会出现这个情况的。

posted on 2017-04-26 17:13 nodeyang 阅读(...) 评论(...) 编辑 收藏

转载于:https://www.cnblogs.com/yangjian-java/p/6769592.html

【代码总结-不定期更新】相关推荐

  1. Android实用代码(不定期更新)

    Android实用代码七段(一) 一抹火焰 整理(不定期更新) 前言 这里积累了一些不常见确又很实用的代码,每收集7条更新一次,希望能对大家有用. 声明: 欢迎转载,但请保留文章原始出处:)  博客园 ...

  2. Liunx上训练模型的常见情况(不定期更新)

    这篇博客用来记录一些Linux上后台训练机器学习模型的时候可能用到的简短的代码(不定期更新) 目录: 后台执行python训练脚本 查看训练时占用的资源 中途停止模型的训练 1.后台执行python训 ...

  3. [刷题记录] luogu网络流24题 及 网络流心得体会 及 经典模型不定期更新

    文章目录 信息汇总表格 飞行员配对方案问题 分配问题 运输问题 数字梯形问题 最小路径覆盖问题 魔术球问题 圆桌问题 试题库问题 深海机器人问题 航空路线问题 火星探险问题 太空飞行计划问题 方格取数 ...

  4. React性能优化记录(不定期更新)

    React性能优化记录(不定期更新) 1. 使用PureComponent代替Component 在新建组件的时候需要继承Component会用到以下代码 import React,{Componen ...

  5. net core 小坑杂记之配置文件读取(不定期更新)

    其实很早就想写了,原想等积累差不多了再写的,但是发现遇到一个当时记下效果会比较好,所以就不定期更新这个系列了,后面获取会整个整理一下. 此篇记载net core入门时踩的一些坑,网上教程太少了,也不规 ...

  6. 不定期更新的IDEA功能整理

    目录 不定期更新的IDEA功能整理 idea 命令 Preferences 和 Project Structure Keymap HTTP Proxy Postfix Completion 插件 插件 ...

  7. 【不定期更新】游戏开发中的一些良好习惯与技术技巧

    平时programing时想到和积累的一些小技巧,在这里写成一篇日志,欢迎拍砖. <技巧一> 使用二进制位移运算来进行乘数是2的幂的简单整数乘法(除法),因为所有的数据在计算机中都是以二进 ...

  8. vscode html注释快捷键_最强编辑器 VSCode 系列之插件推荐【不定期更新】

    [TOC] 前言 emsp;如果你还不知道这款最强编辑器的话,查看本站热门文章,最强编辑器 VSCode 系列之入门简介. 通用 无论你用什么语言,都会用得到的插件. Project Manager ...

  9. 【HIT-CN/不定期更新】计网NFAQ

    咦,你问为什么是NFAQ(Not Frequently Asked Questions)?我也不知道xD 因为本人不用CSDN写文,所以不用找以前的博客了,不存在的.(实际上是因为懒,所以都不发博客吧 ...

最新文章

  1. 3w字带你揭开WebSocket的神秘面纱~
  2. hdu1846巴什博弈(java)
  3. java中使用request,application,session,cookie对象
  4. tomcat关闭和重启
  5. 缓存应用--Memcached分布式缓存简介(二)
  6. redis——实战关注
  7. netpref 使用_使用PerfView监测.NET程序性能(转发)
  8. 使用百度编辑器--ueditor,后台接收提交编辑的内容,HTML不见了, 赋值不了,赋值之后,html暴露出来了??...
  9. Audition生成扫频信号(四十)
  10. yaf index.php,yaf框架访问路由为什么始终访问INDEX下的INDEX控制器下的INDEX方法
  11. 基本操作?这46个 Linux 面试常见问题送给你
  12. 英文单词 modal 模态,flex里取模糊之意
  13. gxworks2使用指令手册_三菱编程软件 GX Works2 操作手册简单工程篇中文高清版
  14. Vbs 脚本编程简明教程之一
  15. 工作感想-软件测试工程师
  16. IE提示:无法打开匿名级安全令牌
  17. CentOS7 离线安装fastDFS、jdk1.8、mysql5.7、nginx、libreOffice
  18. 效率是绳,质量是命!——浅析如何运用UML来提高手游团队的绳命质量
  19. [机器学习]模型评估指标:ROC/AUC,KS,GINI,Lift/Gain, PSI 总结
  20. html怎样修改背景图片大小,css中如何设置背景图片的大小?

热门文章

  1. 好的程序员如何写代码
  2. UG二次开发教程(基于NX12.0/VS2015版本)
  3. 智能充电桩开发(一):系统总体设计概述
  4. 1. debian telnet安装
  5. Layer.js——强大的弹出框
  6. 最新 c4d mac 中文版
  7. 实况摄像头,“偷窥” 世界美景!
  8. FANUC机器人负载手动设置方法参考
  9. scala spark hbase 操作案例
  10. 计算机原理及接口技术题目,微机原理及接口技术-习题答案