2017-07-07 21:23
/**
* 生成条形码规则为 Code128
*
* @param contents 数据
* @param width
* @param height
* @param showText 是否显示数据
* @return BufferedImage
*/
public BufferedImage createCode128(String contents, int width, int height, boolean showText) {
Hashtable hints = new Hashtable();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.MARGIN, 16); //边距,条形码静区也叫空白区,是条码左右的空白部分,好让扫描设备做好准备,如果没有静区会导致无法读取条码。
int defaultFontSize = 16;
try {
if (showText && height < (4 + defaultFontSize)) {
height += defaultFontSize;
}
BitMatrix bitMatrix = new Code128Writer().encode(contents, BarcodeFormat.CODE_128, width, height, hints);
BufferedImage bufferedImage = me.toBufferedImage(bitMatrix);
if (showText) {
height = bufferedImage.getHeight();
width = bufferedImage.getWidth();
Graphics g = bufferedImage.getGraphics();
Font textFont = new Font("TimesRoman", Font.BOLD, defaultFontSize);
g.setFont(textFont);
//得到当前的font metrics
FontMetrics fm = g.getFontMetrics();
int fnFontHeight = fm.getHeight();
int posX = (width - fm.stringWidth(contents)) / 2;
int posY = height - fnFontHeight;
g.setColor(Color.white);
g.fillRect(0, posY, width, height);//创建文字显示区域
g.setColor(Color.black);
int fontPosY = height - (fnFontHeight - defaultFontSize) / 2;//计算文字写入位置
g.drawString(contents, posX, fontPosY);
g.dispose();
bufferedImage.flush();
}
return bufferedImage;
} catch (WriterException e) {
log.error("生成Code128出错", e);
}
return null;
}
2016-10-11 21:21
@JFinal 谢谢指导。
分享完整的Handler代码
@Override
public void configHandler(Handlers me) {
String skipedUrlRegx = PropKit.get("except_urlpattern");
Handler handler1 = StrKit.isBlank(skipedUrlRegx) ? new UrlSkipHandler("\\.css$|\\.js$|\\.jpg$|\\.gif$|\\.png$|\\.gzjs$|\\.gzcss", false) : new UrlSkipHandler(skipedUrlRegx, false);
me.add(handler1);
me.add(new ContextPathHandler("basePath"));
// me.add(new ViewAttrHandler());
me.add(new RootHandler());
}
/**
* 实现对所有的请求都返回相同的页面
*
* @author 张宗荣
*
*/
public class RootHandler extends Handler {
@Override
public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
String[] urlPara = { null };
Action action = JFinal.me().getAction(target, urlPara);
if (action == null) {
// 先将 target 存起来,可在 controller 中通过getAttr("target")得到
request.setAttribute("target", target);
// 直接转发到 Controller.index();
next.handle("/_tools/notify", request, response, isHandled);
} else {
next.handle(target, request, response, isHandled);
}
}
}