【代码总结-不定期更新】
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 //读取配置文件 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 }
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 }
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 }
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"})
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")); } }
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 小于号 < < 11 大于号 > > 12 和 & & 13 单引号 ' ' 14 双引号 " " 15 2、使用<![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 > 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 > 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常用写法
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>
项目中出现的奇怪现象:
BaseConfig appProConfig = baseConfigService.selectByParam("cfg_appIndexPro");
就是查询不出来,后来粘贴java代码中的参数cfg_appIndexPro到subline中对比数据库中的value 值 cfg_appIndexPro:我伙呆:
暂时还不知道怎么会出现这个情况的。